backtrader.indicators.mabase module

Moving Average Base Module - Core moving average infrastructure.

This module provides the base classes and registration system for all moving average indicators in backtrader.

Classes:

MovingAverage: Placeholder for all moving average types. MovAv: Alias for MovingAverage. MovingAverageBase: Base class for moving average indicators.

Example

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

self.sma = bt.indicators.SMA(self.data.close, period=20) self.ema = bt.indicators.EMA(self.data.close, period=12) # Or using MovAv wrapper self.wma = bt.indicators.MovAv.WMA(self.data.close, period=15)

def next(self):
if self.data.close[0] > self.sma[0]:

self.buy()

elif self.data.close[0] < self.sma[0]:

self.sell()

class backtrader.indicators.mabase.MovingAverage[source]

Bases: object

MovingAverage (alias MovAv)

A placeholder to gather all Moving Average Types in a single place.

Instantiating a SimpleMovingAverage can be achieved as follows:

sma = MovingAverage.Simple(self.data, period)

Or using the shorter aliases:

sma = MovAv.SMA(self.data, period)

or with the full (forwards and backwards) names:

sma = MovAv.SimpleMovingAverage(self.data, period)

sma = MovAv.MovingAverageSimple(self.data, period)

classmethod register(regcls)[source]

Register a moving average class with the placeholder.

Parameters:

regcls – The moving average class to register.

Sets the class name and aliases as attributes on the placeholder for easy access (e.g., MovAv.SMA, MovAv.EMA).

Adaptive

alias of AdaptiveMovingAverage

class AdaptiveMovingAverage

Bases: MovingAverageBase

Defined by Perry Kaufman in his book “Smarter Trading”.

It is A Moving Average with a continuously scaled smoothing factor by taking into account market direction and volatility. The smoothing factor is calculated from 2 ExponetialMovingAverage smoothing factors, a fast one and slow one.

If the market trends, the value will tend to the fast ema smoothing period. If the market doesn’t trend, it will move towards the slow EMA smoothing period.

It is a subclass of SmoothingMovingAverage, overriding once to account for the live nature of the smoothing factor

Formula:
  • direction = close - close_period

  • volatility = sumN(abs (close - close_n), period)

  • effiency_ratio = abs (direction / volatility)

  • fast = 2 / (fast_period + 1)

  • slow = 2 / (slow_period + 1)

  • Smfactor = squared(efficienty_ratio * (fast - slow) + slow)

  • smfactor1 = 1.0 - smfactor

  • The initial seed value is a SimpleMovingAverage

__init__(*args, **kwargs)
alias = ('KAMA', 'MovingAverageAdaptive')
frompackages = ()
next()

Calculate KAMA for the current bar.

KAMA = prev_KAMA + sc * (price - prev_KAMA) where sc is the adaptive smoothing constant.

nextstart()

Seed KAMA calculation with SMA on first valid bar.

Calculates simple moving average for the initial seed value.

once(start, end)

Calculate KAMA in runonce mode.

Seeds with SMA and applies adaptive smoothing for each bar.

packages = ()
DEMA

alias of DoubleExponentialMovingAverage

DMA

alias of DicksonMovingAverage

Dickson

alias of DicksonMovingAverage

DicksonMA

alias of DicksonMovingAverage

class DicksonMovingAverage

Bases: MovingAverageBase

By Nathan Dickson

The Dickson Moving Average combines the ZeroLagIndicator (aka ErrorCorrecting or EC) by Ehlers, and the HullMovingAverage to try to deliver a result close to that of the Jurik Moving Averages

Formula:
  • ec = ZeroLagIndicator(period, gainlimit)

  • hma = HullMovingAverage(hperiod)

  • dma = (ec + hma) / 2

  • The default moving average for the ZeroLagIndicator is EMA, but can be changed with the parameter _movav

    ::note:: the passed moving average must calculate alpha (and 1 - alpha)

    and make them available as attributes alpha and alpha1

  • The second moving average can be changed from Hull to anything else with the param _hma

__init__(*args, **kwargs)
alias = ('DMA', 'DicksonMA')
frompackages = ()
next()

Calculate DMA for the current bar.

Formula: DMA = (ZeroLag + HMA) / 2

once(start, end)

Calculate DMA in runonce mode.

packages = ()
DoubleExponential

alias of DoubleExponentialMovingAverage

class DoubleExponentialMovingAverage

Bases: MovingAverageBase

DEMA was first time introduced in 1994, in the article “Smoothing Data with Faster-Moving Averages” by Patrick G. Mulloy in “Technical Analysis of Stocks & Commodities” magazine.

It attempts to reduce the inherent lag associated with Moving Averages

Formula:
  • dema = (2.0 - ema(data, period) - ema(ema(data, period), period)

See:

(None)

__init__(*args, **kwargs)
alias = ('DEMA', 'MovingAverageDoubleExponential')
frompackages = ()
next()

Calculate DEMA for the current bar.

Formula: DEMA = 2 * EMA1 - EMA(EMA1)

once(start, end)

Calculate DEMA in runonce mode.

packages = ()
EC

alias of ZeroLagIndicator

EMA

alias of ExponentialMovingAverage

ErrorCorrecting

alias of ZeroLagIndicator

Exponential

alias of ExponentialMovingAverage

class ExponentialMovingAverage

Bases: MovingAverageBase

A Moving Average that smoothes data exponentially over time.

It is a subclass of SmoothingMovingAverage.

  • self.smfactor -> 2 / (1 + period)

  • self.smfactor1 -> 1 - self.smfactor

Formula:
  • movav = prev * (1.0 - smoothfactor) + newdata * smoothfactor

__init__(*args, **kwargs)
alias = ('EMA', 'MovingAverageExponential')
frompackages = ()
next()

Calculate EMA for the current bar.

Formula: EMA = previous_ema * alpha1 + current_price * alpha

nextstart()

Seed the EMA with SMA of first period values.

once(start, end)

Calculate EMA in runonce mode

packages = ()
HMA

alias of HullMovingAverage

Hull

alias of HullMovingAverage

HullMA

alias of HullMovingAverage

class HullMovingAverage

Bases: MovingAverageBase

By Alan Hull

The Hull Moving Average solves the age-old dilemma of making a moving average more responsive to current price activity whilst maintaining curve smoothness. In fact, the HMA almost eliminates lag altogether and manages to improve smoothing at the same time.

Formula:
  • hma = wma(2 * wma(data, period // 2) - wma(data, period), sqrt(period))

Note

  • Please note that the final minimum period is not the period passed with the parameter period. A final moving average on moving average is done in which the period is the square root of the original.

    In the default case of 30, the final minimum period before the moving average produces a non-NAN value is 34

__init__(*args, **kwargs)
alias = ('HMA', 'HullMA')
frompackages = ()
next()

Calculate HMA for the current bar.

Formula: HMA = WMA(2*WMA(n/2) - WMA(n), sqrt(n))

once(start, end)

Calculate HMA in runonce mode.

packages = ()
KAMA

alias of AdaptiveMovingAverage

ModifiedMovingAverage

alias of SmoothedMovingAverage

MovingAverageAdaptive

alias of AdaptiveMovingAverage

MovingAverageDoubleExponential

alias of DoubleExponentialMovingAverage

MovingAverageExponential

alias of ExponentialMovingAverage

class MovingAverageSimple

Bases: MovingAverageBase

Non-weighted average of the last n periods

Formula:
  • movav = Sum(data, period) / period

__init__(*args, **kwargs)
alias = ('SMA', 'SimpleMovingAverage')
frompackages = ()
next()

Phase 2 Optimized next() method with vectorized calculations

nextstart()

Initialize on first call after minperiod is met

once(start, end)

Optimized batch calculation for runonce mode

packages = ()
MovingAverageSmoothed

alias of SmoothedMovingAverage

MovingAverageTripleExponential

alias of TripleExponentialMovingAverage

MovingAverageWeighted

alias of WeightedMovingAverage

MovingAverageWilder

alias of SmoothedMovingAverage

SMA

alias of MovingAverageSimple

SMMA

alias of SmoothedMovingAverage

Simple

alias of MovingAverageSimple

SimpleMovingAverage

alias of MovingAverageSimple

Smoothed

alias of SmoothedMovingAverage

class SmoothedMovingAverage

Bases: MovingAverageBase

Smoothing Moving Average used by Wilder in his 1978 book New Concepts in Technical Trading

Defined in his book originally as:

  • new_value = (old_value * (period - 1) + new_data) / period

It Can be expressed as a SmoothingMovingAverage with the following factors:

  • self.smfactor -> 1.0 / period

  • self.smfactor1 -> 1.0 - self.smfactor

Formula:
  • movav = prev * (1.0 - smoothfactor) + newdata * smoothfactor

__init__(*args, **kwargs)
alias = ('SMMA', 'WilderMA', 'MovingAverageSmoothed', 'MovingAverageWilder', 'ModifiedMovingAverage')
frompackages = ()
next()

Calculate SMMA for the current bar.

Formula: SMMA = prev_SMMMA * alpha1 + current_price * alpha where alpha = 1/period and alpha1 = 1 - alpha.

nextstart()

Seed SMMA calculation with SMA on first valid bar.

Initializes with simple moving average of the first period values.

once(start, end)

Calculate SMMA in runonce mode

packages = ()
TEMA

alias of TripleExponentialMovingAverage

TripleExponential

alias of TripleExponentialMovingAverage

class TripleExponentialMovingAverage

Bases: MovingAverageBase

TEMA was first time introduced in 1994, in the article “Smoothing Data with Faster-Moving Averages” by Patrick G. Mulloy in “Technical Analysis of Stocks & Commodities” magazine.

It attempts to reduce the inherent lag associated with Moving Averages

Formula:
  • ema1 = ema(data, period)

  • ema2 = ema(ema1, period)

  • ema3 = ema(ema2, period)

  • tema = 3 * ema1 - 3 * ema2 + ema3

See:

(None)

__init__(*args, **kwargs)
alias = ('TEMA', 'MovingAverageTripleExponential')
frompackages = ()
next()

Calculate TEMA for the current bar.

Formula: TEMA = 3 * EMA1 - 3 * EMA2 + EMA3

once(start, end)

Calculate TEMA in runonce mode.

packages = ()
WMA

alias of WeightedMovingAverage

Weighted

alias of WeightedMovingAverage

class WeightedMovingAverage

Bases: MovingAverageBase

A Moving Average which gives an arithmetic weighting to values with the newest having the more weight

Formula:
  • weights = range(1, period + 1)

  • coef = 2 / (period * (period + 1))

  • movav = coef * Sum(weight[i] * data[period - i] for i in range(period))

__init__(*args, **kwargs)
alias = ('WMA', 'MovingAverageWeighted')
frompackages = ()
next()

Calculate WMA for the current bar.

Applies arithmetic weighting with newest values having more weight.

once(start, end)

Calculate WMA in runonce mode.

Applies weighted average calculation across all bars.

packages = ()
WilderMA

alias of SmoothedMovingAverage

ZLEMA

alias of ZeroLagExponentialMovingAverage

ZLInd

alias of ZeroLagIndicator

ZLIndicator

alias of ZeroLagIndicator

ZeroLagEma

alias of ZeroLagExponentialMovingAverage

ZeroLagExponential

alias of ZeroLagExponentialMovingAverage

class ZeroLagExponentialMovingAverage

Bases: MovingAverageBase

The zero-lag exponential moving average (ZLEMA) is a variation of the EMA which adds a momentum term aiming to reduce lag in the average to track current prices more closely.

Formula:
  • lag = (period - 1) / 2

  • zlema = ema(2 * data - data(-lag))

__init__(*args, **kwargs)
alias = ('ZLEMA', 'ZeroLagEma')
frompackages = ()
next()

Calculate ZLEMA for the current bar.

Applies EMA to lag-adjusted data: 2 * data - data(-lag).

nextstart()

Seed ZLEMA calculation with SMA on first valid bar.

Uses SMA of lag-adjusted data for initial seed value.

once(start, end)

Calculate ZLEMA in runonce mode.

Applies EMA to lag-adjusted data across all bars.

packages = ()
class ZeroLagIndicator

Bases: MovingAverageBase

By John Ehlers and Ric Way

The zero-lag indicator (ZLIndicator) is a variation of the EMA which modifies the EMA by trying to minimize the error (distance price - error correction) and thus reduce the lag

Formula:
  • EMA(data, period)

  • For each iteration calculate a best-error-correction of the ema (see the paper and/or the code) iterating over -bestgain -> +bestgain for the error correction factor (both incl.)

  • The default moving average is EMA, but can be changed with the parameter _movav

    ::note:: the passed moving average must calculate alpha (and 1 -

    alpha) and make them available as attributes alpha and alpha1 in the instance

__init__(*args, **kwargs)
alias = ('ZLIndicator', 'ZLInd', 'EC', 'ErrorCorrecting')
frompackages = ()
next()

Calculate zero lag indicator for the current bar.

Iterates over gain values to find the error correction that minimizes the difference between price and corrected EMA.

once(start, end)

Implement once using next for batch calculation.

This is used when next is overridden but once is not. It loops through the range and calls next for each step.

Parameters:
  • start – Starting index

  • end – Ending index

oncestart(start, end)

Implement oncestart using nextstart for batch calculation.

This is used when nextstart is overridden but oncestart is not.

Parameters:
  • start – Starting index

  • end – Ending index

packages = ()
preonce(start, end)

Implement preonce using prenext for batch calculation.

This is a generic implementation if prenext is overridden but preonce is not. It loops through the range and calls prenext for each step.

Parameters:
  • start – Starting index

  • end – Ending index

class backtrader.indicators.mabase.MovAv[source]

Bases: MovingAverage

Alias for MovingAverage.

Provides a shorter name for accessing moving average types.

class backtrader.indicators.mabase.MovingAverageBase[source]

Bases: Indicator

Base class for all moving average indicators.

Provides common initialization with minimum period management and automatic registration with the MovingAverage placeholder.

params

Default period parameter (30).

plotinfo

Default to plot on main chart (subplot=False).

plotinfo = <backtrader.metabase.plotinfo_obj object>
__init__(*args, **kwargs)
classmethod __init_subclass__(**kwargs)[source]

Register moving average classes automatically

frompackages = ()
packages = ()