backtrader.lineseries module¶
LineSeries Module - Multi-line time-series data management.
This module defines the LineSeries class and related descriptors for classes that hold multiple lines at once. It provides the infrastructure for managing collections of line objects with named access.
- Key Classes:
LineSeries: Base class for objects with multiple lines. Lines: Container for multiple line objects with named access. LinesManager: Manages line operations and access. LineAlias: Descriptor for named line access. MinimalData/MinimalOwner/MinimalClock: Minimal implementations for edge cases.
示例
Accessing lines by name: >>> obj.lines.close # Access the 'close' line >>> obj.lines[0] # Access the first line
- class backtrader.lineseries.MinimalData[源代码]¶
基类:
objectMinimal data replacement for missing data0, data1, etc. attributes.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- class backtrader.lineseries.MinimalOwner[源代码]¶
基类:
objectMinimal owner implementation for observers and analyzers.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- class backtrader.lineseries.MinimalClock[源代码]¶
基类:
objectMinimal clock implementation used as a fallback when _clock is not set.
CRITICAL FIX: Defined at module level to support pickling for multiprocessing. Previously this was defined as a local class inside __getattribute__, which caused pickle failures during strategy optimization.
- class backtrader.lineseries.LineAlias[源代码]¶
基类:
objectDescriptor class that store a line reference and returns that line from the owner
- 关键字参数:
line (int) -- reference to the line that will be returned from
buffer (owner's lines)
As a convenience, the __set__ method of the descriptor is used not set the line reference because this is a constant along the live of the descriptor instance, but rather to set the value of the line at the instant '0' (the current one)
- class backtrader.lineseries.LinesManager[源代码]¶
基类:
objectManager for lines operations without metaclass
- class backtrader.lineseries.Lines[源代码]¶
基类:
objectDefines an "array" of lines which also has most of the interface of a LineBuffer class (forward, rewind, advance...).
This interface operations are passed to the lines held by self
The class can autosubclass itself (_derive) to hold new lines keeping them in the defined order.
- classmethod getlinealiases()[源代码]¶
Get all line aliases for this class.
- 返回:
Tuple of line alias names.
- 返回类型:
- itersize()[源代码]¶
Return an iterator over the lines.
- 返回:
Iterator over lines from index 0 to size().
- 返回类型:
iterator
- __init__(initlines=None)[源代码]¶
Create the lines recording during "_derive" or else use the provided "initlines"
- fullsize()[源代码]¶
Return the total number of lines including extra lines.
- 返回:
Total number of lines.
- 返回类型:
- forward(value=0.0, size=1)[源代码]¶
Forward all lines by the specified size.
- 参数:
value -- Value to use for forwarding (default: 0.0).
size -- Number of positions to forward (default: 1).
- backwards(size=1, force=False)[源代码]¶
Move all lines backward by the specified size.
- 参数:
size -- Number of positions to move backward (default: 1).
force -- If True, force the backward movement.
- rewind(size=1)[源代码]¶
Rewind all lines by decreasing idx and lencount.
- 参数:
size -- Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[源代码]¶
Extend all lines with additional positions.
- 参数:
value -- Value to use for extension (default: 0.0).
size -- Number of positions to add (default: 0).
- advance(size=1)[源代码]¶
Advance all lines by increasing idx.
- 参数:
size -- Number of positions to advance (default: 1).
- class backtrader.lineseries.LineSeriesMixin[源代码]¶
基类:
objectMixin to provide LineSeries functionality without metaclass
- class backtrader.lineseries.LineSeries[源代码]¶
基类:
LineMultiple,LineSeriesMixin,ParamsMixinBase class for objects with multiple time-series lines.
LineSeries provides the foundation for classes that manage multiple line objects, such as indicators with multiple output lines. It handles line creation, access, and management.
- lines¶
Container object holding all line instances.
- plotinfo¶
Plotting configuration object.
示例
Accessing lines by name or index: >>> obj = LineSeries() >>> obj.lines.close # Named access >>> obj.lines[0] # Index access
- static __new__(cls, *args, **kwargs)[源代码]¶
Instantiate lines class when creating LineSeries instances.
CRITICAL FIX: The lines attribute is set as a class by __init_subclass__, but it needs to be instantiated for each object instance.
- class PlotInfoObj[源代码]¶
基类:
objectPlot information object for LineSeries.
Stores plotting configuration attributes that control how the LineSeries is displayed in plots.
- __init__()[源代码]¶
Initialize plotinfo with default values.
Sets up default plotting attributes including plot status, plot master, and legend location.
- plotinfo = <backtrader.lineseries.LineSeries.PlotInfoObj object>¶
- class PlotLinesObj[源代码]¶
基类:
objectPlot lines configuration object for LineSeries.
Stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.
- plotlines = <backtrader.lineseries.LineSeries.PlotLinesObj object>¶
- csv = True¶
- property array¶
Get the array of the first line.
- 返回:
The underlying array of the first line.
- 返回类型:
- property line¶
Return the first line (lines[0]) for single-line indicators
- property l¶
Alias for lines - used in indicator next() methods like self.l.sma[0]
- __getattr__(name)[源代码]¶
High-frequency attribute resolution optimized for performance.
OPTIMIZATION NOTES: - Results are cached in __dict__ to avoid repeated lookups - Removed recursion guard overhead (rely on Python's natural recursion limit) - Use direct __dict__ access instead of getattr() to avoid triggering __getattr__ - Use index check (name[0]) instead of startswith() for speed
- __setattr__(name, value)[源代码]¶
Optimized attribute setter with minimal type checking.
OPTIMIZATION NOTES: - Use type() instead of isinstance() - faster for simple types - Use EAFP (try/except) instead of hasattr() to avoid double lookups - Minimize attribute access on value object
- __len__()[源代码]¶
Return length of LineSeries (number of data points)
OPTIMIZATION NOTES: - Cache lines[0] reference to avoid repeated indexing - Called 11M+ times, so optimization is critical
- __getitem__(key)[源代码]¶
Get value at index from primary line.
OPTIMIZATION NOTES: - Cache reference to lines[0] to avoid repeated indexing - Use fast NaN detection without isinstance/math.isnan - Minimal exception handling
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- __call__(ago=None, line=-1)[源代码]¶
Return either a delayed line or the data for a given index/name
- Possible calls:
self() -> current line
self(ago) -> delayed line by "ago" periods
self(-1) -> current line
self(line=-1) -> current line
self(line='close') -> current line by name
- forward(value=0.0, size=1)[源代码]¶
Forward all lines by the specified size.
- 参数:
value -- Value to use for forwarding (default: 0.0).
size -- Number of positions to forward (default: 1).
- backwards(size=1, force=False)[源代码]¶
Move all lines backward by the specified size.
- 参数:
size -- Number of positions to move backward (default: 1).
force -- If True, force the backward movement.
- rewind(size=1)[源代码]¶
Rewind all lines by decreasing idx and lencount.
- 参数:
size -- Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[源代码]¶
Extend all lines with additional positions.
- 参数:
value -- Value to use for extension (default: 0.0).
size -- Number of positions to add (default: 0).
- reset(value=0.0)[源代码]¶
Reset all lines to their initial state.
- 参数:
value -- Value to use for reset (default: 0.0).
- advance(size=1)[源代码]¶
Advance all lines by increasing idx.
- 参数:
size -- Number of positions to advance (default: 1).
- property chkmin¶
Property to ensure chkmin is never None for TestStrategy
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineseries.LineSeriesStub[源代码]¶
基类:
LineSeriesSimulates a LineMultiple object based on LineSeries from a single line
The index management operations are overriden to take into account if the line is a slave, i.e.:
The line reference is a line from many in a LineMultiple object
Both the LineMultiple object and the Line are managed by the same object
Were slave not to be taken into account, the individual line would, for example, be advanced twice:
Once under when the LineMultiple object is advanced (because it advances all lines it is holding
Again as part of the regular management of the object holding it
- extralines = 1¶
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- forward(value=0.0, size=1)[源代码]¶
Forward the line if not a slave.
- 参数:
value -- Value to use for forwarding (default: 0.0).
size -- Number of positions to forward (default: 1).
- backwards(size=1, force=False)[源代码]¶
Move the line backward if not a slave.
- 参数:
size -- Number of positions to move backward (default: 1).
force -- If True, force the backward movement.
- rewind(size=1)[源代码]¶
Rewind the line if not a slave.
- 参数:
size -- Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[源代码]¶
Extend the line if not a slave.
- 参数:
value -- Value to use for extension (default: 0.0).
size -- Number of positions to add (default: 0).
- advance(size=1)[源代码]¶
Advance the line if not a slave.
- 参数:
size -- Number of positions to advance (default: 1).
- frompackages = ()¶
- packages = ()¶
- backtrader.lineseries.LineSeriesMaker(arg, slave=False)[源代码]¶
Create a LineSeries from a single line or return existing LineSeries.
- 参数:
arg -- A single line or LineSeries object.
slave -- If True, mark the created stub as a slave.
- 返回:
The original LineSeries if arg is already a LineSeries, otherwise a LineSeriesStub wrapping the line.