Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
error that I cannot solve

Hi,
I have been having this error and sent "feedback" to Q with no response for days. Could anyone help me understand why I am getting below error message?

Something went wrong. Sorry for the inconvenience. Try using the built-in debugger to analyze your code. If you would like help, send us an email.
KeyError: Equity(1476, symbol='CHB', asset_name='CHAMPION ENTERPRISES INC', exchange='NEW YORK STOCK EXCHANGE', start_date=Timestamp('1993-01-04 00:00:00+0000', tz='UTC'), end_date=Timestamp('2009-11-13 00:00:00+0000', tz='UTC'), first_traded=None)
There was a runtime error on line 102.

When i try to run below algo between 12/20/2008 and 01/10/2009, for instance, it creates error. However it can create error in any other time frame, or sometimes it doesn't. So I think it has to do with which securities end up getting involved. I couldn't even tell if data issue or time frame issue.

Thank you so much.

3 responses

by the way using
longs_30_90 = longs_30_90.dropna()
doesn't fix the problem.

the securities you get are quite excotic at times so you have to check their existence in data and if you want to be thorough wether price exists in data[stock]

This works for me

import pytz  
import talib  
import numpy as np  
import pandas as pd  
from datetime import datetime, timedelta


def initialize(context):

    context.stocks = []  
    set_universe(universe.DollarVolumeUniverse(floor_percentile=80.0 ,ceiling_percentile=82.5))  
    context.other_stocks = symbols('AET', 'AMGN', 'ADI', 'CSCO', 'IP', 'KMB', 'PRU', 'PEG', 'SLB', 'SYK', 'SPY')  
    context.nogo = ['SSO']

    context.testStopday = None  
    context.StocksToOrder = 15.0  
    context.StocksToKeep = 30.0  
    context.rebalance_interval = 200  
    context.time_steps = 0  
def handle_data(context, data):  


    priceHistory = history(90, '1d', 'price')  
    last_5_day_mean = priceHistory.tail(5).mean()  
    last_10_day_mean = priceHistory.tail(10).mean()  
    last_30_day_mean = priceHistory.tail(30).mean()  
    last_90_day_mean = priceHistory.tail(90).mean()  
    CurrentPrice = priceHistory.tail(1).mean()  
    diff_30_90 = (last_30_day_mean - last_90_day_mean)/ CurrentPrice  
    diff_10_30 = (last_10_day_mean - last_30_day_mean) / CurrentPrice  
    diff_5_30 = (last_5_day_mean - last_30_day_mean) / CurrentPrice  
    longs_30_90 = diff_30_90[diff_30_90 > 0.01]  
    longs_10_30 = diff_10_30[diff_10_30 > 0.01]  
    longs_5_30 = diff_5_30[diff_5_30 > 0.01]

    if longs_30_90 is not None and longs_10_30 is not None:  
        longsIndex = longs_30_90.index.intersection(longs_10_30.index)  
        longsSeries = longs_10_30[longsIndex]

        #eliminate stocks that are no longer traded...  
        for stock in longsSeries.index:  
            if stock.security_end_date < get_datetime():  
                if stock.symbol not in context.nogo:  
                    context.nogo.append(stock.symbol)  

        longsSeries.sort(ascending=False) #  
        keepsSeries = longsSeries  
        longsSeries_length = min(context.StocksToOrder, len(longsSeries))  
        keepsSeries_length = min(context.StocksToKeep, len(keepsSeries))  
        longs_weight   = 1.0 / longsSeries_length   if longsSeries_length   != 0 else 0  
        keeps_weight   = 1.0 / keepsSeries_length   if keepsSeries_length   != 0 else 0  
        longsSeries = longsSeries.iloc[:longsSeries_length] if longs_weight   != 0 else None  
        keepsSeries = keepsSeries.iloc[:keepsSeries_length] if keeps_weight   != 0 else None  
 #----------------------------------------------------------------------------------------------------------------------  
    open_orders = get_open_orders()  
    Long_counter = 0.0  
    #print context.portfolio.positions[data].sid  
    if longsSeries is not None and not open_orders:  
        if len(context.portfolio.positions) != 0:  
            for stock in context.portfolio.positions:  
                if context.portfolio.positions[stock].amount > 0:  
                    Long_counter = Long_counter + 1  
                    #log.info( 'long {A}; Shares {B}; price {C}'.\  
                    #         format(A=stock, B =context.portfolio.positions[stock].amount, C=data[stock].price))  
                    if stock not in longs_10_30:  
                        if stock.symbol not in context.nogo:  
                            order_target_percent(stock, 0)  
                            Long_counter = Long_counter -1  
                    currPrice = context.portfolio.positions[stock].last_sale_price  
                    costBasis = context.portfolio.positions[stock].cost_basis  
                    changePct = currPrice/costBasis - 1  
                    if changePct < -0.05 and stock in data and 'price' in data[stock]:  
                        order_target_percent(stock, 0)  
                        Long_counter = Long_counter -1  
                        context.nogo.append(stock.symbol)  
            for stock in longsSeries.index:  
                if stock not in context.portfolio.positions:  
                    if Long_counter < context.StocksToOrder:  
                        if stock is not symbol('SPY'):  
                            if stock.symbol not in context.nogo and stock in data and 'price' in data[stock]:  
                                order_target_percent(stock, 1.0/context.StocksToOrder)  
                                Long_counter = Long_counter + 1  
            context.time_steps = context.time_steps + 1  
            if context.time_steps == context.rebalance_interval :  
                context.time_steps = 0  
                order_target_percent(symbol('SPY'), - Long_counter / context.StocksToOrder)  
    #----------------------------------------------------------------------------------------------------------------------  
    '''  
    this is a logic to have the algo to stop at a certain date.  
    '''  
    if context.testStopday == None:  
        context.testStopday = get_datetime()  
    # in case skipping holidays  
    if context.testStopday < get_datetime():  
        context.testStopday = get_datetime()  
    if get_datetime() == context.testStopday:  
        context.testStopday = context.testStopday + timedelta(days = 97)  
        '''  
        context.stocks = [str(sid.symbol) for sid in data]  
        print  ', '.join(context.stocks)  
        '''  
        if context.testStopday.weekday()==4:  
            context.testStopday = context.testStopday + timedelta(days = 3)  
        else:  
            context.testStopday = context.testStopday + timedelta(days = 1)  
    #----------------------------------------------------------------------------------------------------------------------       

    #record(NXPI_diff_10_30 = diff_10_30[symbol('JUNO')])  
    #record(changePct = context.portfolio.positions[stock].last_sale_price/costBasis = context.portfolio.positions[stock].cost_basis - 1)  
    #----------------------------------------------------------------------------------------------------------------------  
    #this needs to executed at the very first time...  
    if len(context.portfolio.positions) == 0:  
        for stock in data:  
            # If the security instead exists in buys index, buy  
            if longsSeries is not None and stock in longsSeries.index:  
                if stock is not symbol('SPY'):  
                    order_target_percent(stock, 1.0/context.StocksToOrder)


Wow,
That did the fix. Thank you so much!