Back to Community
Need helps on the simple moving average

Hi guys,

I am trying to write my first algorithm and I am really really bad on Python. My stuff is keeping saying "NameError: global name 'SMA5' is not defined". I know there are bunches of mistakes... and really need some help. sorry for the mess.

I want to buy a stock if :
1- The previous day close price is greater than the 5-day moving average
2- when 5-day moving average is greater than 10-day moving average
Otherwise, sell them

Really appreciate!!

Loading notebook preview...
1 response

This code may be helpful in IDE (Research --> Algorithms) to accomplish what you specified.

from quantopian.pipeline.factors import SimpleMovingAverage as SMA, MarketCap  
from import USEquityPricing as USEP  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.filters import QTradableStocksUS, Q500US  
from quantopian.pipeline import Pipeline  
# --------------------------------------  
MA_F = 5; MA_S = 10; N = 4 ;  
# --------------------------------------  
def initialize(context):  
    schedule_function(my_rebalance,date_rules.every_day(), time_rules.market_close(minutes = 30), True)  
    mcap = MarketCap(window_length = 1, mask =  QTradableStocksUS())  
    sma_f  = SMA(inputs = [USEP.close], window_length = MA_F)  
    sma_s  = SMA(inputs = [USEP.close], window_length = MA_S)  
    longs  = (sma_f > sma_s)  
    screen =  QTradableStocksUS() & (longs) &  

    attach_pipeline(Pipeline({'longs': longs}, screen), 'my_pipe')  

def my_rebalance(context,data):  
    output = pipeline_output('my_pipe')  
    longs = output[output['longs']].index  

    for sec in context.portfolio.positions:  
        if sec not in longs:  
            order_target_percent(sec, 0)  

    for sec in longs:  
        wt = 1.0/len(longs) if len(longs) > 0 else 0  
        order_target_percent(sec, wt)