backtrader.indicators.basicops module

Basic Operations Indicator Module - Fundamental calculation indicators.

This module provides basic mathematical operations and calculations for indicator development, including period-based operations and statistics.

Classes:

PeriodN: Base class for period-based indicators. OperationN: Base class for function-based period calculations. BaseApplyN: Base class for applying a function over a period. ApplyN: Applies a function over a period. Highest: Calculates highest value (alias: MaxN). Lowest: Calculates lowest value (alias: MinN). ReduceN: Applies reduce function over a period. SumN: Calculates sum over a period. AnyN: Returns True if any value is True. AllN: Returns True only if all values are True. FindFirstIndex: Finds first index matching condition. FindFirstIndexHighest: Index of first highest value. FindFirstIndexLowest: Index of first lowest value. FindLastIndex: Finds last index matching condition. FindLastIndexHighest: Index of last highest value. FindLastIndexLowest: Index of last lowest value. Accum: Cumulative sum (aliases: CumSum, CumulativeSum). Average: Arithmetic mean (aliases: ArithmeticMean, Mean). ExponentialSmoothing: EMA-style smoothing (alias: ExpSmoothing). ExponentialSmoothingDynamic: Dynamic alpha smoothing (alias: ExpSmoothingDynamic). WeightedAverage: Weighted average (alias: AverageWeighted).

Example

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

# Calculate highest and lowest prices over 20 periods self.highest = bt.indicators.Highest(self.data.close, period=20) self.lowest = bt.indicators.Lowest(self.data.close, period=20)

# Calculate average price self.avg = bt.indicators.Average(self.data.close, period=20)

def next(self):

# Buy when price breaks above highest of last 20 bars if self.data.close[0] > self.highest[-1]:

self.buy()

# Sell when price breaks below lowest of last 20 bars elif self.data.close[0] < self.lowest[-1]:

self.sell()

class backtrader.indicators.basicops.PeriodN[source]

Bases: Indicator

Base class for indicators which take a period (__init__ has to be called either via supper or explicitly)

This class has no defined lines

__init__(*args, **kwargs)
frompackages = ()
packages = ()
class backtrader.indicators.basicops.OperationN[source]

Bases: PeriodN

Calculates “func” for a given period

Serves as a base for classes that work with a period and can express the logic in a callable object

Note

Base classes must provide a “func” attribute which is callable

Formula:
  • line = func(data, period)

next()[source]

Calculate function value for the current bar.

Applies func to the last ‘period’ data values.

once(start, end)[source]

Optimized batch calculation for runonce mode - same approach as SMA

frompackages = ()
packages = ()
class backtrader.indicators.basicops.BaseApplyN[source]

Bases: OperationN

Base class for ApplyN and others which may take a func as a parameter but want to define the lines in the indicator.

Calculates func for a given period where func is given as a parameter, aka named argument or kwarg

Formula:
  • lines[0] = func(data, period)

Any extra lines defined beyond the first (index 0) are not calculated

__init__(*args, **kwargs)
frompackages = ()
packages = ()
class backtrader.indicators.basicops.ApplyN[source]

Bases: BaseApplyN

Calculates func for a given period

Formula:
  • line = func(data, period)

frompackages = ()
packages = ()
class backtrader.indicators.basicops.Highest[source]

Bases: OperationN

Calculates the highest value for the data in a given period

Uses the built-in max for the calculation

Formula:
  • highest = max(data, period)

alias = ('MaxN',)
func()

max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.Lowest[source]

Bases: OperationN

Calculates the lowest value for the data in a given period

Uses the built-in min for the calculation

Formula:
  • lowest = min(data, period)

alias = ('MinN',)
func()

min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.ReduceN[source]

Bases: OperationN

Calculates the Reduced value of the period data points applying function

Uses the built-in reduce for the calculation plus the func that subclassess define

Formula:
  • reduced = reduce (function(data, period)), initializer=initializer)

Notes

  • In order to mimic the python reduce, this indicator takes a function non-named argument as the 1st argument, unlike other Indicators which take only named arguments

__init__(*args, **kwargs)
func()

reduce(function, iterable[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence or iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.SumN[source]

Bases: OperationN

Calculates the Sum of the data values over a given period

Uses math.fsum for the calculation rather than the built-in sum to avoid precision errors

Formula:
  • sumn = sum(data, period)

func(seq, /)

Return an accurate floating point sum of values in the iterable seq.

Assumes IEEE-754 floating point arithmetic.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.AnyN[source]

Bases: OperationN

Has a value of True (stored as 1.0 in the lines) if any of the values in the period evaluates to non-zero (ie: True)

Uses the built-in any for the calculation

Formula:
  • anyn = any(data, period)

func(iterable, /)

Return True if bool(x) is True for any x in the iterable.

If the iterable is empty, return False.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.AllN[source]

Bases: OperationN

Has a value of True (stored as 1.0 in the lines) if all of the values in the period evaluates to non-zero (ie: True)

Uses the built-in all for the calculation

Formula:
  • alln = all(data, period)

func(iterable, /)

Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindFirstIndex[source]

Bases: OperationN

Returns the index of the last data that satisfies equality with the condition generated by the parameter _evalfunc

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = first for which data[index] == _evalfunc(data)

func(iterable)[source]

Find first index where value matches eval function result.

Parameters:

iterable – Data values to search.

Returns:

Index of first matching value (looking backwards).

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindFirstIndexHighest[source]

Bases: FindFirstIndex

Returns the index of the first data that is the highest in the period

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = index of first data which is the highest

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindFirstIndexLowest[source]

Bases: FindFirstIndex

Returns the index of the first data that is the lowest in the period

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = index of first data which is the lowest

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindLastIndex[source]

Bases: OperationN

Returns the index of the last data that satisfies equality with the condition generated by the parameter _evalfunc

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = last for which data[index] == _evalfunc(data)

func(iterable)[source]

Find last index where value matches eval function result.

Parameters:

iterable – Data values to search.

Returns:

Index of last matching value (looking backwards).

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindLastIndexHighest[source]

Bases: FindLastIndex

Returns the index of the last data that is the highest in the period

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = index of last data which is the highest

frompackages = ()
packages = ()
class backtrader.indicators.basicops.FindLastIndexLowest[source]

Bases: FindLastIndex

Returns the index of the last data that is the lowest in the period

Note

Returned indexes look backwards. 0 is the current index and 1 is the previous bar.

Formula:
  • index = index of last data which is the lowest

frompackages = ()
packages = ()
class backtrader.indicators.basicops.Accum[source]

Bases: Indicator

Cummulative sum of the data values

Formula:
  • accum += data

alias = ('CumSum', 'CumulativeSum')
nextstart()[source]

Start accumulation with seed value.

accum = seed + data[0]

next()[source]

Add current data value to accumulation.

accum += data

oncestart(start, end)[source]

Start accumulation in runonce mode.

accum = seed + data for each bar.

once(start, end)[source]

Continue accumulation in runonce mode.

accum = prev_accum + data for each bar.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.Average[source]

Bases: PeriodN

Averages a given data arithmetically over a period

Formula:
  • av = data(period) / period

alias = ('ArithmeticMean', 'Mean')
next()[source]

Calculate arithmetic mean for the current bar.

av = sum(data, period) / period

once(start, end)[source]

Calculate Average (SMA) in runonce mode

frompackages = ()
packages = ()
class backtrader.indicators.basicops.ExponentialSmoothing[source]

Bases: Average

Averages a given data over a period using exponential smoothing

A regular ArithmeticMean (Average) is used as the seed value considering the first period values of data

Formula:
  • av = prev * (1 - alpha) + data * alpha

alias = ('ExpSmoothing',)
__init__(*args, **kwargs)
nextstart()[source]

Seed exponential smoothing with SMA value.

Uses parent’s SMA calculation for initial seed.

next()[source]

Calculate EMA for the current bar.

av = prev * alpha1 + data * alpha

oncestart(start, end)[source]

Calculate seed value in runonce mode.

Uses parent’s SMA calculation for initial seed.

once(start, end)[source]

Calculate EMA in runonce mode

frompackages = ()
packages = ()
class backtrader.indicators.basicops.ExponentialSmoothingDynamic[source]

Bases: ExponentialSmoothing

Averages a given data over a period using exponential smoothing

A regular ArithmeticMean (Average) is used as the seed value considering the first period values of data

Note

  • alpha is an array of values which can be calculated dynamically

Formula:
  • av = prev * (1 - alpha) + data * alpha

alias = ('ExpSmoothingDynamic',)
__init__(*args, **kwargs)
next()[source]

Calculate dynamic EMA for the current bar.

Handles both float and LineBuffer alpha sources.

once(start, end)[source]

Calculate dynamic EMA in runonce mode.

Handles both float and LineBuffer alpha sources.

frompackages = ()
packages = ()
class backtrader.indicators.basicops.WeightedAverage[source]

Bases: PeriodN

Calculates the weighted average of the given data over a period

The default weights (if none are provided) are linear to assigne more weight to the most recent data

The result will be multiplied by a given “coef”

Formula:
  • av = coef * sum(mul(data, period), weights)

See:
alias = ('AverageWeighted',)
__init__(*args, **kwargs)
frompackages = ()
next()[source]

Calculate weighted average for the current bar.

Multiplies data by weights and sums, then applies coefficient.

packages = ()
once(start, end)[source]

Calculate weighted average in runonce mode.

Computes weighted averages across all bars efficiently.

backtrader.indicators.basicops.AverageWeighted

alias of WeightedAverage