Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
PLease somebody debugg . Line 25 shows an error, 'context.long' not defined

from quantopian.algorithm import attach_pipeline,pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume,SimpleMovingAverage
from quantopian.pipeline.filters.morningstar import Q1500US
from quantopian.pipeline.data import morningstar

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

def 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.0)

for security in context.longs:  
    if data.can_trade(security):  
        order_target_percent(security,context.long_weights)  

for security in context.shorts:  
    if data.can_trade(security):  
        order_target_percent(security,context.short_weights)

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

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

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

#short  
context.shorts= context.output[context.output['shorts']].index.tolist()  
context.long_weights,context.short_weights= my_compute_weights(context)  

def make_pipeline():
#Universe Q1500US()
base_universe= Q1500US()
#Energy sector
sector= morningstar.asset_classification.morningstar_sector_code.latest
energy_sector=sector.eq(309)
#combine the mask
base_energy= base_universe & energy_sector
# dollar volume 30 days
dollar_volume= AverageDollarVolume(window_length=30)
# grab top 5% of stocks
high_dollar_volume= dollar_volume.percentile_between(95,100)
#combine filters
top_five_base_energy= base_energy & high_dollar_volume
# 10day mean close
mean_10= SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=10, mask=top_five_base_energy)
# 30 Day Mean close
mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=30, mask=top_five_base_energy)
#Percent difference
percent_diff=(mean_10-mean_30)/mean_30
#List of shorts
shorts= percent_diff < 0
#List of longs
longs= percent_diff > 0
#Final mask/filter for anything in shorts and longs
securities_to_trade= (shorts| longs)
#retrun pipleine
return Pipeline(columns={'longs':longs,'shorts':shorts,'perc_diff':percent_diff},screen=securities_to_trade)

6 responses

It would be helpful if you could format the code better

Hi Yash,

You can share the algo using 'the Attach' drop-down (upper right hand corner), and then choosing 'Backtest.' You'll have much better chance at getting help that way I reckon. Just remove any 'secret sauce' stuff first if there's something you don't want to share.

Try pipline output calculation in "rebalance"
Something like this:

def rebalance(context,data):  
    output = pipeline_output('my_pipeline')  
    longs = output[output['longs']].index  
    shorts = output[output['shorts']].index  
    long_weights = 0.5/ len(longs) if len(longs) > 0 else 0  
    short_weights = 0.5/ len(shorts) if len(shorts) > 0 else 0

    print (long_weights, short_weights)

    for sec in context.portfolio.positions:  
        if sec not in longs and sec not in shorts and data.can_trade(sec):  
            order_target_percent(sec, 0.0)

    for sec in longs:  
        if data.can_trade(sec):  
            order_target_percent(sec, long_weights)  

    for sec in shorts:  
        if data.can_trade(sec):  
            order_target_percent(sec, short_weights) 

    record(leverage = context.account.leverage)  

I have attached the backtest . Kindly help now.

I have commented lines 19-54 and placed my code above instead...
It is working for me.

Thank you.