backtrader.indicators.macd module

MACD Indicator Module - Moving Average Convergence Divergence.

This module provides the MACD (Moving Average Convergence Divergence) indicator developed by Gerald Appel in the 1970s for trend following.

Classes:

MACD: MACD indicator with signal line. MACDHisto: MACD with histogram (alias: MACDHistogram).

Example

class MyStrategy(bt.Strategy):
def __init__(self):

self.macd = bt.indicators.MACD(self.data) self.macd_hist = bt.indicators.MACDHisto(self.data)

def next(self):

# MACD crossover strategy if self.macd.macd[0] > self.macd.signal[0]:

self.buy()

elif self.macd.macd[0] < self.macd.signal[0]:

self.sell()

class backtrader.indicators.macd.MACD[source]

Bases: Indicator

Moving Average Convergence Divergence. Defined by Gerald Appel in the 70s.

It measures the distance of a short and a long term moving average to try to identify the trend.

A second lagging moving average over the convergence-divergence should provide a “signal” upon being crossed by the macd

Formula:
  • macd = ema(data, me1_period) - ema(data, me2_period)

  • signal = ema(macd, signal_period)

See:
plotinfo = <backtrader.metabase.plotinfo_obj object>
plotlines = <backtrader.metabase.plotlines_obj object>
__init__(*args, **kwargs)
prenext()[source]

Calculate MACD during warmup period.

Ensures MACD values are available for signal line seeding.

nextstart()[source]

Calculate MACD and seed signal line on first valid bar.

Computes MACD and seeds signal with SMA of MACD values.

next()[source]

Calculate MACD and signal line for the current bar.

MACD = me1 - me2 Signal = EMA(MACD)

once(start, end)[source]

Calculate MACD in runonce mode

frompackages = ()
packages = ()
class backtrader.indicators.macd.MACDHisto[source]

Bases: MACD

Subclass of MACD which adds a “histogram” of the difference between the macd and signal lines

Formula:
  • histo = macd - signal

See:
alias = ('MACDHistogram',)
plotlines = <backtrader.metabase.plotlines_obj object>
__init__(*args, **kwargs)
nextstart()[source]

Calculate MACD Histogram on first valid bar.

Histogram = MACD - Signal.

next()[source]

Calculate MACD Histogram for the current bar.

Histogram = MACD - Signal.

once(start, end)[source]

Calculate MACD Histogram in runonce mode.

Computes histogram as MACD minus signal across all bars.

frompackages = ()
packages = ()