I cloned a ROC algorithm from here (www.quantopian.com/posts/roc-rate-of-change), hoping to edit it to do the following:
Start Long SPY
If SPY’s ROC (5-day) > 5%, Sell SPY long position and Buy SH
If SPY’s ROC (5-day) <-5%, Sell SH long position and Buy SPY
Can someone please help a newbie fix his mistakes? Many thanks!
import talib
def initialize(context):
context.stock1 = symbol('SPY')
context.stock2 = symbol('SH')
def handle_data(context, data):
# history needs to have at least N+1 days for ROC timeperiod=N
prices = history(51, '1d', 'close_price')
# this applies ROC to all stocks in the universe
rate_of_change = prices.apply(talib.ROC, timeperiod=5).iloc[-1]
# compare for our stocks
if rate_of_change[context.stock1] > 5:
order_target_percent(context.stock2, 1)
if rate_of_change[context.stock1] <-5:
order_target_percent(context.stock1, 1)
else:
order_target_percent(context.stock1, 1)