Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
KeyError: 'shorts' . Please Help

I keep getting this error and i have no idea how to fix it . KeyError: 'longs' There was a runtime error on line 22.

def initialize(context):
schedule_function(my_rebalance,date_rules.week_start(),time_rules.market_open(hours=1))
my_pipe= make_pipeline()
attach_pipeline(my_pipe,'my_pipeline')

def my_rebalance(context,data):
for security in context.portfolio.positions:
if security not in context.longs and security not in context.shorts and data.can_trade(security):
order_target_percent(security,0)

 for security in context.shorts:                               <<<<==== error here  
    if data.can_trade(security):  
        order_target_percent(security,context.short_weight)  
  for security in context.longs:                                <<<<<<===== error here  
    if data.can_trade(security):  
        order_target_percent(security,context.long_weight)  

def my_compute_weights(context):
if len(context.longs)==0:
long_weight=0
else:
long_weight= 0.5/len(context.longs)

if len(context.shorts)==0:  
    long_weight=0  
else:  
    short_weight= -0.5/ len(context.shorts)  
return(long_weight, short_weight)  

def before_trading_starts(context,data):
context.output= pipeline_output('my_pipeline')
#long
context.longs= context.output[context.output['longs']].index.tolist()
#short
context.shorts= context.output[context.output['shorts']].index.tolist()

context.long_weight, context.short_weight= my_compute_weights(context)  

def make_pipeline():

#U  
4 responses

Could you attach a backtest of your algo? It makes it much easier to help debug. Even if a backtest generates an error, you should still be able to attach it to a post. Simply click the "Attach" dropdown menu in the upper right corner of the reply text box. Choose "backtest" then choose the desired algo and backtest.

This is probably something simple but much easier to troubleshoot this way.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

I imagine that is something very simple but I cannot find the error.

Thanks for including the algo. Yup, some simple things. Several typos...

# original code  
def before_trading_starts(context,data):

# misspelled function name (note the s)  
def before_trading_start(context,data):

Also, in make_pipeline...

# original code  
    return Pipeline(columns={  
        'longs:':longs,  
        'shorts:':shorts,  
        'percent diff:':percent_difference  
    },screen=securities_to_trade)

# had colons included in the names. This can work but then need to use the colons when referencing the field.  
# probably best not to use special characters like this  
    return Pipeline(columns={  
        'longs': longs,  
        'shorts': shorts,  
        'percent diff': percent_difference  
    },  
    screen=securities_to_trade)

Finally, in my_compute_weights a copy/paste mistake...

# original code  
    if len(context.shorts)==0:  
        long_weight=0  
    else:  
        short_weight= -0.5/ len(context.shorts)

# long_weight should be short_weight  
    if len(context.shorts)==0:  
        short_weight=0  
    else:  
        short_weight= -0.5/ len(context.shorts)

Attached is the running algo. Good luck.

thank you very much Dan!!
I you helped me a lot!!!