Numerical Python question

Colin J. Williams cjw at sympatico.ca
Sun Oct 12 17:41:55 EDT 2003


numarray, the planned successor to Numeric 23, has a function cumsum 
(cumulative sum) which might be helpful.

numarray apears to be largely operational, you might consider it.

Colin W.

Carl Banks wrote:
> Neil Hodgson wrote:
> 
>>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.
> 
> 
> While it might be a common technique, it's also inefficient (for
> Numeric) because you have to iterate over tens of thousands of entries
> in a Python loop.  Fortunately, Numeric provides a much, much faster
> way to do this using slicing.
> 
> Let's say D[i] is the daily high at the end of day i, and N is the
> total number of days in the array.  To calculate 10-day averages, you
> can add ten slices offset by one, then divide the sum by 10:
> 
>     A = zeros(N-9,Float)
>     for j in range(10):
>         A += D[j:N-9+j]
>     A /= 10.0
> 
> Bam, that's it.  Instead of looping over tens of thousands of slices
> of ten, you're now looping over ten slices of tens of thousands.
> 
> This works because, when you add ten slices offset by one, the result
> is that each item contains the sum of ten consecutive numbers from the
> original array.
> 
> 





More information about the Python-list mailing list