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).
示例
- 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[源代码]¶
基类:
IndicatorBase 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[源代码]¶
基类:
PeriodNCalculates "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
备注
Base classes must provide a "func" attribute which is callable
- Formula:
line = func(data, period)
- next()[源代码]¶
Calculate function value for the current bar.
Applies func to the last 'period' data values.
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.BaseApplyN[源代码]¶
基类:
OperationNBase class for ApplyN and others which may take a
funcas a parameter but want to define the lines in the indicator.Calculates
funcfor a given period where func is given as a parameter, aka named argument orkwarg- 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[源代码]¶
基类:
BaseApplyNCalculates
funcfor a given period- Formula:
line = func(data, period)
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.Highest[源代码]¶
基类:
OperationNCalculates the highest value for the data in a given period
Uses the built-in
maxfor 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[源代码]¶
基类:
OperationNCalculates the lowest value for the data in a given period
Uses the built-in
minfor 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[源代码]¶
基类:
OperationNCalculates the Reduced value of the
perioddata points applyingfunctionUses the built-in
reducefor the calculation plus thefuncthat subclassess define- Formula:
reduced = reduce (function(data, period)), initializer=initializer)
备注
In order to mimic the python reduce, this indicator takes a
functionnon-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[源代码]¶
基类:
OperationNCalculates the Sum of the data values over a given period
Uses
math.fsumfor the calculation rather than the built-insumto 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[源代码]¶
基类:
OperationNHas a value of
True(stored as1.0in the lines) if any of the values in theperiodevaluates 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[源代码]¶
基类:
OperationNHas a value of
True(stored as1.0in the lines) if all of the values in theperiodevaluates 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[源代码]¶
基类:
OperationNReturns the index of the last data that satisfies equality with the condition generated by the parameter _evalfunc
备注
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)[源代码]¶
Find first index where value matches eval function result.
- 参数:
iterable -- Data values to search.
- 返回:
Index of first matching value (looking backwards).
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.FindFirstIndexHighest[源代码]¶
-
Returns the index of the first data that is the highest in the period
备注
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[源代码]¶
-
Returns the index of the first data that is the lowest in the period
备注
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[源代码]¶
基类:
OperationNReturns the index of the last data that satisfies equality with the condition generated by the parameter _evalfunc
备注
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)[源代码]¶
Find last index where value matches eval function result.
- 参数:
iterable -- Data values to search.
- 返回:
Index of last matching value (looking backwards).
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.FindLastIndexHighest[源代码]¶
-
Returns the index of the last data that is the highest in the period
备注
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[源代码]¶
-
Returns the index of the last data that is the lowest in the period
备注
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[源代码]¶
基类:
IndicatorCummulative sum of the data values
- Formula:
accum += data
- alias = ('CumSum', 'CumulativeSum')¶
- once(start, end)[源代码]¶
Continue accumulation in runonce mode.
accum = prev_accum + data for each bar.
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.Average[源代码]¶
基类:
PeriodNAverages a given data arithmetically over a period
- Formula:
av = data(period) / period
- alias = ('ArithmeticMean', 'Mean')¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.ExponentialSmoothing[源代码]¶
基类:
AverageAverages 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()[源代码]¶
Seed exponential smoothing with SMA value.
Uses parent's SMA calculation for initial seed.
- oncestart(start, end)[源代码]¶
Calculate seed value in runonce mode.
Uses parent's SMA calculation for initial seed.
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.ExponentialSmoothingDynamic[源代码]¶
-
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
备注
alpha is an array of values which can be calculated dynamically
- Formula:
av = prev * (1 - alpha) + data * alpha
- alias = ('ExpSmoothingDynamic',)¶
- __init__(*args, **kwargs)¶
- next()[源代码]¶
Calculate dynamic EMA for the current bar.
Handles both float and LineBuffer alpha sources.
- once(start, end)[源代码]¶
Calculate dynamic EMA in runonce mode.
Handles both float and LineBuffer alpha sources.
- frompackages = ()¶
- packages = ()¶
- class backtrader.indicators.basicops.WeightedAverage[源代码]¶
基类:
PeriodNCalculates 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()[源代码]¶
Calculate weighted average for the current bar.
Multiplies data by weights and sums, then applies coefficient.
- packages = ()¶
- backtrader.indicators.basicops.AverageWeighted¶
WeightedAverage的别名