Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the most pythonic way to calculate percentage changes on a list of numbers

Tags:

python

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?

like image 893
Homunculus Reticulli Avatar asked Apr 19 '12 10:04

Homunculus Reticulli


People also ask

What is the fastest way to calculate percentage difference?

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.

How do you calculate the percentage change between 3 numbers?

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.


1 Answers

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]
like image 195
pwuertz Avatar answered Sep 28 '22 04:09

pwuertz