Back to Community
Error when rolling futures

Hello everyone,

When I run the below codes, i get "IndexError:list index out of range".
The funny thing is, this happens only if the backtest date ends after 09/17/2018.
If the end date is before 09/17/2018, there is no error.

Can someone please advise?

Thanks in advanced.

from zipline.utils.calendars import get_calendar

def initialize (context):  
    context.ES = continuous_future('ES', offset=0, roll='calendar', adjustment='mul')  
    context.GC = continuous_future('GC', offset=0, roll='calendar', adjustment='mul')

    context.futures = [context.ES, context.GC]  
    context.futures_calendar = get_calendar('us_futures')

    schedule_function(first_purchase, date_rules.month_start(), time_rules.market_open())  
    schedule_function(roll, date_rules.every_day(), time_rules.market_open())

def first_purchase(context, data):  
    for x in context.futures:  
        futures_contract = data.current(x, 'contract')  
    order_target(futures_contract, 2)

    print context.portfolio.portfolio_value

def roll(context, data):  
    today = get_datetime('US/Eastern') 

    for x in context.futures:  
        contract_chain = data.current_chain(x)  
        futures_quantity = context.portfolio.positions[contract_chain[0]].amount  
        distance = context.futures_calendar.session_distance(today, contract_chain[0].auto_close_date)

        if distance == 1:  
            order_target(contract_chain[0], 0)  
            order_target(contract_chain[1], futures_quantity)