Numerical Python question

Sean Moore smm at ibl.bm
Sun Oct 12 20:45:27 EDT 2003


"Neil Hodgson" <nhodgson at bigpond.net.au> wrote in message news:<S0bib.147688$bo1.23845 at news-server.bigpond.net.au>...
> 2mc:
> 
> > Assume an array in Numerical Python, the contents of which are the
> > daily open, high, low, and last prices of the DOW Jones Industrial
> > Average for its entire history.  How would one iterate throughout the
> > entire array calculating the 10 day average of daily high price or the
> > daily low price?
> 
>    The common technique for moving averages is to maintain a single
> accumulator value over the last n points. For each new point, remove (by
> subtracting) the value at the beginning of the window and add in the value
> at the end of the window. The value of the accumulator divided by n is the
> moving average. You will need to define what you want as output, if any,
> before the nth point.
> 
>    Neil


While this is common in c/c++, it is not the most efficient way in
python when you have numpy around to do the loops in c if used correctly.

I use the following setup

from Numeric import array, cumsum

def movavg(s, n):
    ''' returns an n period moving average for the time series s
       
        s is a list ordered from oldest (index 0) to most recent (index -1)
        n is an integer

        returns a numeric array of the moving average
    '''
    s = array(s)
    c = cumsum(s)
    return (c[n-1:] - c[:-n+1]) / float(n)

This should run in near constant time with regard to n (of course,
O(n) to the length of s).  At least one person has said yuk becuase
of the numerical issue of losing precission in the cumsum, but for
small n's, and values like you will see in stock prices and indices,
I don't think this is too much of a problem.  Someone may have 
a more numerically stable version, but then you could just implement
the c-code version and wrap it for python.

Sean




More information about the Python-list mailing list