Hi Vlad, the code you have provided has been incredibly helpful. Do you know if there are any limitations with using the talib.SMA function for multiple futures? I have gotten a dimension error when trying to add more symbols. This is the code I'm currently using but would like to add more symbols to this backtest to see how it performs with other futures.
import talib
from zipline.utils.calendars import get_calendar
EARLY_ROLL_DAYS = 14
def initialize(context):
schedule_function(trade, date_rules.every_day(), time_rules.market_open())
def trade(context,data):
open_orders = get_open_orders()
context.corn = continuous_future('CN', offset = 0, roll = 'calendar', adjustment='mul')
ma_f = 10; ma_s = 20; days_rule = 3; bars = ma_s + days_rule
prices = data.history(context.corn, 'close', bars, '1d').bfill()
mavg_f = talib.SMA( prices[-ma_f-days_rule:], ma_f)[-days_rule:]
mavg_s = talib.SMA( prices[-ma_s-days_rule:], ma_s)[-days_rule:]
diff = mavg_f - mavg_s
primary = data.current(context.corn, 'contract')
if (diff[-1] > 0 and diff[-2] > 0 and diff[-3] > 0) and context.portfolio.positions[primary].amount == 0 and context.corn not in open_orders:
order_target_percent(primary, 1.)
elif (diff[-1] < 0 and diff[-2] < 0 and diff[-3] < 0) and context.portfolio.positions[primary].amount > 0:
order_target_percent(primary, 0.)
if (diff[-1] < 0 and diff[-2] < 0 and diff[-3] < 0) and context.portfolio.positions[primary].amount == 0 and context.corn not in open_orders:
order_target_percent(primary, -1.)
elif (diff[-1] > 0 and diff[-2] > 0 and diff[-3] > 0) and context.portfolio.positions[primary].amount < 0:
order_target_percent(primary, 0.)