I am attempting to create a trailing data frame containing the mean normalized price of the securities in the universe for some look back period. i.e. on every day in the data frame the price for each security will be the price of the security on that day divided by the mean of x previous days on that day.
currently what i have is something like what I've included below but I'm missing some key insight somewhere... probably a matter of not knowing my way around python all that well.
from collections import defaultdict, deque
from functools import partial
import numpy as np
def initialize(context):
context.sid1 = sid(23112) #Chevron
context.lookbackPeriod = 30
context.normalizedPrices = defaultdict(partial(deque, maxlen=context.lookbackPeriod))
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
price_history = history(bar_count=30, frequency='1d', field='price')
normalizedPrice = data[context.sid1].price/price_history[context.sid1].mean()
context.normalizedPrices[context.sid1].append(normalizedPrice)
stock_series = np.array(context.normalizedPrices[context.sid1])
record(price=normalizedPrice)