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]