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

示例

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

class backtrader.feed.AbstractDataBase[源代码]

基类: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.

示例

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

Convert datetime to internal numeric format.

参数:

dt -- datetime object to convert.

返回:

Internal numeric representation of the datetime.

返回类型:

float

num2date(dt=None, tz=None, naive=True)[源代码]

Convert internal numeric format to datetime.

参数:
  • dt -- Numeric datetime value (uses current if None).

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

  • naive -- Return naive datetime if True.

返回:

Converted datetime object.

返回类型:

datetime

haslivedata()[源代码]

Check if this data feed has live data.

返回:

False for base class, override for live data feeds.

返回类型:

bool

do_qcheck(onoff, qlapse)[源代码]

Calculate wait interval for queue checking.

参数:
  • onoff -- Whether queue checking is enabled.

  • qlapse -- Time elapsed since last check.

islive()[源代码]

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

Add arguments to notification queue

get_notifications()[源代码]

Return the pending "store" notifications

getfeed()[源代码]

Get the parent feed object.

返回:

The parent feed instance.

返回类型:

FeedBase or None

qbuffer(savemem=0, replaying=False)[源代码]

Apply queued buffering to all lines.

参数:
  • savemem -- Memory saving mode.

  • replaying -- Whether replaying is active.

start()[源代码]

Start the data feed.

Resets internal queues and sets initial status to CONNECTED.

stop()[源代码]

Stop the data feed.

Override in subclasses for cleanup.

clone(**kwargs)[源代码]

Create a clone of this data feed.

参数:

**kwargs -- Additional keyword arguments for the clone.

返回:

A cloned data feed.

返回类型:

DataClone

copyas(_dataname, **kwargs)[源代码]

Copy the data feed with a different name.

参数:
  • _dataname -- New name for the data feed.

  • **kwargs -- Additional keyword arguments.

返回:

A cloned data feed with the new name.

返回类型:

DataClone

setenvironment(env)[源代码]

Keep a reference to the environment

getenvironment()[源代码]

Get the cerebro environment reference.

返回:

The cerebro environment instance.

addfilter_simple(f, *args, **kwargs)[源代码]

Add a simple filter wrapper to this data feed.

参数:
  • f -- Filter function to apply.

  • *args -- Positional arguments for the filter.

  • **kwargs -- Keyword arguments for the filter.

addfilter(p, *args, **kwargs)[源代码]

Add a filter to this data feed.

参数:
  • p -- Filter class or instance.

  • *args -- Positional arguments for filter creation.

  • **kwargs -- Keyword arguments for filter creation.

compensate(other)[源代码]

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

advance_peek()[源代码]

Peek at the datetime of the next bar.

返回:

Numeric datetime of next bar, or inf if unavailable.

返回类型:

float

advance(size=1, datamaster=None, ticks=True)[源代码]

Advance the data feed by the specified size.

参数:
  • 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)[源代码]

Move to the next bar.

参数:
  • datamaster -- Master data feed for synchronization.

  • ticks -- Whether to process tick data.

返回:

True if a bar is available, False otherwise.

返回类型:

bool

preload()[源代码]

Preload all available data from the data feed.

Loads all bars and resets position to the beginning.

load()[源代码]

Load the next bar from the data feed.

返回:

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

返回类型:

bool

This method handles:
  • Forwarding the data pointer

  • Processing filters

  • Checking date boundaries

resample(**kwargs)[源代码]

Add a resampling filter to this data feed.

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

参数:

**kwargs -- Arguments for the Resampler filter.

replay(**kwargs)[源代码]

Add a replay filter to this data feed.

Replay filters process tick data into bars with precise control.

参数:

**kwargs -- Arguments for the Replayer filter.

frompackages = ()
packages = ()
class backtrader.feed.DataBase[源代码]

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

基类:object

Base class for feed containers.

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

__init__(**kwargs)[源代码]

Initialize the feed base.

参数:

**kwargs -- Keyword arguments for parameters.

start()[源代码]

Start all managed data feeds.

stop()[源代码]

Stop all managed data feeds.

getdata(dataname, name=None, **kwargs)[源代码]

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

参数:
  • dataname -- Data source identifier (filename, URL, etc.).

  • name -- Display name for the data feed.

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

返回:

The created or retrieved data feed instance.

返回类型:

DataBase

class backtrader.feed.CSVDataBase[源代码]

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

Start the CSV data feed.

Opens the CSV file and optionally skips headers.

stop()[源代码]

Stop the CSV data feed.

Closes the CSV file if open.

preload()[源代码]

Preload all data from the CSV file.

Loads all available data and closes the file handle.

frompackages = ()
packages = ()
class backtrader.feed.CSVFeedBase[源代码]

基类:FeedBase

Base class for CSV feed containers.

Manages CSV data feeds with support for base path prefixing.

__init__(basepath='', **kwargs)[源代码]

Initialize the CSV feed base.

参数:
  • basepath -- Base path to prepend to data file names.

  • **kwargs -- Additional keyword arguments for parameters.

class backtrader.feed.DataClone[源代码]

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

Start the data clone.

Initializes internal tracking variables.

preload()[源代码]

Preload data from the source data feed.

After preloading, resets the source data's position.

advance(size=1, datamaster=None, ticks=True)[源代码]

Advance the data clone by the specified size.

参数:
  • size -- Number of bars to advance.

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

  • ticks -- Whether to process tick data.

frompackages = ()
packages = ()