Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Newbie, trying to offset EMA by a few days to compare MACDs of different dates.

Hey, guys!

I'm trying to create an algo that will execute a buy whenever MACD hits a local minimum. I've simply defined this as MACD (t-2) > MACD (t-1) < MACD (today). So I have my MACD defined, below. I'm wondering how to create MACD (t-2) and (t-1) using EMAs of two days prior and one day prior, if anyone can help, please.

//

import talib

def initialize(context):
context.stock = sid(8554)
schedule_function(trade, date_rules.every_day(), time_rules.market_open(hours=1))

def trade(context,data):
prices = data.history(context.stock,'price', 47,'1d')
ema12 = talib.EMA(prices,12)
ema26 = talib.EMA(prices,26)
macd = ema12 - ema26

3 responses

@Joch,

Try this:

import talib  
# --------------------------  
stock = symbol('SPY')  
Fast, Slow, Sig = 12, 26, 9  
# --------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = 65))

def trade(context,data):  
    bars = Fast + Slow + Sig  
    prices = data.history(stock, 'price', bars, '1d')  
    macd, signal, hist = talib.MACD(prices, Fast, Slow, Sig)  
    if macd[-1] > macd[-2] < macd[-3]:  
        order_target_percent(stock, 1.0)  
    elif macd[-1] < macd[-2] > macd[-3]:  
        order_target_percent(stock, 0)  
    record(macd = macd[-1])  

This worked, thank you!

what is the significance of [-1]? I understand it represents the most current time period, but why is the [-1] required? I would have thought that represented the t-1 period instead

[-1] == t, [-2] == t-1, [-3] == t-2 ...