There was an error (line 55) running the below code. Could someone help me on the error? Thanks.
from quantopian.algorithm import attach_pipeline,pipeline_output
from quantopian.pipeline.data import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage
from quantopian.pipeline import Pipeline
from quantopian.pipeline.filters.morningstar import Q1500US
def initialize(context):
schedule_function(my_rebalance,date_rules.week_start(),time_rules.market_open(minutes = 1))
schedule_function(my_record_vars,date_rules.every_day(),time_rules.market_close())
my_pipe = make_pipeline()
attach_pipeline(my_pipe,"my_pipeline")
def make_pipeline():
base_universe = Q1500US()
mean_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],window_length = 10, mask = base_universe)
mean_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],window_length = 30, mask = base_universe)
percent_difference = (mean_10 - mean_30)/ mean_10
shorts = percent_difference.top(25)
longs = percent_difference.bottom(25)
securities_to_trade = (shorts | longs)
pipe = Pipeline(
{"longs":longs,
"shorts":shorts
},
screen = securities_to_trade
)
return pipe
def my_compute_weight(context):
long_weight = 0.5/len(context.longs) if len(context.longs) > 0 else 0
short_weight = 0.5/len(context.shorts) if len(context.shorts) > 0 else 0
return (long_weight,short_weight)
def before_trading_start(context, data):
context.output = pipeline_output("my_pipeline")
context.longs = context.output[context.output["longs"]].index.tolist()
context.shorts = context.output[context.output["shorts"]].index.tolist()
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.longs:
if data.can_trade(security):
order_target_percent(security,context.long_weight)
for security in context.shorts:
if data.can_trade(security):
order_target_percent(security,context.short_weight)
def my_record_vars(context,data):
longs=shorts=0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs +=1
elif positions.amount < 0:
shorts +=1
record(leverage = context.account.leverage, long_count = longs, short_count= shorts)