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[源代码]

基类:object

Minimal 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[源代码]

基类:object

Minimal owner implementation for observers and analyzers.

Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.

__init__()[源代码]

Initialize minimal owner with default attributes.

Sets up basic attributes needed for observers and analyzers when the actual owner is not available.

class backtrader.lineseries.MinimalClock[源代码]

基类:object

Minimal 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.

buflen()[源代码]

Return buffer length.

返回:

Always returns 1 for minimal clock.

返回类型:

int

__reduce__()[源代码]

Support pickling for multiprocessing.

class backtrader.lineseries.LineAlias[源代码]

基类:object

Descriptor 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.

__set__(obj, value)[源代码]

A line cannot be "set" once it has been created. But the values inside the line can be "set". This is achieved by adding a binding to the line inside "value"

class backtrader.lineseries.LinesManager[源代码]

基类:object

Manager for lines operations without metaclass

class backtrader.lineseries.Lines[源代码]

基类:object

Defines 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.

返回类型:

tuple

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

__len__()[源代码]

Return the number of lines

size()[源代码]

Return the number of lines excluding extra lines.

返回:

Number of main lines.

返回类型:

int

fullsize()[源代码]

Return the total number of lines including extra lines.

返回:

Total number of lines.

返回类型:

int

extrasize()[源代码]

Return the number of extra lines.

返回:

Number of extra lines.

返回类型:

int

get(ago=0, size=1, line=0)[源代码]

Get a slice of values from a specific line.

参数:
  • ago -- Number of periods to look back (0=current).

  • size -- Number of values to return.

  • line -- Line index to get values from.

返回:

Slice of values from the specified line.

返回类型:

list or array

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()[源代码]

Reset all lines to their initial state.

home()[源代码]

Reset all lines to the home position (beginning).

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.

返回类型:

int

__getattr__(name)[源代码]

Handle missing attributes, especially _owner for observers

__setattr__(name, value)[源代码]

Handle attribute setting, especially _owner and line bindings

class backtrader.lineseries.LineSeriesMixin[源代码]

基类:object

Mixin to provide LineSeries functionality without metaclass

classmethod __init_subclass__(**kwargs)[源代码]

Called when a class is subclassed - replaces metaclass functionality

class backtrader.lineseries.LineSeries[源代码]

基类:LineMultiple, LineSeriesMixin, ParamsMixin

Base 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[源代码]

基类:object

Plot 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.

keys()[源代码]

Return list of public attribute names.

返回:

List of non-private, non-callable attribute names.

返回类型:

list

plotinfo = <backtrader.lineseries.LineSeries.PlotInfoObj object>
class PlotLinesObj[源代码]

基类:object

Plot lines configuration object for LineSeries.

Stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.

__init__()[源代码]

Initialize plotlines container.

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.

返回类型:

array

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).

plotlabel()[源代码]

Get the plot label for this LineSeries.

返回:

The plot label string.

返回类型:

str

__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).

home()[源代码]

Reset all lines to the home position (beginning).

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

property chkmin

Property to ensure chkmin is never None for TestStrategy

frompackages = ()
packages = ()
class backtrader.lineseries.LineSeriesStub[源代码]

基类:LineSeries

Simulates 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).

reset()[源代码]

Reset the line if not a slave.

home()[源代码]

Reset the line to home position if not a slave.

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).

minbuffer(size)[源代码]

Set minimum buffer size (no-op for stub).

参数:

size -- Minimum buffer size.

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.