The idea is to come up with an average slope for a curve, or trend line for a given lookback window.
Would like -90 degrees to +90 degrees. Of course, just stretching a graph horizontally would change those numbers.
Edited 2017-06-17
Edit 2017-12-22 Backtest on this date below has an example without the loop, multiple stocks to history and slopes all at once.
'''
Slope calculation using statsmodels.api
'''
import statsmodels.api as sm
def initialize(context):
context.sids = symbols('TSLA', 'AAPL')
def handle_data(context, data):
for s in context.sids:
slp = slope(data.history(s, 'close', 60, '1m').dropna())
if slp > .05:
print slp
order_target_percent(s, .5)
elif slp < -.05:
order_target(s, 0)
def slope(in_):
return sm.OLS(in_, sm.add_constant(range(-len(in_) + 1, 1))).fit().params[-1] # slope