I want to find out how long it has been since a cross-over of two moving averages. Inputs would be (data, context, ma_short, ma_long) where the last two are each a series of moving averages. Here is an example of what I want to accomplish, but I think it can be written a whole lot better.
# Gather historical prices (last 400 days)
prices = history(400, '1d', 'price')
# Calculate moving averages
ma_short = talib.EMA(prices[context.stock], timeperiod=20)
ma_long = talib.EMA(prices[context.stock], timeperiod=50)
# Determine how many days since the last cross-over
last_crossover_time_difference = time_since_last_crossover(context,data,ma_short,ma_long)
def last_crossover_days(data, context, ma_short, ma_long):
for i in range[1,399]:
if ma_short[-i] > ma_long[-i] and ma_short[-(i+1) < ma_long[-(i+1)]:
# Return time difference from today to the last crossover
return ma_short[-1] - i.index
elif ma_short[-i] < ma_long[-i] and ma_short[-(i+1) > ma_long[-(i+1)]:
# Return time difference from today to the last crossover
return ma_short[-1] - i.index
else:
continue
BTW, with the help of James, I created a similar time-based function that returned "time since price was higher".