Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Basic 200SMA Algorithm

I'm trying to learn how to use the platform and could use some help. I created the below algorithm, but it isn't working how I expected. I came across a paper that basically invested in the S&P above its 200SMA and went to cash when below. I wanted to try and mimic those results as a way to learn a basic Quantopian algorithm. Any advice on what I'm doing wrong here?

import numpy as np

# This function is run once at the beginning of the algorithm, REQUIRED  
def initialize(context):  
    # SPY stock  
    context.spy = sid(8554)

# This function is run once per day before any calls to handle_data, OPTIONAL  
def before_trading_start(context, data):  
    pass

# This function is run once per bar, REQUIRED  
def handle_data(context, data):  
    twohund_sma = history(201, '1d', 'close_price')  
    current_price = data[context.spy].price  
    for spy in data:  
        if current_price > np.mean(twohund_sma[spy][:-1]):  
            order_target_percent(context.spy, 1.0, style=MarketOrder())  
        else:  
            order_target_percent(context.spy, 0.0, style=MarketOrder())  
    pass  
3 responses

Hi, try this

import talib as ta

def initialize(context):  
    context.spy = sid(8554)

def handle_data(context, data):  
    hclose = history(201, '1d', 'close_price')  
    twohund_sma = ta.SMA(hclose[context.spy], 200)[-1]  
    current_price = data[context.spy].price  
    if current_price > twohund_sma:  
            order_target_percent(context.spy, 1)  
    else:  
        order_target_percent(context.spy, 0)  

I tried that but it doesn't seem to work when it moves up/below the SMA minute after minute. I tried updating the code to the following but it still isn't working.

You can add record plots so you can see the data better

import talib as ta

ma_length = 20

def initialize(context):  
    context.spy = sid(8554)

def handle_data(context, data):  
    hclose = history(201, '1d', 'close_price')  
    sma = ta.SMA(hclose[context.spy], ma_length)[-1]  
    current_price = data[context.spy].price  
    if current_price > sma:  
            order_target_percent(context.spy, 1)  
    else:  
        order_target_percent(context.spy, 0) 

    record(  
        Price = current_price,  
        Sma = sma)