I have a list of floating point numbers and I want to generate another list of period returns from my first list.
This is a run of the mill implementation (not tested - and OBVIOUSLY no error checking/handling):
a = [100,105,100,95,100]
def calc_period_returns(values, period):
output = []
startpos, endpos = (period, len(values)-1)
while True:
current = values[startpos]
previous = values[startpos-period]
ret = 100*((current-previous)/(1.0*previous))
output.append(ret)
startpos += period
if startpos > endpos:
break
return output
calc_period_returns(a,1)
# Expected output:
# [5.0, -4.7619047619047619, -5.0, 5.2631578947368416]
Is there a more pythonic way of doing this - perhaps using list comprehension and maps?
First: work out the difference (increase) between the two numbers you are comparing. Then: divide the increase by the original number and multiply the answer by 100. % increase = Increase ÷ Original Number × 100.
Subtract the original value from the new value, then divide the result by the original value. Multiply the result by 100. The answer is the percent increase.
I don't know how large your list of numbers is going to be, but if you are going to process large amounts of numbers, you should have a look at numpy. The side effect is that calculations look a lot simpler.
With numpy, you create an array for your data
>>> import numpy as np
>>> a = np.array([100,105,100,95,100], dtype=float)
and work with arrays as if they were simple numbers
>>> np.diff(a) / a[:-1] * 100.
[ 5. -4.76190476 -5. 5.26315789]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With