Numerical Python question
David Mertz
mertz at gnosis.cx
Sun Oct 12 22:52:31 EDT 2003
mcrider at bigfoot.com (2mc) wrote previously:
|I apologize for not making this clear. If an array were to be viewed
|as a spreadsheet, then rows would be individual days and columns would
|be date, open price, high price, etc.
Aside from the speed increase, Numeric provides quite a few handy syntax
tricks. For example, in a crude version of your problem, I first create
the "spreadsheet", and populate it with silly open/close/high/low
prices.
>>> from Numeric import *
>>> stock = zeros((5,20),Int)
>>> stock[0,:] = range(20) # number the days
>>> stock[1,:] = [10]*20 # open price
>>> stock[2,:] = [11]*20 # close price
>>> stock[3,:] = [13]*20 # high price
>>> stock[4,:] = [8]*20 # low price
>>> print stock
[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10]
[11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11]
[13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13]
[ 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8]]
Of course, it is an odd stock that opens, closes, and peaks at the same
price on every day. :-)
Next, I can find a particular average high for a range:
>>> avg_high_day5to15 = sum(stocks[3,5:15])/len(stocks[3,5:15])
>>> avg_high_day5to15
13
You might want to generalize it in a function:
>>> def ten_day_avg_high(beg):
... return sum(stocks[3,beg:beg+10])/len(stocks[3,beg:beg+10])
Which let's you calculate your running averages:
>>> map(ten_day_avg_high, range(20))
[13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13]
This works even near the end, where there are fewer than ten days to
average--we divide by the length of the tail, not by '10' to make sure
of that.
You can work out deviations and other statistics in similar ways.
Yours, David...
--
Keeping medicines from the bloodstreams of the sick; food from the bellies
of the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons. Intellectual
property is to the 21st century what the slave trade was to the 16th.
More information about the Python-list
mailing list