Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Question on consecutive bars

I'm new to coding so please bear with me! I'm trying to make a simple test algo that keeps track of the three most recent 5min bars, it's not working the way it should though and I'm not sure why. Here is my code:

close_5m = price_history.resample('5T', closed='right', label='right').last()  

price_list = []  
price_list.append(close_5m)  
print(price_list)  

third_bar = price_list[-1]  
second_bar = price_list[-2]  
first_bar = price_list[-3]

I am getting the error:

IndexError: list index out of range
USER ALGORITHM:21, in handle_data
second_bar = price_list[-2]

I realize that upon the first instance of running def handle_data there is not yet a value for second_bar, how do I get the program to ignore that and just store a value in second_bar once it has an appropriate value after enough time has passed?

3 responses

Just wanted to bump this, no answers yet.

As the error depicts, the length of your array "price_list" is < 1. Thus an error is raised because the index -2 doesn't exist.
I can't help more without the full procedure code.

May be this will help you.

# ---------------------------------------------------------------  
stock, timeframe, timeframe_unit, bars = symbol('SPY'), 5, 'T', 3  
tf_str = str(timeframe) + timeframe_unit  
# ---------------------------------------------------------------  
def initialize(context):  
    for i in range(timeframe, 390, timeframe):  
        schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = i))

def trade(context,data):  
    bars_1m = bars * timeframe

    C_1m = data.history(stock, 'price', bars_1m, '1m')  
    C_timeframe_m = C_1m.resample(tf_str, closed ='right', label='right').last().ffill()

    last_bar = C_timeframe_m[-1]  
    second_bar = C_timeframe_m[-2]  
    first_bar = C_timeframe_m[-3]  
    print(round(last_bar, 2), round(second_bar, 2), round(first_bar, 2))

2018-07-30 06:35 PRINT (281.17, 281.47, 281.47)
2018-07-30 06:40 PRINT (281.08, 281.17, 281.47)
2018-07-30 06:45 PRINT (280.87, 281.08, 281.17)
2018-07-30 06:50 PRINT (281.05, 280.87, 281.08)
2018-07-30 06:55 PRINT (280.86, 281.05, 280.87)
2018-07-30 07:00 PRINT (280.93, 280.86, 281.05)
2018-07-30 07:05 PRINT (280.8, 280.93, 280.86)