Back to Community
Runtime exception: IndexError: list index out of range

Hi everyone,

I am new to Python and Quantopian. Could someone help me? In my code, myStocks is a list that contains a series of securities which are dictionary objects. Why do I keep getting an error when I simply want to print(myStocks[index]). Is there a way to access each individual security in the list?

Thank you,

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
import talib  
import numpy as np  
import pandas as pd

def before_trading_start(context):  
    marketCap = get_fundamentals(  
        query(  
            fundamentals.valuation.market_cap    #Make a query for marketCap fundamental data  
        )  
        .filter(  
            fundamentals.valuation.market_cap < 100000000    #Filer companies which marketCap < 100 millions  
        )  
        .order_by(  
            fundamentals.valuation.market_cap.desc()    #Order and limit number of companies found  
        )  
        .limit(10)  
    )  
    #Update universe with the list of symbols  
    update_universe(marketCap.columns.values)

def initialize(context):  
    context.myUniverse = []    #Create an empty list to store stock symbols  
    context.date = None

# Will be called on every trade event for the securities you specify.  
def handle_data(context, data):  
    #Filter stock was last close below $5.0  
    for stock in data:  
       if data[stock].close_price <= 5.0:  
            context.myUniverse.append(stock)  
    myStocks = context.myUniverse  
    print(myStocks[0])  
2 responses

Never mind. I have figured it out :). I added the following 2 lines at the end.

myStocks = context.myUniverse    #myStocks now is a list containing security objects  
for i in range(len(myStocks)):  
     print(myStocks[i].symbol)    #Look up Security object to access available attribute such as sid, symbol  

I believe you may also loop through by using:

for sec in data.keys():  

this will loop through each security in your universe