So, I've been trying my hand at pipelne trading. Here is my code:
import numpy as np
from zipline.api import( symbol,
order_target_percent,
schedule_function,
date_rules,
time_rules,
pipeline_output,
attach_pipeline
)
from zipline.pipeline import Pipeline
from zipline.pipeline import CustomFilter
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.factors import SimpleMovingAverage, AverageDollarVolume
def initialize(context):
schedule_function(rebalance, date_rules.week_start(), time_rules.market_open(hours=1))
my_pipe = make_pipeline(context)
attach_pipeline(my_pipe,name='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)
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_compute_weights(context):
if len(context.longs) == 0:
long_weight=0
else:
long_weight = 0.5 / len(context.longs)
if len(context.shorts)==0:
short_weight=0
else:
short_weight = -0.5 / len(context.shorts)
return (long_weight,short_weight)
def before_trading_start(context,data):
context.output = pipeline_output('pipeline')
context.shorts = context.output[context.outputs['shorts']].index.tolist()
context.longs = context.output[context.outputs['longs']].index.tolist()
context.long_weight, context.short_weight = my_compute_weights(context)
def make_pipeline(context):
high_dollar_volume = dollar_volume.percentile_between(90,100)
top_open_prices = USEquityPricing.open.latest.top(50,mask=high_dollar_volume)
high_close_price = USEquityPricing.open.latest.percentile_between(90,100,mask = top_open_prices)
mean_close_30 = SimpleMovingAverage(inputs = [USEquityPricing.close],window_length=30,mask=high_close_price)
mean_close_10 = SimpleMovingAverage(inputs = [USEquityPricing.close],window_length=10,mask=high_close_price)
percent_difference = (mean_close_10-mean_close_30)/mean_close_30
#combine
shorts = percent_difference < 0
longs = percent_difference > 0
securities_to_trade = (shorts | longs)
return Pipeline(columns={
'longs' :longs,
'shorts':shorts,
'perc_diff':percent_difference},
screen = securities_to_trade)
However, when I run this, I get this error:
line 25, in rebalance
AttributeError: 'TradingAlgorithm' object has no attribute 'longs'
'TradingAlgorithm' object has no attribute 'longs'
I have no idea what is wrong with my code. I suspected that it was because I hadn't referred to a specific set of stocks in my pipeline, but I don't know how to fix this.
Could someone help me out here?