これまでのところ、これが私の解決策です。もっとエレガントで効率的な方法があるのだろうか?
import datetime as dt
example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9, dt.datetime(2008, 1, 5) : 12,
dt.datetime(2008, 1, 6) : 15, dt.datetime(2008, 1, 7) : 20, dt.datetime(2008, 1, 8) : 22, dt.datetime(2008, 1, 9) : 25, dt.datetime(2008, 1, 10) : 35}
def calculateMovingAverage(prices, period):
#calculates the moving average between each datapoint and two days before (usually 3! datapoints included)
average_dict = {}
for price in prices:
pricepoints = [prices[x] for x in prices.keys() if price - dt.timedelta(period) <= x <= price]
average = reduce(lambda x, y: x + y, pricepoints) / len(pricepoints)
average_dict[price] = average
return average_dict
print calculateMovingAverage(example, 2)
ここでリスト内包表記を使用する必要があるかどうかはわかりません。
おそらくどこかにこれのための何らかの機能がありますが、私はそれを見つけられませんでした。