Numerical Python question

Carl Banks imbosol at aerojockey.invalid
Sun Oct 12 14:59:18 EDT 2003


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.


-- 
CARL BANKS                   http://www.aerojockey.com/software

As the newest Lady Turnpot descended into the kitchen wrapped only in
her celery-green dressing gown, her creamy bosom rising and falling
like a temperamental souffle, her tart mouth pursed in distaste, the
sous-chef whispered to the scullery boy, "I don't know what to make of
her." 
          --Laurel Fortuner, Montendre, France 
            1992 Bulwer-Lytton Fiction Contest Winner




More information about the Python-list mailing list