Good evening everybody,
I am trying to develop a trend-following strategy but I have difficulties in the coding
The strategy is simple:
--> If the SMA 50 > SMA 100 (of the SPY), then invest in the top 5 companies with the largest 126 days returns (universe Q500US)
--> If SMA50<SMA100, then invest in TLT
This is a monthly strategy.
You will find below my code, could you please advise me on what should I change in order to make it work?
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data import USEquityPricing
from quantopian.pipeline.filters import Q500US
from quantopian.pipeline.factors import SimpleMovingAverage,Returns
from quantopian.algorithm import attach_pipeline, pipeline_output
# ---------------------------
SPY=symbol('SPY'); BOND=symbols('TLT'); U=Q500US
MOM=126;N=5;SMA100=100; SMA50=50;MIN=30
# ---------------------------
def initialize(context):
#Companies with highest return from universe
R=Returns(window_length=MOM, mask=U).top(N)
attach_pipeline(Pipeline({'R': R,}),'pipe')
#Schedule function
schedule_function(trade, date_rules.month_end(),
time_rules.market_close(minutes = MIN))
def trade(context,data):
#Output the top 5 selected
output = pipeline_output('pipe')
stock=output.R
#Trend Following Filter
sma_f=SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=SMA50)[SPY]
sma_s=SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=SMA100)[SPY]
#Weigh for the portfolio of stocks
wt=1/N
if sma_f > sma_s:
order_target_percent(stock,wt)
elif not sma_f < sma_s:
order_target_percent(BOND,1.0)
I thank you in advance