到目前为止,这是我的解决方案。我想知道是否有一些更优雅/有效的方式?
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)
我不确定是否应该在这里使用列表理解。
在某个地方可能有一些功能,但我没有找到它。