StratCraft
Backtrader Indicator Guide

Backtrader MACD Momentum Trading Strategy

Trend-following momentum indicator showing the relationship between two exponential moving averages (typically 12 and 26 periods). The signal line (9-period EMA of MACD) generates crossover signals.

bt.indicators.MACDMomentum Trading Strategies

Trend-following momentum indicator showing the relationship between two exponential moving averages (typically 12 and 26 periods). The signal line (9-period EMA of MACD) generates crossover signals.

MACD is the definitive momentum indicator. When the MACD line crosses above the signal line, momentum is shifting bullish. In momentum strategies, traders ride the trend until MACD shows divergence (price makes new high but MACD does not), signaling trend exhaustion.

Learn more about Momentum Trading Strategies →
Pythonbacktrader
import backtrader as bt

class MACDMomentum(bt.Strategy):
    params = (('fast', 12), ('slow', 26), ('signal', 9))

    def __init__(self):
        self.macd = bt.indicators.MACD(self.data.close,
                                        period_me1=self.p.fast,
                                        period_me2=self.p.slow,
                                        period_signal=self.p.signal)

    def next(self):
        # MACD line crosses above signal line = bullish momentum
        if self.macd.macd[0] > self.macd.signal[0] and self.macd.macd[-1] <= self.macd.signal[-1]:
            self.buy()
        # MACD line crosses below signal line = bearish momentum
        elif self.macd.macd[0] < self.macd.signal[0] and self.macd.macd[-1] >= self.macd.signal[-1]:
            self.sell()
ParameterDefaultDescription
period_me112Fast EMA period
period_me226Slow EMA period
period_signal9Signal line EMA period