backtrader.linebuffer module¶
LineBuffer Module - Circular buffer storage for time-series data.
This module provides the LineBuffer class which implements a circular buffer for storing time-series data. The buffer allows efficient operations like appending, forwarding, rewinding, and resetting.
- Key Features:
Index 0 always points to the current active value
Positive indices fetch past values (left-hand side)
Negative indices fetch future values (right-hand side)
Automatic memory management with qbuffer
Line bindings for automatic value propagation
- Classes:
LineBuffer: Core circular buffer implementation. LineActions: Base class for line objects with multiple lines. LineActionsMixin: Mixin providing line operations. LineActionsCache: Cache system for performance optimization. PseudoArray: Wrapper for non-array iterables. LinesOperation: Operations on multiple lines. LineOwnOperation: Operations on owned lines.
示例
Basic buffer usage: >>> buf = LineBuffer() >>> buf.home() # Reset to beginning >>> buf.forward() # Move to next position >>> buf[0] = 100.0 # Set current value >>> print(buf[0]) # Get current value 100.0 >>> print(buf[-1]) # Get previous value
- class backtrader.linebuffer.LineBuffer[源代码]¶
-
LineBuffer defines an interface to an "array.array" (or list) in which index 0 points to the item which is active for input and output.
Positive indices fetch values from the past (left-hand side) Negative indices fetch values from the future (if the array has been extended on the right-hand side)
With this behavior, no index has to be passed around to entities which have to work with the current value produced by other entities: the value is always reachable at "0".
Likewise, storing the current value produced by "self" is done at 0.
Additional operations to move the pointer (home, forward, extend, rewind, advance getzero) are provided
The class can also hold "bindings" to other LineBuffers. When a value is set in this class, it will also be set in the binding.
- UnBounded = 0¶
- QBuffer = 1¶
- __init__()[源代码]¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- set_idx(idx, force=False)[源代码]¶
Set the index position.
- 参数:
idx -- The new index value.
force -- If True, force set even in QBuffer mode at lenmark.
备注
In QBuffer mode, when at lenmark, the index stays at 0 unless force is True. This allows resampling operations.
- qbuffer(savemem=0, extrasize=0)[源代码]¶
Enable queued buffer mode for memory-efficient storage.
- 参数:
savemem -- Memory saving mode (0=normal, >0=enable cache mode).
extrasize -- Extra buffer size for resampling/replay operations.
备注
In QBuffer mode, only the last maxlen values are kept, reducing memory usage for long backtests.
- getindicators()[源代码]¶
Get list of indicators using this line buffer.
- 返回:
Empty list for base LineBuffer (override in subclasses).
- 返回类型:
- minbuffer(size)[源代码]¶
The linebuffer must guarantee the minimum requested size to be available.
In non-dqbuffer mode, this is always true (of course, until data is filled at the beginning, there are fewer values, but minperiod in the framework should account for this.
In dqbuffer mode, the buffer has to be adjusted for this if currently less than requested
- __len__()[源代码]¶
Return the linebuffer's length counter.
Performance optimization: Restore master branch's simple implementation - Directly return self.lencount (pre-calculated length value) - Remove all recursion checks, hasattr calls and complex logic - Performance improvement: from 0.611s to ~0.05s (92% improvement)
- buflen()[源代码]¶
Real data that can be currently held in the internal buffer
The internal buffer can be longer than the actual stored data to allow for "lookahead" operations. The real amount of data that is held/can be held in the buffer is returned
- __getitem__(ago)[源代码]¶
Get the value at a specified offset - optimized for hot path.
- 参数:
ago (int) -- Relative offset from current index (0=current, -1=previous, 1=next)
- 返回:
Value at the specified position
- get(ago=0, size=1)[源代码]¶
Returns a slice of the array relative to ago
- 关键字参数:
ago (int) -- Point of the array to which size will be added
size (to return the slice) -- size of the slice to return,
negative (can be positive or)
If size is positive ago will mark the end of the iterable and vice versa if size is negative
- 返回:
A slice of the underlying buffer
- __setitem__(ago, value)[源代码]¶
Sets a value at position "ago" and executes any associated bindings
- 关键字参数:
ago (int) -- Point of the array to which size will be added to return
slice (the)
value (variable) -- value to be set
Performance optimization: Use pre-calculated flags to avoid repeated hasattr and string operations
- set(value, ago=0)[源代码]¶
Sets a value at position "ago" and executes any associated bindings
- 关键字参数:
value (variable) -- value to be set
ago (int) -- Point of the array to which size will be added to return
slice (the)
PERF: Uses pre-calculated _is_datetime_line and _default_value flags instead of hasattr/isinstance checks on every call.
- home()[源代码]¶
Rewinds the logical index to the beginning
The underlying buffer remains untouched and the actual len can be found out with buflen
- forward(value=nan, size=1)[源代码]¶
Moves the logical index forward and enlarges the buffer as much as needed
- 关键字参数:
value (variable) -- value to be set in new positions
size (int) -- How many extra positions to enlarge the buffer
- backwards(size=1, force=False)[源代码]¶
Moves the logical index backwards and reduces the buffer as much as needed
- safe_backwards(size=1)[源代码]¶
Safely move the index backwards without raising errors.
- 参数:
size -- Number of positions to move backwards.
- 返回:
True if index is still >= 0 after moving, False otherwise.
- 返回类型:
- rewind(size=1)[源代码]¶
Rewind the buffer by decreasing idx and lencount.
- 参数:
size -- Number of positions to rewind.
- extend(value=nan, size=0)[源代码]¶
Extends the underlying array with positions that the index will not reach
- 关键字参数:
value (variable) -- value to be set in new positins
size (int) -- How many extra positions to enlarge the buffer
The purpose is to allow for lookahead operations or to be able to set values in the buffer "future"
- addbinding(binding)[源代码]¶
Adds another line binding
- 关键字参数:
binding (LineBuffer) -- another line that must be set when this line
value (becomes a)
- plot(idx=0, size=None)[源代码]¶
Returns a slice of the array relative to the real zero of the buffer
- 关键字参数:
This is a variant of getzero that unless told otherwise returns the entire buffer, which is usually the idea behind plottint (all must be plotted)
- 返回:
A slice of the underlying buffer
- bind2line(binding=0)¶
Stores a binding to another line. "Binding" can be an index or a name
- __call__(ago=None)[源代码]¶
Returns either the current value (ago=None) or a delayed LineBuffer that fetches the value which is "ago" periods before. Useful to have the closing price 5 bars before: close(-5)
- datetime(ago=0, tz=None, naive=True)[源代码]¶
Get the datetime value at the specified offset.
- 参数:
ago -- Number of periods to look back (0=current, -1=previous).
tz -- Timezone to apply. If None, uses self._tz.
naive -- If True, return naive datetime without timezone info.
- 返回:
Datetime object representing the timestamp.
- 返回类型:
datetime
- 抛出:
IndexError -- If the requested position is out of bounds for data feeds.
- date(ago=0, tz=None, naive=True)[源代码]¶
Get the date component of the datetime value at the specified offset.
- 参数:
ago -- Number of periods to look back (0=current, -1=previous).
tz -- Timezone to apply. If None, uses self._tz.
naive -- If True, return naive date without timezone info.
- 返回:
Date object representing the date portion of the timestamp.
- 返回类型:
date
- 抛出:
IndexError -- If the requested position is out of bounds for data feeds.
- time(ago=0, tz=None, naive=True)[源代码]¶
Get the time component of the datetime value at the specified offset.
- 参数:
ago -- Number of periods to look back (0=current, -1=previous).
tz -- Timezone to apply. If None, uses self._tz.
naive -- If True, return naive time without timezone info.
- 返回:
Time object representing the time portion of the timestamp.
- 返回类型:
time
- tm_raw(ago=0)[源代码]¶
Returns a localtime/gmtime like time.struct_time object which is compatible with strftime formatting.
The time zone of the struct_time is naive
- tm(ago=0)[源代码]¶
Returns a localtime/gmtime like time.struct_time object which is compatible with strftime formatting.
The time zone of the struct_time is naive
- tm_lt(other, ago=0)[源代码]¶
Returns True if the time carried by this line's index "ago" is lower than the time carried by the "other" line
- tm_le(other, ago=0)[源代码]¶
Returns True if the time carried by this line's index "ago" is lower than or equal to the time carried by the "other" line
- tm_eq(other, ago=0)[源代码]¶
Returns True if the time carried by this line's index "ago" is equal to the time carried by the "other" line
- tm_gt(other, ago=0)[源代码]¶
Returns True if the time carried by this line's index "ago" is greater than the time carried by the "other" line
- tm_ge(other, ago=0)[源代码]¶
Returns True if the time carried by this line's index "ago" is greater than or equal to the time carried by the "other" line
- class backtrader.linebuffer.LineActionsCache[源代码]¶
基类:
objectCache system for LineActions to avoid repetitive calculations
- class backtrader.linebuffer.LineActionsMixin[源代码]¶
基类:
objectMixin to provide LineActions functionality without metaclass
- class backtrader.linebuffer.PseudoArray[源代码]¶
基类:
objectWrapper for non-array iterables to provide array-like access.
This class wraps iterables (including itertools.repeat) and provides array-like indexing access. It handles cases where the wrapped object doesn't support direct indexing.
- wrapped¶
The wrapped iterable object.
- _minperiod¶
Minimum period inherited from the wrapped object.
示例
>>> from itertools import repeat >>> pseudo = PseudoArray(repeat(1.0)) >>> print(pseudo[0]) 1.0
- class backtrader.linebuffer.LineActions[源代码]¶
基类:
LineBuffer,LineActionsMixin,ParamsMixinBase class for Line Clases with different lines, derived from a LineBuffer
- plotlines = <object object>¶
- static __new__(cls, *args, **kwargs)[源代码]¶
Handle data processing for indicators and other LineActions objects
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- getindicators()[源代码]¶
Get list of indicators using this line actions object.
- 返回:
Empty list for base LineActions (override in subclasses).
- 返回类型:
- qbuffer(savemem=0)[源代码]¶
Enable queued buffer mode for memory-efficient storage.
- 参数:
savemem -- Memory saving mode (0=normal, >0=enable cache mode).
- static arrayize(obj)[源代码]¶
Convert an object to an array-compatible object.
- 参数:
obj -- Object to convert. Can be a value, iterable, or array-like.
- 返回:
The original object if it has an array attribute, otherwise a LineNum or PseudoArray wrapper.
- frompackages = ()¶
- packages = ()¶
- backtrader.linebuffer.LineDelay(a, ago=0, **kwargs)[源代码]¶
Create a delayed line object.
- 参数:
a -- Source line object.
ago -- Number of periods to delay. Negative for lookback.
**kwargs -- Additional keyword arguments.
- 返回:
A delayed line object.
- 返回类型:
_LineDelay or _LineForward
- backtrader.linebuffer.LineNum(num)[源代码]¶
Create a constant line from a number.
- 参数:
num -- The constant value.
- 返回:
A line object that always returns the constant value.
- 返回类型:
_LineDelay
- class backtrader.linebuffer.LinesOperation[源代码]¶
基类:
LineActionsOperation between two line objects (binary operations).
This class represents binary operations (addition, subtraction, etc.) between two line objects. The result is a new line that contains the element-wise operation result.
- operation¶
The binary function to apply (e.g., operator.add).
- a¶
First operand (left-hand side).
- b¶
Second operand (right-hand side).
- r¶
If True, reverse operation order.
- _parent_a¶
Parent indicator for operand a.
- _parent_b¶
Parent indicator for operand b.
示例
>>> result = LinesOperation(indicator1, indicator2, operator.sub) >>> # result[0] = indicator1[0] - indicator2[0]
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- __getitem__(ago)[源代码]¶
CRITICAL FIX: Override __getitem__ to compute value dynamically from source operands.
This ensures correct values in runonce mode where LinesOperation's _idx may not be properly advanced because it's not registered as IndType.
- next()[源代码]¶
Calculate and set the operation result for the current bar.
Performs the binary operation on the current values of both operands and stores the result at position 0.
- once(start, end)[源代码]¶
Calculate operation results in batch mode (runonce).
- 参数:
start -- Starting index.
end -- Ending index.
- frompackages = ()¶
- packages = ()¶
- class backtrader.linebuffer.LineOwnOperation[源代码]¶
基类:
LineActionsOperation on a single line object (unary operations).
This class represents unary operations (negation, absolute value, etc.) on a single line object. The result is a new line that contains the element-wise operation result.
- operation¶
The unary function to apply (e.g., operator.neg).
- a¶
The operand (line object).
- _parent_a¶
Parent indicator for the operand.
示例
>>> result = LineOwnOperation(indicator, operator.neg) >>> # result[0] = -indicator[0]
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- frompackages = ()¶
- packages = ()¶
- __getitem__(ago)[源代码]¶
CRITICAL FIX: Override __getitem__ to compute value dynamically from source operand.
- next()[源代码]¶
Calculate and set the unary operation result for the current bar.
Performs the unary operation on the current value of the operand and stores the result at position 0.