Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Cannot Access Elements of A List - I can only get the first and last elements

I am currently making an algorithm that creates a list of stocks, and then creates a corresponding list containing the "gap percentages" of each stock (ie, the percentage difference between yesterday's closing price and today's opening price).

I can access the first and last elements of this "gap percentages" list, but I get the following error when I try to access any other element: "Runtime exception: IndexError: list index out of range." Also, by getting the length of the list using len(), I have confirmed that the list of gap percentages is over 800. So why can't I access the other elements in the list?

Here is my code:

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
import math  
import numpy as np  
import pandas as pd  
def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(90.0, 100.0))

# Will be called on every trade event for the securities you specify.  
def handle_data(context, data):  
    # Implement your algorithm logic here.  
    # Reset All Variables for each day  
    context.stocks = []  
    context.gaps = []  
    context.stock_data = []  
    closing_price_history = 0  
    opening_price_history = 0  
    total_number_of_stocks = 0  
    closing_bar = 0  
    opening_bar = 0  
    gap_percentage = 0  
    #Create list of stocks  
    context.stocks = [str(sid.symbol) for sid in data]  
    #Yesterday's closing price and today's opening price  
    closing_price_history = history(bar_count=2, frequency='1d', field='price')  
    opening_price_history = history(1, '1d', 'open_price')  
    #add the gap percentages for each stock to the list context.gaps  
    for s in data:  
        closing_bar = closing_price_history[s][-2]  
        opening_bar = opening_price_history[s][-1]  
        gap_percentage = (opening_bar - closing_bar)/(closing_bar) * 100  
        if math.isnan(gap_percentage):  
            gap_percentage = 0  
        context.gaps.append(gap_percentage)  
    print context.gaps  
    print context.gaps[0]  
    print context.gaps[-1]  
    print context.gaps[1]  
1 response

An alternative would be to store the gaps in a dict or a series and access them with iteritems(). Here's a skeleton example:

import pandas as pd  
from random import random

def initialize(context):  
    context.secs = [sid(24), sid(8554)]

def handle_data(context, data):  
    gaps = {}  
    for sec in data:  
        gap = random()  # replace with real computations  
        gaps[sec] = gap

    # gaps = pd.Series(gaps)  # optional:  convert dict to Series

    lines = []  
    for sec, gap in gaps.iteritems():  
        lines.append('{sym} {gap}'.format(sym=sec.symbol, gap=gap))  
    output = '\n{lines}'.format(lines='\n'.join(lines))  
    log.info(output)  

Sample output:

2011-01-04 handle_data:20 INFO  
AAPL 0.459880189516  
SPY 0.837693684464  
2011-01-05 handle_data:20 INFO  
AAPL 0.918546600604  
SPY 0.400735692204