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.
Example
Accessing lines by name: >>> obj.lines.close # Access the ‘close’ line >>> obj.lines[0] # Access the first line
- class backtrader.lineseries.MinimalData[source]¶
Bases:
objectMinimal data replacement for missing data0, data1, etc. attributes.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- __init__()[source]¶
Initialize minimal data with pre-filled array.
Creates a pre-filled array to prevent index errors when accessing missing data attributes.
- __getitem__(key)[source]¶
Get item from the array at the specified index offset.
- Parameters:
key – Index offset from the current position (_idx).
- Returns:
Value at the computed index, or 0.0 if index is invalid.
- Return type:
- class backtrader.lineseries.MinimalOwner[source]¶
Bases:
objectMinimal owner implementation for observers and analyzers.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- class backtrader.lineseries.MinimalClock[source]¶
Bases:
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__()[source]¶
Initialize minimal clock with default attributes.
Sets up basic attributes needed for clock functionality when the actual clock is not available.
- __len__()[source]¶
Return the length of the minimal clock.
- Returns:
Always returns 0 for minimal clock.
- Return type:
- class backtrader.lineseries.LineAlias[source]¶
Bases:
objectDescriptor class that store a line reference and returns that line from the owner
- Keyword Arguments:
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)[source]¶
Initialize the line alias descriptor.
- Parameters:
line – Index of the line in the owner’s lines buffer.
- class backtrader.lineseries.LinesManager[source]¶
Bases:
objectManager for lines operations without metaclass
- class backtrader.lineseries.Lines[source]¶
Bases:
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()[source]¶
Get all line aliases for this class.
- Returns:
Tuple of line alias names.
- Return type:
- itersize()[source]¶
Return an iterator over the lines.
- Returns:
Iterator over lines from index 0 to size().
- Return type:
iterator
- __init__(initlines=None)[source]¶
Create the lines recording during “_derive” or else use the provided “initlines”
- __iter__()[source]¶
Allow proper iteration over lines without calling __getitem__ for each index.
- Returns:
Iterator over the lines list.
- Return type:
iterator
- __len__()[source]¶
Return the number of lines.
- Returns:
Number of lines in the lines list.
- Return type:
- size()[source]¶
Return the number of lines excluding extra lines.
- Returns:
Number of main lines.
- Return type:
- fullsize()[source]¶
Return the total number of lines including extra lines.
- Returns:
Total number of lines.
- Return type:
- __getitem__(line)[source]¶
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.
- Parameters:
line – Index of the line to retrieve.
- Returns:
- The line at the specified index, or None if
the index exceeds the maximum reasonable limit.
- Return type:
- __setitem__(line, value)[source]¶
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
- Parameters:
line – Line index or name to set.
value – Value to assign (scalar, indicator, or iterable).
- forward(value=0.0, size=1)[source]¶
Forward all lines by the specified size.
- Parameters:
value – Value to use for forwarding (default: 0.0).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move all lines backward by the specified size.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind all lines by decreasing idx and lencount.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend all lines with additional positions.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- advance(size=1)[source]¶
Advance all lines by increasing idx.
- Parameters:
size – Number of positions to advance (default: 1).
- buflen(line=0)[source]¶
Get the buffer length of a specific line.
- Parameters:
line – Index of the line (default: 0).
- Returns:
Buffer length of the specified line.
- Return type:
- __getattr__(name)[source]¶
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[source]¶
Bases:
objectMixin to provide LineSeries functionality without metaclass
- class backtrader.lineseries.LineSeries[source]¶
Bases:
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.
Example
Accessing lines by name or index: >>> obj = LineSeries() >>> obj.lines.close # Named access >>> obj.lines[0] # Index access
- static __new__(cls, *args, **kwargs)[source]¶
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[source]¶
Bases:
objectPlot information object for LineSeries.
Stores plotting configuration attributes that control how the LineSeries is displayed in plots.
- __init__()[source]¶
Initialize plotinfo with default values.
Sets up default plotting attributes including plot status, plot master, and legend location.
- get(key, default=None)[source]¶
Standard get method for compatibility
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotinfo = <backtrader.lineseries.LineSeries.PlotInfoObj object>¶
- class PlotLinesObj[source]¶
Bases:
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)[source]¶
Standard get method for compatibility
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotlines = <backtrader.lineseries.LineSeries.PlotLinesObj object>¶
- csv = True¶
- property array¶
Get the array of the first line.
- Returns:
The underlying array of the first line.
- Return type:
- property line¶
Return the first line (lines[0]) for single-line indicators.
- Returns:
The first line in the lines collection.
- Return type:
- property l¶
Alias for lines - used in indicator next() methods like self.l.sma[0].
- Returns:
The lines container object.
- Return type:
- __getattr__(name)[source]¶
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)[source]¶
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__()[source]¶
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)[source]¶
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)[source]¶
Set a line value by index.
Delegates to the Lines.__setitem__ method which handles line assignments properly including binding for indicators.
- Parameters:
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).
- plotlabel()[source]¶
Get the plot label for this LineSeries.
- Returns:
The plot label string.
- Return type:
- __call__(ago=None, line=-1)[source]¶
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)[source]¶
Forward all lines by the specified size.
- Parameters:
value – Value to use for forwarding (default: 0.0).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move all lines backward by the specified size.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind all lines by decreasing idx and lencount.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend all lines with additional positions.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- reset(value=0.0)[source]¶
Reset all lines to their initial state.
- Parameters:
value – Value to use for reset (default: 0.0).
- advance(size=1)[source]¶
Advance all lines by increasing idx.
- Parameters:
size – Number of positions to advance (default: 1).
- size()[source]¶
Return the number of lines in this LineSeries.
- Returns:
Number of main lines (excluding extra lines).
- Return type:
- 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.
- Returns:
The chkmin value, or 30 as a safe default.
- Return type:
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineseries.LineSeriesStub[source]¶
Bases:
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)[source]¶
Forward the line if not a slave.
- Parameters:
value – Value to use for forwarding (default: 0.0).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move the line backward if not a slave.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind the line if not a slave.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend the line if not a slave.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- advance(size=1)[source]¶
Advance the line if not a slave.
- Parameters:
size – Number of positions to advance (default: 1).
- qbuffer()[source]¶
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)[source]¶
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.
- Parameters:
size – Minimum buffer size (ignored in stub).
- frompackages = ()¶
- packages = ()¶
- backtrader.lineseries.LineSeriesMaker(arg, slave=False)[source]¶
Create a LineSeries from a single line or return existing LineSeries.
- Parameters:
arg – A single line or LineSeries object.
slave – If True, mark the created stub as a slave.
- Returns:
The original LineSeries if arg is already a LineSeries, otherwise a LineSeriesStub wrapping the line.