Calculating change in percentage between two numbers (Python)
If you haven't been exposed to the pandas library in Python (http://pandas.pydata.org/), you should definitely check it out.
Doing this is as easy as:
import pandas as pd
prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]
price_series = pd.Series(prices)
price_series.pct_change()
Though definitely not the most elegant way, if you'd like to define a function it would look something like this:
def pctc(Q):
output = [0]
for i in range(len(Q)):
if i > 0:
increase = Q[i]-Q[i-1]
percentage = (increase/Q[i]) * 100
output.append(percentage)
return(output)
There's probably even a better way to do that function, but it's clear at least. :))
Try this:
prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]
for a, b in zip(prices[::1], prices[1::1]):
print 100 * (b - a) / a
Edit: If you want this as a list, you could do this:
print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])]