Here is a quick snippet that can help you determine how long it has been since the price was higher (or lower) than today.
# Get the last X days of prices for every stock in our universe.
closes = history(252, '1d', 'close_price').dropna(axis=1)
highs = history(252, '1d', 'high').dropna(axis=1)
lows = history(252, '1d', 'low').dropna(axis=1)
# How long since the stock was higher than today? (check 252 days)
for days in range(1,252):
# Check historical days, going back one day at a time
test_high = max(highs[stock][-(days+1):-1])
if test_high > highs[stock].iloc[-1]:
# If the history day is higher than today, record # of days
context.Highest_In = days
break
elif days == 251: # Today is the highest high in our history
context.Highest_In = days
# How long since the stock was lower than today? (check 252 days)
for days in range(1,252):
# Check historical days, going back one day at a time
test_low = min(lows[stock][-(days+1):-1])
if test_low < lows[stock].iloc[-1]:
# If the history day is lower than today, record # of days
context.Lowest_In = days
break
elif days == 251: # Today is the lowest low in our history
context.Lowest_In = days
# How long since the stock CLOSED higher than today? (check 252 days)
for days in range(1,252):
# Check historical days, going back one day at a time
test_high = max(closes[stock][-(days+1):-1])
if test_high > closes[stock].iloc[-1]:
# If the history day is higher than today, record # of days
context.Highest_Close_In = days
break
elif days == 251: # Today is the highest close in our history
context.Highest_Close_In = days
# How long since the stock CLOSED lower than today? (check 252 days)
for days in range(1,252):
# Check historical days, going back one day at a time
test_low = min(closes[stock][-(days+1):-1])
if test_low < closes[stock].iloc[-1]:
# If the history day is lower than today, record # of days
context.Lowest_Close_In = days
break
elif days == 251: # Today is the lowest close in our history
context.Lowest_Close_In = days