backtrader.feed module

Data Feed Module - Financial data feed implementations.

This module provides the base classes and implementations for data feeds in backtrader. Data feeds are the source of price/volume data for strategies and indicators.

Key Classes:

AbstractDataBase: Base class for all data feeds with core functionality. DataBase: Full-featured data feed with replay/resample support. CSVDataBase: Base class for CSV file data feeds. FeedBase: Base for live/real-time data feeds.

Data feeds provide:
  • OHLCV (Open, High, Low, Close, Volume) data

  • Timeline management and session handling

  • Replay and resampling capabilities

  • Live data support for trading

Example

Creating a custom data feed: >>> class MyDataFeed(CSVDataBase): … params = ((‘dataname’, ‘data.csv’),)

class backtrader.feed.AbstractDataBase[source]

Bases: OHLCDateTime

Base class for all data feed implementations.

Provides the core functionality for data feeds including: - Data loading and preprocessing - Timeline management - Session handling - Live data support - Notification system for data status changes

States:

CONNECTED, DISCONNECTED, CONNBROKEN, DELAYED, LIVE, NOTSUBSCRIBED, NOTSUPPORTED_TF, UNKNOWN

Params:

dataname: Data source identifier (filename, URL, etc.). name: Display name for the data feed. compression: Timeframe compression factor. timeframe: TimeFrame period (Days, Minutes, etc.). fromdate: Start date for data filtering. todate: End date for data filtering. sessionstart: Session start time. sessionend: Session end time. filters: List of data filters to apply. tz: Output timezone. tzinput: Input timezone. qcheck: Timeout in seconds for live event checking. calendar: Trading calendar to use.

Example

>>> data = AbstractDataBase(dataname='data.csv')
>>> cerebro.adddata(data)
CONNECTED = 0
DISCONNECTED = 1
CONNBROKEN = 2
DELAYED = 3
LIVE = 4
NOTSUBSCRIBED = 5
NOTSUPPORTED_TF = 6
UNKNOWN = 7
__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).

resampling = 0
replaying = 0
date2num(dt)[source]

Convert datetime to internal numeric format.

Parameters:

dt – datetime object to convert.

Returns:

Internal numeric representation of the datetime.

Return type:

float

num2date(dt=None, tz=None, naive=True)[source]

Convert internal numeric format to datetime.

Parameters:
  • dt – Numeric datetime value (uses current if None).

  • tz – Timezone to use (uses feed tz if None).

  • naive – Return naive datetime if True.

Returns:

Converted datetime object.

Return type:

datetime

haslivedata()[source]

Check if this data feed has live data.

Returns:

False for base class, override for live data feeds.

Return type:

bool

do_qcheck(onoff, qlapse)[source]

Calculate wait interval for queue checking.

Parameters:
  • onoff – Whether queue checking is enabled.

  • qlapse – Time elapsed since last check.

islive()[source]

If this returns True, Cerebro will deactivate preload and runonce because a live data source must be fetched tick by tick (or bar by bar)

put_notification(status, *args, **kwargs)[source]

Add arguments to notification queue

get_notifications()[source]

Return the pending “store” notifications

getfeed()[source]

Get the parent feed object.

Returns:

The parent feed instance.

Return type:

FeedBase or None

qbuffer(savemem=0, replaying=False)[source]

Apply queued buffering to all lines.

Parameters:
  • savemem – Memory saving mode.

  • replaying – Whether replaying is active.

start()[source]

Start the data feed.

Resets internal queues and sets initial status to CONNECTED.

stop()[source]

Stop the data feed.

Override in subclasses for cleanup.

clone(**kwargs)[source]

Create a clone of this data feed.

Parameters:

**kwargs – Additional keyword arguments for the clone.

Returns:

A cloned data feed.

Return type:

DataClone

copyas(_dataname, **kwargs)[source]

Copy the data feed with a different name.

Parameters:
  • _dataname – New name for the data feed.

  • **kwargs – Additional keyword arguments.

Returns:

A cloned data feed with the new name.

Return type:

DataClone

setenvironment(env)[source]

Keep a reference to the environment

getenvironment()[source]

Get the cerebro environment reference.

Returns:

The cerebro environment instance.

addfilter_simple(f, *args, **kwargs)[source]

Add a simple filter wrapper to this data feed.

Parameters:
  • f – Filter function to apply.

  • *args – Positional arguments for the filter.

  • **kwargs – Keyword arguments for the filter.

addfilter(p, *args, **kwargs)[source]

Add a filter to this data feed.

Parameters:
  • p – Filter class or instance.

  • *args – Positional arguments for filter creation.

  • **kwargs – Keyword arguments for filter creation.

compensate(other)[source]

Call it to let the broker know that actions on this asset will compensate open positions in another

advance_peek()[source]

Peek at the datetime of the next bar.

Returns:

Numeric datetime of next bar, or inf if unavailable.

Return type:

float

advance(size=1, datamaster=None, ticks=True)[source]

Advance the data feed by the specified size.

Parameters:
  • size – Number of bars to advance (default: 1).

  • datamaster – Master data feed for synchronization.

  • ticks – Whether to process tick data.

next(datamaster=None, ticks=True)[source]

Move to the next bar.

Parameters:
  • datamaster – Master data feed for synchronization.

  • ticks – Whether to process tick data.

Returns:

True if a bar is available, False otherwise.

Return type:

bool

preload()[source]

Preload all available data from the data feed.

Loads all bars and resets position to the beginning.

load()[source]

Load the next bar from the data feed.

Returns:

True if a bar was loaded, False if no more data.

Return type:

bool

This method handles:
  • Forwarding the data pointer

  • Processing filters

  • Checking date boundaries

resample(**kwargs)[source]

Add a resampling filter to this data feed.

Resampling converts data to a different timeframe (e.g., minutes to days).

Parameters:

**kwargs – Arguments for the Resampler filter.

replay(**kwargs)[source]

Add a replay filter to this data feed.

Replay filters process tick data into bars with precise control.

Parameters:

**kwargs – Arguments for the Replayer filter.

frompackages = ()
packages = ()
class backtrader.feed.DataBase[source]

Bases: AbstractDataBase

Full-featured data feed class.

Inherits all functionality from AbstractDataBase. This is the standard data feed class for most use cases.

frompackages = ()
packages = ()
class backtrader.feed.FeedBase[source]

Bases: object

Base class for feed containers.

Manages multiple data feeds and provides parameter processing without using metaclasses.

__init__(**kwargs)[source]

Initialize the feed base.

Parameters:

**kwargs – Keyword arguments for parameters.

start()[source]

Start all managed data feeds.

stop()[source]

Stop all managed data feeds.

getdata(dataname, name=None, **kwargs)[source]

Get or create a data feed and add it to the managed datas.

Parameters:
  • dataname – Data source identifier (filename, URL, etc.).

  • name – Display name for the data feed.

  • **kwargs – Additional parameters for the data feed.

Returns:

The created or retrieved data feed instance.

Return type:

DataBase

class backtrader.feed.CSVDataBase[source]

Bases: DataBase

Base class for classes implementing CSV DataFeeds

The class takes care of opening the file, reading the lines and tokenizing them.

Subclasses do only need to override:

  • _loadline(tokens)

The return value of _loadline (True/False) will be the return value of _load which has been overriden by this base class

f = None
__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).

start()[source]

Start the CSV data feed.

Opens the CSV file and optionally skips headers.

stop()[source]

Stop the CSV data feed.

Closes the CSV file if open.

preload()[source]

Preload all data from the CSV file.

Loads all available data and closes the file handle.

frompackages = ()
packages = ()
class backtrader.feed.CSVFeedBase[source]

Bases: FeedBase

Base class for CSV feed containers.

Manages CSV data feeds with support for base path prefixing.

__init__(basepath='', **kwargs)[source]

Initialize the CSV feed base.

Parameters:
  • basepath – Base path to prepend to data file names.

  • **kwargs – Additional keyword arguments for parameters.

class backtrader.feed.DataClone[source]

Bases: AbstractDataBase

Clones an existing data feed.

Creates a new data feed that references an existing data feed. Useful for creating multiple views of the same data with different parameters or filters.

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

start()[source]

Start the data clone.

Initializes internal tracking variables.

preload()[source]

Preload data from the source data feed.

After preloading, resets the source data’s position.

advance(size=1, datamaster=None, ticks=True)[source]

Advance the data clone by the specified size.

Parameters:
  • size – Number of bars to advance.

  • datamaster – Master data feed for synchronization (unused).

  • ticks – Whether to process tick data.

frompackages = ()
packages = ()