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__.
- __init__()[源代码]¶
Initialize minimal data with pre-filled array.
Creates a pre-filled array to prevent index errors when accessing missing data attributes.
- 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.
- __init__()[源代码]¶
Initialize minimal clock with default attributes.
Sets up basic attributes needed for clock functionality when the actual clock is not available.
- __len__()[源代码]¶
Return the length of the minimal clock.
- 返回:
Always returns 0 for minimal clock.
- 返回类型:
- 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)
- __init__(line)[源代码]¶
Initialize the line alias descriptor.
- 参数:
line -- Index of the line in the owner's lines buffer.
- 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"
- __iter__()[源代码]¶
Allow proper iteration over lines without calling __getitem__ for each index.
- 返回:
Iterator over the lines list.
- 返回类型:
iterator
- fullsize()[源代码]¶
Return the total number of lines including extra lines.
- 返回:
Total number of lines.
- 返回类型:
- __getitem__(line)[源代码]¶
Get a line by index.
This method implements dynamic line creation - accessing an index beyond the current number of lines will create new lines up to a reasonable limit.
- 参数:
line -- Index of the line to retrieve.
- 返回:
- The line at the specified index, or None if
the index exceeds the maximum reasonable limit.
- 返回类型:
- __setitem__(line, value)[源代码]¶
Set a line by index with proper binding support.
This method handles different types of values: - Scalar values: Creates a LineNum (constant line) - Indicators: Binds the indicator's output line to the parent's line - LineBuffers: Adds binding for value propagation - Iterables: Creates a new line from the iterable values
- 参数:
line -- Line index or name to set.
value -- Value to assign (scalar, indicator, or iterable).
- 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).
- buflen(line=0)[源代码]¶
Get the buffer length of a specific line.
- 参数:
line -- Index of the line (default: 0).
- 返回:
Buffer length of the specified line.
- 返回类型:
- __getattr__(name)[源代码]¶
Handle missing attributes, especially _owner for observers.
PERF OPTIMIZATIONS: - Class-level frozenset for critical attrs (was recreated every call) - name[0] == '_' instead of startswith (2-3x faster) - Removed inspect.currentframe() stack walk (extremely expensive) - Reduced hasattr chains with try/except EAFP
- 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.
- get(key, default=None)[源代码]¶
Standard get method for compatibility
- 参数:
key -- Attribute name.
default -- Default value if attribute not found.
- 返回:
The attribute value or default.
- 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.
- get(key, default=None)[源代码]¶
Standard get method for compatibility
- 参数:
key -- Attribute name.
default -- Default value if attribute not found.
- 返回:
The attribute value or default.
- 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.
- 返回:
The first line in the lines collection.
- 返回类型:
- property l¶
Alias for lines - used in indicator next() methods like self.l.sma[0].
- 返回:
The lines container object.
- 返回类型:
- __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
- __setitem__(key, value)[源代码]¶
Set a line value by index.
Delegates to the Lines.__setitem__ method which handles line assignments properly including binding for indicators.
- 参数:
key -- Line index or name.
value -- Value to set.
- __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).
- size()[源代码]¶
Return the number of lines in this LineSeries.
- 返回:
Number of main lines (excluding extra lines).
- 返回类型:
- property chkmin¶
Property to ensure chkmin is never None for TestStrategy.
This property provides a safe default value for chkmin, which is used in testing to validate minimum period requirements.
- 返回:
The chkmin value, or 30 as a safe default.
- 返回类型:
- 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).
- qbuffer()[源代码]¶
Queue buffer operation (no-op for stub).
This method is a no-op in the stub implementation since the underlying line manages its own buffering.
- minbuffer(size)[源代码]¶
Set minimum buffer size (no-op for stub).
This method is a no-op in the stub implementation since the underlying line manages its own buffering.
- 参数:
size -- Minimum buffer size (ignored in stub).
- 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.