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.

示例

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[源代码]

基类: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)[源代码]

Register a moving average class with the placeholder.

参数:

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

AdaptiveMovingAverage 的别名

class AdaptiveMovingAverage

基类: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

DoubleExponentialMovingAverage 的别名

DMA

DicksonMovingAverage 的别名

Dickson

DicksonMovingAverage 的别名

DicksonMA

DicksonMovingAverage 的别名

class DicksonMovingAverage

基类: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

DoubleExponentialMovingAverage 的别名

class DoubleExponentialMovingAverage

基类: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

ZeroLagIndicator 的别名

EMA

ExponentialMovingAverage 的别名

ErrorCorrecting

ZeroLagIndicator 的别名

Exponential

ExponentialMovingAverage 的别名

class ExponentialMovingAverage

基类: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

HullMovingAverage 的别名

Hull

HullMovingAverage 的别名

HullMA

HullMovingAverage 的别名

class HullMovingAverage

基类: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))

备注

  • 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

AdaptiveMovingAverage 的别名

ModifiedMovingAverage

SmoothedMovingAverage 的别名

MovingAverageAdaptive

AdaptiveMovingAverage 的别名

MovingAverageDoubleExponential

DoubleExponentialMovingAverage 的别名

MovingAverageExponential

ExponentialMovingAverage 的别名

class MovingAverageSimple

基类: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

SmoothedMovingAverage 的别名

MovingAverageTripleExponential

TripleExponentialMovingAverage 的别名

MovingAverageWeighted

WeightedMovingAverage 的别名

MovingAverageWilder

SmoothedMovingAverage 的别名

SMA

MovingAverageSimple 的别名

SMMA

SmoothedMovingAverage 的别名

Simple

MovingAverageSimple 的别名

SimpleMovingAverage

MovingAverageSimple 的别名

Smoothed

SmoothedMovingAverage 的别名

class SmoothedMovingAverage

基类: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

TripleExponentialMovingAverage 的别名

TripleExponential

TripleExponentialMovingAverage 的别名

class TripleExponentialMovingAverage

基类: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

WeightedMovingAverage 的别名

Weighted

WeightedMovingAverage 的别名

class WeightedMovingAverage

基类: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

SmoothedMovingAverage 的别名

ZLEMA

ZeroLagExponentialMovingAverage 的别名

ZLInd

ZeroLagIndicator 的别名

ZLIndicator

ZeroLagIndicator 的别名

ZeroLagEma

ZeroLagExponentialMovingAverage 的别名

ZeroLagExponential

ZeroLagExponentialMovingAverage 的别名

class ZeroLagExponentialMovingAverage

基类: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

基类: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.

参数:
  • 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.

参数:
  • 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.

参数:
  • start -- Starting index

  • end -- Ending index

class backtrader.indicators.mabase.MovAv[源代码]

基类:MovingAverage

Alias for MovingAverage.

Provides a shorter name for accessing moving average types.

class backtrader.indicators.mabase.MovingAverageBase[源代码]

基类: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)[源代码]

Register moving average classes automatically

frompackages = ()
packages = ()