Back to Community
Trying to get max MACD value over past 15 periods

Hi,

My algo is trading based on MACD crossovers and I'm trying to get the max MACD value over the past 15 periods. I want to sell the current position if the MACD falls below the max MACD value from the past 15 periods. I keep getting a "KeyError: -15" when running the code segment below:

import talib

# Initialization function run once per day  
def initialize(context):  
    context.stock = sid(24)  
    # Trading schedule framework  
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())  
# Rebalance daily.  
def rebalance(context, data):  
    # Load historical data for the stocks  
    prices = data.history(context.stock, 'price', 40, '1d')  
    # Contains MACD values  
    macds = {}  
    # Create MACD and set signals  
    macd_raw, signal, hist = talib.MACD(prices,fastperiod=12,slowperiod=26,signalperiod=9)  
    macd = macd_raw[-1] - signal[-1]  
    macds[context.stock] = macd  
    # Set High and Low  
    MACD_High = max(macds[-15]) #This is where the error is occuring  
    high_threshold = MACD_High * 0.95 #relaxed by 0.3%  

How can I grab the past 15 MACD values in order to set the max value as a variable?
Thanks