Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trend Following Strategy : help on the code

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

2 responses

@ Tony B,
try this way:

from quantopian.pipeline import Pipeline  
from quantopian.pipeline.filters import Q500US  
from quantopian.pipeline.factors import Returns  
from quantopian.algorithm import attach_pipeline, pipeline_output  
# -----------------------------------------------------  
SPY = symbol('SPY'); BOND = symbol('TLT'); U = Q500US()  
MOM = 126; N = 5; SMA100 = 100; SMA50 = 50; MIN = 60;  
# -----------------------------------------------------  
def initialize(context):  
    # Companies with highest return from universe  
    R = Returns(window_length = MOM, mask = U).top(N)  
    attach_pipeline(Pipeline(screen = R),'pipe')  
    # Schedule function  
    schedule_function(trade, date_rules.month_start(), time_rules.market_open(minutes = MIN))

def trade(context,data):  
    # Output the top 5 selected  
    stocks = pipeline_output('pipe').index 

    # Trend Following Filter  
    sma_f = data.history(SPY,'close', SMA50, '1d').mean()  
    sma_s = data.history(SPY,'close', SMA100, '1d').mean()  
    # Weigh for the portfolio of stocks  
    wt_stk = 1.0/N 

    # Sell stocks no more in top(N) first  
    for sec in context.portfolio.positions:  
        if sec not in stocks and sec is not BOND:  
            order_target_percent(sec, 0);

    if sma_f >= sma_s:  
        for sec in stocks:  
            order_target_percent(sec, wt_stk)  
        order_target_percent(BOND, 0)

    elif sma_f < sma_s:  
        for sec in stocks:  
            order_target_percent(sec, 0)  
        order_target_percent(BOND, 1.0)

    record(leverage = context.account.leverage)

@ Vladimir

It is perfect, thank you so much!