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[源代码]¶
基类:
OHLCDateTimeBase 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.
- 返回类型:
- 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.
- 返回类型:
- 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,
Cerebrowill deactivatepreloadandrunoncebecause a live data source must be fetched tick by tick (or bar by bar)
- qbuffer(savemem=0, replaying=False)[源代码]¶
Apply queued buffering to all lines.
- 参数:
savemem -- Memory saving mode.
replaying -- Whether replaying is active.
- clone(**kwargs)[源代码]¶
Create a clone of this data feed.
- 参数:
**kwargs -- Additional keyword arguments for the clone.
- 返回:
A cloned data feed.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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.
- 返回类型:
- 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[源代码]¶
-
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[源代码]¶
基类:
objectBase 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.
- 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.
- 返回类型:
- class backtrader.feed.CSVDataBase[源代码]¶
基类:
DataBaseBase 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_loadwhich 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).
- preload()[源代码]¶
Preload all data from the CSV file.
Loads all available data and closes the file handle.
- frompackages = ()¶
- packages = ()¶
- class backtrader.feed.CSVFeedBase[源代码]¶
基类:
FeedBaseBase class for CSV feed containers.
Manages CSV data feeds with support for base path prefixing.
- class backtrader.feed.DataClone[源代码]¶
-
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).
- 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 = ()¶