Data Feeds

Data feeds provide market data to the backtesting engine.

Data Feeds Module - Data source implementations.

This module provides data feed implementations for various data sources including CSV files, pandas DataFrames, Yahoo Finance, Quandl, InfluxDB, and the unified bt_api_py live interface.

Data Feed Types:
  • CSV Feeds: GenericCSVData, BTCSV, MT4CSV, SierraChart, VChartCSV

  • Pandas: PandasData for pandas DataFrame integration

  • Online: Yahoo Finance, Quandl, BtApiFeed

  • Utilities: Chainer, RollOver for data manipulation

示例

Loading data from a CSV file: >>> data = bt.feeds.GenericCSVData( ... dataname='data.csv', ... datetime=0, ... open=1, ... high=2, ... low=3, ... close=4, ... volume=5 ... ) >>> cerebro.adddata(data)

class backtrader.feeds.Any[源代码]

基类:object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class backtrader.feeds.BacktraderCSV[源代码]

基类:CSVFeedBase

Backtrader CSV feed class.

Wrapper class for BacktraderCSVData feed functionality.

DataCls

BacktraderCSVData 的别名

class backtrader.feeds.BacktraderCSVData[源代码]

基类:CSVDataBase

Parses a self-defined CSV Data used for testing.

Specific parameters:

  • dataname: The filename to parse or a file-like object

frompackages = ()
packages = ()
class backtrader.feeds.BarBarrierPolicy[源代码]

基类:object

Time and quality policy shared by 23 and 24 consumers.

timeframe_seconds: float = 60.0
timeout_seconds: float = 2.0
max_quote_skew_ms: float = 500.0
__init__(timeframe_seconds=60.0, timeout_seconds=2.0, max_quote_skew_ms=500.0)
参数:
  • timeframe_seconds (float)

  • timeout_seconds (float)

  • max_quote_skew_ms (float)

返回类型:

None

class backtrader.feeds.BarBarrierReason[源代码]

基类:object

Stable result codes for evidence and barrier decisions.

READY = 'READY'
WAITING_FOR_LEGS = 'WAITING_FOR_LEGS'
WAITING_FOR_WATERMARK = 'WAITING_FOR_WATERMARK'
UNKNOWN_SYMBOL = 'UNKNOWN_SYMBOL'
SYMBOL_MISMATCH = 'SYMBOL_MISMATCH'
EXCHANGE_MISMATCH = 'EXCHANGE_MISMATCH'
CANDIDATE_MISMATCH = 'CANDIDATE_MISMATCH'
BUCKET_MISMATCH = 'BUCKET_MISMATCH'
SESSION_MISMATCH = 'SESSION_MISMATCH'
TRADING_DAY_MISMATCH = 'TRADING_DAY_MISMATCH'
GENERATION_MISMATCH = 'GENERATION_MISMATCH'
RULES_HASH_MISMATCH = 'RULES_HASH_MISMATCH'
CLOCK_DOMAIN_MISMATCH = 'CLOCK_DOMAIN_MISMATCH'
CLOCK_MODE_MISMATCH = 'CLOCK_MODE_MISMATCH'
CLOCK_MAPPING_MISSING = 'CLOCK_MAPPING_MISSING'
CLOCK_MAPPING_MISMATCH = 'CLOCK_MAPPING_MISMATCH'
CLOCK_INVALID = 'CLOCK_INVALID'
CLOCK_REGRESSION = 'CLOCK_REGRESSION'
SCOPE_RESET_REQUIRED = 'SCOPE_RESET_REQUIRED'
INVALID_BAR = 'INVALID_BAR'
SKIP_INCOMPLETE_MINUTE = 'SKIP_INCOMPLETE_MINUTE'
SKIP_BARRIER_TIMEOUT = 'SKIP_BARRIER_TIMEOUT'
FUTURE_DATA_REJECTED = 'FUTURE_DATA_REJECTED'
DUPLICATE_BAR = 'DUPLICATE_BAR'
REVISION_REJECTED = 'REVISION_REJECTED'
LATE_BAR_REJECTED = 'LATE_BAR_REJECTED'
FUTURE_SEAL_REJECTED = 'FUTURE_SEAL_REJECTED'
BLOCKED_QUOTE_CUTOFF = 'BLOCKED_QUOTE_CUTOFF'
BLOCKED_CROSS_LEG_SKEW = 'BLOCKED_CROSS_LEG_SKEW'
QUOTE_AFTER_CUTOFF = 'QUOTE_AFTER_CUTOFF'
QUOTE_AFTER_SEAL = 'QUOTE_AFTER_SEAL'
QUOTE_FUTURE_DATA = 'QUOTE_FUTURE_DATA'
QUOTE_SCOPE_MISMATCH = 'QUOTE_SCOPE_MISMATCH'
QUOTE_EXCHANGE_MISMATCH = 'QUOTE_EXCHANGE_MISMATCH'
QUOTE_IDENTITY_CONFLICT = 'QUOTE_IDENTITY_CONFLICT'
QUOTE_IDENTITY_MISSING = 'QUOTE_IDENTITY_MISSING'
QUOTE_TRADING_DAY_MISMATCH = 'QUOTE_TRADING_DAY_MISMATCH'
QUOTE_RULES_HASH_MISMATCH = 'QUOTE_RULES_HASH_MISMATCH'
QUOTE_QUALITY_INVALID = 'QUOTE_QUALITY_INVALID'
QUOTE_DUPLICATE = 'QUOTE_DUPLICATE'
QUOTE_NOT_IN_FROZEN_INPUT = 'QUOTE_NOT_IN_FROZEN_INPUT'
NO_FROZEN_INPUT = 'NO_FROZEN_INPUT'
class backtrader.feeds.BarBarrierResult[源代码]

基类:object

Result of one bar ingestion or clock advance.

reason: str
decision_input: MinuteDecisionInput | None = None
key: Tuple[Any, ...] | None = None
reset_warmup: bool = False
property ready: bool

Whether this result carries a complete decision input.

返回:

True when decision_input was produced, i.e. the barrier had all required legs closed for the bucket.

返回类型:

bool

__init__(reason, decision_input=None, key=None, reset_warmup=False)
参数:
返回类型:

None

class backtrader.feeds.BarEvidence[源代码]

基类:object

An immutable feed-produced closed OHLCV bar.

The object carries both trade-bar provenance and the independently frozen quote cutoff used by the 24 minute consumer. quote_events are optional because the 23 consumer is deliberately bar-only.

symbol: str
exchange: str
bucket_start: Any
bucket_end: Any
available_at: Any
seal_received_mono: Any
trading_day: str
generation: int
session_segment: str
rules_hash: str
quality: Any = <object object>
volume_complete: Any = <object object>
first_ingest_seq: int = 0
last_ingest_seq: int = 0
quote_cutoff_seq: Any = <object object>
bar_id: str = ''
bar_sequence: int = 0
closure_reason: str = 'watermark'
watermark: Any = None
max_event_time: Any = None
open: float = 0.0
high: float = 0.0
low: float = 0.0
close: float = 0.0
volume: float = 0.0
openinterest: float = 0.0
quote_events: Tuple[Any, ...] = ()
clock_domain: Any = <object object>
clock_mode: Any = <object object>
seal_received_at: Any = <object object>
candidate_id: str = ''
timeframe_seconds: float | None = None
trade_count: int | None = None
complete: Any = <object object>
clock_mapping: Any = <object object>
to_dict()[源代码]

Return this bar evidence as a JSON-serialisable dict.

Every field is passed through _json_safe so the result can be written straight to the run receipt.

返回:

Identity, bucket bounds, availability and seal instants, generation and ingest sequence numbers, quality flags and OHLCV values for this bar.

返回类型:

Dict[str, Any]

__init__(symbol, exchange, bucket_start, bucket_end, available_at, seal_received_mono, trading_day, generation, session_segment, rules_hash, quality=<object object>, volume_complete=<object object>, first_ingest_seq=0, last_ingest_seq=0, quote_cutoff_seq=<object object>, bar_id='', bar_sequence=0, closure_reason='watermark', watermark=None, max_event_time=None, open=0.0, high=0.0, low=0.0, close=0.0, volume=0.0, openinterest=0.0, quote_events=(), clock_domain=<object object>, clock_mode=<object object>, seal_received_at=<object object>, candidate_id='', timeframe_seconds=None, trade_count=None, complete=<object object>, clock_mapping=<object object>)
参数:
  • symbol (str)

  • exchange (str)

  • bucket_start (Any)

  • bucket_end (Any)

  • available_at (Any)

  • seal_received_mono (Any)

  • trading_day (str)

  • generation (int)

  • session_segment (str)

  • rules_hash (str)

  • quality (Any)

  • volume_complete (Any)

  • first_ingest_seq (int)

  • last_ingest_seq (int)

  • quote_cutoff_seq (Any)

  • bar_id (str)

  • bar_sequence (int)

  • closure_reason (str)

  • watermark (Any)

  • max_event_time (Any)

  • open (float)

  • high (float)

  • low (float)

  • close (float)

  • volume (float)

  • openinterest (float)

  • quote_events (Tuple[Any, ...])

  • clock_domain (Any)

  • clock_mode (Any)

  • seal_received_at (Any)

  • candidate_id (str)

  • timeframe_seconds (float | None)

  • trade_count (int | None)

  • complete (Any)

  • clock_mapping (Any)

返回类型:

None

class backtrader.feeds.BarLeg[源代码]

基类:object

One exact expected instrument identity for a barrier.

symbol: str
exchange: str
__init__(symbol, exchange)
参数:
返回类型:

None

class backtrader.feeds.BtApiFeed[源代码]

基类:LiveBarCohortFeedMixin, LiveFeedBase

Data feed that backfills and streams bars through BtApiStore.

orderbook_as_ticks=True exposes each depth snapshot as a zero-volume midpoint tick bar before calling notify_orderbook. This gives native broker orders a valid feed price and clock even without trade/bar streams. It requires timeframe=TimeFrame.Ticks for legacy non-SDK adapters. SDK order-book events retain their unknown clock/freshness and are delivered only to notification callbacks; they never create midpoint bars.

__init__(*args, **kwargs)
property live_bar_cohort

Return the exact cohort installed by Cerebro for this feed, if any.

start()[源代码]

Start the feed, register it, and backfill if configured.

stop()[源代码]

Stop the feed.

islive()[源代码]

Return whether this feed has a configured live data source.

返回类型:

bool

haslivedata()[源代码]

Return whether a completed live bar is immediately available.

Pending raw ticks/orderbooks are realtime traffic, but they do not advance the strategy clock until they aggregate into a completed bar. Treating them as live data here makes Cerebro skip qcheck and spin while repeatedly draining ticks that produce no bar.

返回类型:

bool

bar_integrity_counts()[源代码]

Counts of dropped bars, including unknown and unfinished finality.

tick_ingest_error_counts()[源代码]

Counts of real-time SDK ticks dropped per finite ingestion error code.

OUT_OF_ORDER_EVENT_TIME counts ticks dropped because their exchange time went backwards (D62-38).

historical_warmup_active()[源代码]

Whether historical bars are still being replayed (D62-15a).

True while backfilled historical bars are still queued for delivery to the strategy. A live feed that is merely quiet (closed market, no ticks) is not warming up.

gateway_trade_qualification(*, expected_store, expected_instrument)[源代码]

Qualify only the Gateway Feed bound to this Store and instrument.

trade_qualification(now_monotonic_ns=None)[源代码]

Whether this feed's data may back a live order now (D62-21/27/28).

Separate from LIVE status (D62-15b) and computed afresh on every call: a quiet market makes the last tick expire. now_monotonic_ns defaults to this feed's monotonic clock (the clock param when injected, otherwise time.monotonic_ns()); it must be in the same monotonic domain as the ticks' received_monotonic_ns. Never raises for an unusable input: it is reported as a finite reason.

返回:

ok and the finite failure reasons.

返回类型:

FeedTradeQualification

line_bar_quality()[源代码]

Quality of the bar now at [0] on this feed's lines (iteration 62).

Returns a FeedLineBarQuality, or None when no bar was published by this feed or the lines no longer hold the bar it published last. A bar that entered the lines with incomplete volume (incomplete_volume_bars="lines") has complete=False, volume_complete=False and its volume flags in quality_flags; the same facts are on its BarEvent in notify_bar.

valuation_mark_max_age = None

Upper bound in seconds on how old the close of the current bar may be for valuation_mark(); None means one bar period plus receive_time_max_age. A caller may only tighten it.

valuation_mark_sources = frozenset({'local_aggregation', 'market_tick', 'provider_bar'})

a provider bar that the provider declared final (bar_final=True), a bar this feed closed from typed, quality-checked ticks by the event-time watermark, and, on a Tick timeframe, one typed tick whose own source and quality made it bar-eligible. Replayed bars and anything built from legacy (untyped) ticks are never a live mark.

Type:

Line sources valuation_mark() accepts

valuation_mark(max_age=None)[源代码]

Price on this feed's lines for strategy valuation (iteration 60, 60.11-A5/F6).

Returns (price: Decimal, as_of_utc: datetime, source: str). as_of_utc is the provider/exchange event time the price belongs to: a bar's close time, or a tick's own event time. Eligible only when the value on the lines is the one this feed itself published from an accepted source (valuation_mark_sources), its price is finite and positive, and now - as_of_utc (now from this feed's injected clock param, the wall clock otherwise) is neither negative beyond receive_time_max_age nor greater than the tighter of valuation_mark_max_age and max_age seconds. Otherwise raises ValueError whose code attribute is a finite reason; never guesses.

frompackages = ()
packages = ()
get_logging_health()[源代码]

Return the number of feed log-sink failures observed in this process.

class backtrader.feeds.Chainer[源代码]

基类:DataBase

Class that chains datas

islive()[源代码]

Returns True to notify Cerebro that preloading and runonce should be deactivated

__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 Chainer data feed.

Initializes all chained data feeds.

stop()[源代码]

Stop the Chainer data feed.

Stops all underlying data feeds.

get_notifications()[源代码]

Get notifications from the current data feed.

返回:

Notifications from active data feed or empty list.

返回类型:

list

frompackages = ()
packages = ()
class backtrader.feeds.ClockMapping[源代码]

基类:object

A caller-provided wall/monotonic mapping used for barrier deadlines.

The mapping is evidence, rather than a convenience conversion. It must carry the sampled anchor, its clock domain and generation, a named source, a finite error bound, an expiry, and the rules identity. Replay fixtures set synthetic=True explicitly; live evidence cannot use a synthetic mapping. No process clock is read here.

mapping_id: str
wall_utc_at_anchor: Any
mono_ns_at_anchor: int
clock_domain_id: str
connection_generation: int
source: str
error_bound_ns: int
valid_until_mono_ns: int
rules_hash: str
synthetic: bool = False
map_wall_to_mono_ns(wall_time)[源代码]

Map a wall time while refusing values outside this mapping's scope.

参数:

wall_time (Any)

返回类型:

int

validate_pair(wall_time, mono_seconds)[源代码]

Check one observed wall/monotonic pair against the error interval.

参数:
  • wall_time (Any)

  • mono_seconds (Any)

返回类型:

None

conservative_deadline_seconds(wall_deadline)[源代码]

Return the earliest monotonic deadline allowed by the error bound.

参数:

wall_deadline (Any)

返回类型:

float

to_dict()[源代码]

Return this clock mapping as a JSON-serialisable dict.

返回:

Anchor wall/monotonic instants, clock domain, connection generation, source, error bound, validity horizon, rules hash and the synthetic flag.

返回类型:

Dict[str, Any]

__init__(mapping_id, wall_utc_at_anchor, mono_ns_at_anchor, clock_domain_id, connection_generation, source, error_bound_ns, valid_until_mono_ns, rules_hash, synthetic=False)
参数:
  • mapping_id (str)

  • wall_utc_at_anchor (Any)

  • mono_ns_at_anchor (int)

  • clock_domain_id (str)

  • connection_generation (int)

  • source (str)

  • error_bound_ns (int)

  • valid_until_mono_ns (int)

  • rules_hash (str)

  • synthetic (bool)

返回类型:

None

class backtrader.feeds.CryptoHFTData[源代码]

基类:DataBase

Load historical exchange trades from CryptoHFTData.

Tick requests emit one OHLCV-shaped backtrader bar per trade. Second, minute, and daily requests aggregate the same trades into UTC-aligned bars. Use TimeFrame.Minutes with compression=60 for hourly bars.

fromdate and todate are required to avoid accidental unbounded high-frequency downloads. Naive datetimes are interpreted as UTC.

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

Download the requested trades and prepare chronological bars.

frompackages = ()
packages = ()
class backtrader.feeds.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.feeds.GenericCSV[源代码]

基类:CSVFeedBase

Generic CSV feed class.

Wrapper class for GenericCSVData feed functionality.

DataCls

GenericCSVData 的别名

class backtrader.feeds.GenericCSVData[源代码]

基类:CSVDataBase

Parses a CSV file according to the order and field presence defined by the parameters

Specific parameters (or specific meaning):

  • dataname: The filename to parse or a file-like object

  • The lines parameters (datetime, open, high ...) take numeric values

    A value of -1 indicates absence of that field in the CSV source

  • If time is present (parameter time >=0), the source contains separated fields for date and time, which will be combined

  • nullvalue

    Value that will be used if a value which should be there is missing (the CSV field is empty)

  • dtformat: Format used to parse the datetime CSV field. See the python strptime/strftime documentation for the format.

    If a numeric value is specified, it will be interpreted as follows

    • 1: The value is a Unix timestamp of a type int representing the number of seconds since Jan 1st, 1970

    • 2: The value is a Unix timestamp of a type float

    If a callable is passed

    • It will accept a string and return a datetime.datetime python instance

  • tmformat: Format used to parse the time CSV field if "present" (the default for the "time" CSV field is not to be present)

__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 Generic CSV data feed.

Sets up datetime conversion based on dtformat parameter.

load()[源代码]

Load one CSV bar through a narrow no-filter fast path.

frompackages = ()
packages = ()
class backtrader.feeds.InfluxDB[源代码]

基类:DataBase

InfluxDB data feed for time series market data.

Fetches OHLCV data from an InfluxDB time series database.

frompackages = (('influxdb', [('InfluxDBClient', 'idbclient')]), ('influxdb.exceptions', 'InfluxDBClientError'))
__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).

biter: Iterator[Any] | None
start()[源代码]

Start the InfluxDB data feed.

Connects to InfluxDB and executes query to fetch data.

packages = ()
exception backtrader.feeds.InfluxDBClientError[源代码]

基类:Exception

Exception raised for InfluxDB client errors.

class backtrader.feeds.MT4CSVData[源代码]

基类:GenericCSVData

Parses a Metatrader4 History center CSV exported file.

Specific parameters (or specific meaning):

  • dataname: The filename to parse or a file-like object

  • Uses GenericCSVData and simply modifies the params

frompackages = ()
packages = ()
class backtrader.feeds.MinuteDecisionInput[源代码]

基类:object

One frozen, same-scope multi-leg decision input.

key: Tuple[Any, ...]
bars: Mapping[str, BarEvidence]
bucket_start: datetime
bucket_end: datetime
common_available_at: datetime
bar_ids: Tuple[str, ...]
quote_cutoffs: Mapping[str, int]
accepted_quotes: Mapping[str, Tuple[Mapping[str, Any], ...]]
quote_rejections: Mapping[str, Tuple[str, ...]]
source_sequences: Mapping[str, Tuple[int, int]]
quality_report: Mapping[str, Any]
trading_day: str
generation: int
session_segment: str
rules_hash: str
candidate_id: str
clock_domain: str
clock_mode: str
barrier_ready_mono: float
deadline_mono: float
clock_mapping: ClockMapping
to_dict()[源代码]

Return this decision input as a JSON-serialisable dict.

返回:

The bucket key and bounds, the per-leg bar evidence, quote cutoffs, accepted quotes and rejections, source sequences, quality report, identity fields (trading day, generation, rules hash, candidate id) and the clock/deadline instants including the nested clock mapping.

返回类型:

Dict[str, Any]

__init__(key, bars, bucket_start, bucket_end, common_available_at, bar_ids, quote_cutoffs, accepted_quotes, quote_rejections, source_sequences, quality_report, trading_day, generation, session_segment, rules_hash, candidate_id, clock_domain, clock_mode, barrier_ready_mono, deadline_mono, clock_mapping)
参数:
返回类型:

None

class backtrader.feeds.MixedChannel[源代码]

基类:StreamingEventQueue

Streaming event queue that merges multiple channel groups into one stream.

The constructor flattens the per-group channel lists (channels, tick_channels, orderbook_channels, funding_channels) into a single merged_channels list and delegates to StreamingEventQueue. The remaining keyword arguments (preload_window, max_memory_mb, adaptive, batch_size) are forwarded unchanged.

__init__(channels=None, bars=None, tick_channels=None, orderbook_channels=None, funding_channels=None, preload_window=300.0, max_memory_mb=200, adaptive=True, batch_size=10000)[源代码]

Build a merged-channel streaming queue.

参数:
  • channels -- Optional iterable of generic event channels.

  • bars -- Optional iterable of pre-built bar objects. Copied into a list before being forwarded to the base class.

  • tick_channels -- Optional iterable of tick event channels.

  • orderbook_channels -- Optional iterable of order-book event channels.

  • funding_channels -- Optional iterable of funding-rate event channels.

  • preload_window -- Preload window size in seconds, forwarded to StreamingEventQueue.

  • max_memory_mb -- Soft memory cap (in MB) for the queue, forwarded to the base class.

  • adaptive -- Whether the queue should adapt its batching strategy, forwarded to the base class.

  • batch_size -- Default batch size, forwarded to the base class.

class backtrader.feeds.MultiLegBarBarrier[源代码]

基类:object

Causal two- or three-leg barrier for already-closed bars.

__init__(expected_legs=None, *, legs=None, candidate_id='', expected_rules_hash=None, clock_mapping=None, policy=None, timeframe_seconds=None, timeout_seconds=None, expected_clock_domain=None, clock_domain=None, clock_mode=None, expected_exchange='')[源代码]

Configure a causal barrier over two or three instrument legs.

参数:
  • expected_legs (Iterable[Any] | None) -- Legs the barrier must wait for; each entry is normalised to a BarLeg.

  • legs (Iterable[Any] | None) -- Alias for expected_legs, used when only this keyword is supplied.

  • candidate_id (str) -- Identifier of the candidate these bars belong to.

  • expected_rules_hash (str | None) -- Rules hash every leg must report, if pinned.

  • clock_mapping (ClockMapping | None) -- Mapping used to bound quote and bar deadlines.

  • policy (BarBarrierPolicy | None) -- Barrier policy; a default one is built when omitted.

  • timeframe_seconds (float | None) -- Bucket width; required when no policy supplies it.

  • timeout_seconds (float | None) -- Deadline budget for a bucket.

  • expected_clock_domain (str | None) -- Clock domain every leg must report.

  • clock_domain (str | None) -- Alias for expected_clock_domain.

  • clock_mode (str | None) -- Clock mode every leg must report.

  • expected_exchange (str) -- Exchange every leg is expected to belong to.

抛出:
  • ValueError -- If no legs are given, the leg count is not two or three, leg symbols are not unique, or required values disagree.

  • TypeError -- If clock_mapping is not a ClockMapping.

返回类型:

None

property pending_keys: Tuple[Tuple[Any, ...], ...]

Bucket keys that are still waiting for at least one leg.

返回:

Pending bucket keys, newest last.

返回类型:

Tuple[Tuple[Any, ...], ...]

property finalized_inputs: Mapping[Tuple[Any, ...], MinuteDecisionInput]

Read-only view of the retained completed decision inputs.

返回:

Bucket key to the decision input that was produced for it. Only the most recent _MAX_RETAINED_INPUTS buckets are kept.

返回类型:

Mapping[Tuple[Any, ...], MinuteDecisionInput]

property last_input: MinuteDecisionInput | None

Most recent decision input produced by this barrier.

返回:

The latest completed decision input, or None when the barrier has not produced one yet.

返回类型:

Optional[MinuteDecisionInput]

reset_scope(*, trading_day=None, generation=None, session_segment=None, rules_hash=None, clock_domain=None, clock_mode=None, clock_mapping=None, candidate_id=None)[源代码]

Bind a newly authorized scope and recorded wall/mono mapping.

An empty call deliberately does not reopen the barrier. It retires any pending scope and leaves the barrier requiring a complete declaration, which prevents reset_scope() from being used as a cache-clearing back-fill operation. A real reset must state every time/identity dimension and provide the new mapping.

参数:
  • trading_day (str | None)

  • generation (int | None)

  • session_segment (str | None)

  • rules_hash (str | None)

  • clock_domain (str | None)

  • clock_mode (str | None)

  • clock_mapping (ClockMapping | None)

  • candidate_id (str | None)

返回类型:

None

ingest(bar, *, now_mono=None, now=None)[源代码]

Ingest one feed-created bar without consulting a process clock.

参数:
返回类型:

BarBarrierResult

advance(now_mono)[源代码]

Expire pending buckets using an explicit replay/live monotonic time.

参数:

now_mono (Any)

返回类型:

Tuple[BarBarrierResult, ...]

accept_quote(event, *, decision_input=None)[源代码]

Check a quote against an already-frozen input without mutating it.

A quote arriving after seal can be inspected for diagnostics, but it cannot be admitted into the stored input. This is the key protection against a mutable latest_quote becoming a historical feature.

参数:
返回类型:

QuoteCutoffResult

class backtrader.feeds.PandasData[源代码]

基类:DataBase

Uses a Pandas DataFrame as the feed source, using indices into column names (which can be "numeric")

This means that all parameters related to lines must have numeric values as indices into the tuples

Params:

  • nocase (default True) case-insensitive match of column names

备注

  • The dataname parameter is a Pandas DataFrame

  • Values possible for datetime

    • None: the index contains the datetime

    • -1: no index, autodetect column

    • >= 0 or string: specific colum identifier

  • For other lines parameters

    • None: column not present

    • -1: autodetect

    • >= 0 or string: specific colum identifier

datafields = ['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
__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 Pandas data feed.

Resets index and converts column names to indices.

frompackages = ()
packages = ()
class backtrader.feeds.PandasDirectData[源代码]

基类:DataBase

Uses a Pandas DataFrame as the feed source, iterating directly over the tuples returned by "itertuples".

This means that all parameters related to lines must have numeric values as indices into the tuples

备注

  • The dataname parameter is a Pandas DataFrame

  • A negative value in any of the parameters for the Data lines indicates it's not present in the DataFrame it is

datafields = ['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
__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 PandasDirect data feed.

Creates iterator from DataFrame.

frompackages = ()
packages = ()
class backtrader.feeds.Quandl[源代码]

基类:QuandlCSV

Executes a direct download of data from Quandl servers for the given time range.

Specific parameters (or specific meaning):

  • dataname

    The ticker to download ('YHOO', for example)

  • baseurl

    The server url. Someone might decide to open a Quandl compatible service in the future.

  • proxies

    A dict indicating which proxy to go through for the download as in {'http': 'http://myproxy.com'} or {'http': 'http://127.0.0.1:8080'}

  • buffered

    If True, the entire socket connection will be buffered locally before parsing starts.

  • reverse

    Quandl returns the value in descending order (newest first). If this is True (the default), the request will tell Quandl to return in ascending (oldest to newest) format

  • adjclose

    Whether to use the dividend/split adjusted close and adjust all values according to it.

  • apikey

    Apikey identification in case it may be needed

  • dataset

    String identifying the dataset to query. Defaults to WIKI

__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 Quandl data feed and download data.

Constructs URL with parameters and fetches data from Quandl API.

frompackages = ()
packages = ()
class backtrader.feeds.QuandlCSV[源代码]

基类:CSVDataBase

Parses pre-downloaded Quandl CSV Data Feeds (or locally generated if they comply to the Quandl format)

Specific parameters:

  • dataname: The filename to parse or a file-like object

  • reverse (default: False)

    It is assumed that locally stored files have already been reversed during the download process

  • adjclose (default: True)

    Whether to use the dividend/split adjusted close and adjust all values according to it.

  • round (default: False)

    Whether to round the values to a specific number of decimals after having adjusted the close

  • decimals (default: 2)

    Number of decimals to round to

start()[源代码]

Start the Quandl CSV data feed.

Reverses data if needed for correct chronological order.

frompackages = ()
packages = ()
class backtrader.feeds.QuoteCutoffResult[源代码]

基类:object

Side-effect-free validation result for a quote against a frozen bar.

accepted: bool
reason: str
symbol: str | None = None
event: Mapping[str, Any] | None = None
__init__(accepted, reason, symbol=None, event=None)
参数:
返回类型:

None

class backtrader.feeds.RollOver[源代码]

基类:DataBase

Class that rolls over to the next future when a condition is met

Params:

  • checkdate (default: None)

    This must be a callable with the following signature:

    Checkdate(dt, d):
    

    Where:

    • dt is a datetime.datetime object

    • d is the current data feed for the active future

    Expected Return Values:

    • True: as long as the callable returns this, a switchover can happen to the next future

If a commodity expires on the 3rd Friday of March, checkdate could return True for the entire week in which the expiration takes place.

  • False: the expiration cannot take place

# This parameter is a callable object checkdate(dt,d), where dt is a time object, d is current active data, # If return value is True, will switch to next contract; if False, will not switch to next contract

  • checkcondition (default: None)

    Note: This will only be called if checkdate has returned True

    If None this will evaluate to True (execute roll over) internally

    Else this must be a callable with this signature:

    Checkcondition(d0, d1)
    

    Where:

    • d0 is the current data feed for the active future

    • d1 is the data feed for the next expiration

    Expected Return Values:

    • True: roll-over to the next future

Following with the example from checkdate, this could say that the roll-over can only happen if the volume from d0 is already less than the volume from d1

  • False: the expiration cannot take place

# When checkdate returns True, this function will be called, this must be a callable object, checkcondition(d0,d1) # Where d0 is current active futures contract, d1 is next expiring contract, if True, will switch from d0 to d1, if not, switch will not happen.

islive()[源代码]

Returns True to notify Cerebro that preloading and runonce should be deactivated

__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 RollOver data feed.

Initializes all data feeds for rollover functionality.

stop()[源代码]

Stop the RollOver data feed.

Stops all underlying data feeds.

frompackages = ()
packages = ()
class backtrader.feeds.SierraChartCSVData[源代码]

基类:GenericCSVData

Parses a SierraChart CSV exported file.

Specific parameters (or specific meaning):

  • dataname: The filename to parse or a file-like object

  • Uses GenericCSVData and simply modifies the dateformat (dtformat) to

frompackages = ()
packages = ()
class backtrader.feeds.TimeFrame[源代码]

基类:object

Enumeration of time periods for financial data.

Defines constants for different time periods used in financial data: Ticks, MicroSeconds, Seconds, Minutes, Days, Weeks, Months, Years, and NoTimeFrame.

Class Methods:

getname(tframe, compression): Get name for timeframe. TFrame(name): Get timeframe constant from name. TName(tframe): Get name string from timeframe constant.

Ticks, MicroSeconds, Seconds, Minutes, Days, Weeks, Months, Years, NoTimeFrame

Timeframe constants.

Ticks = 1
MicroSeconds = 2
Seconds = 3
Minutes = 4
Days = 5
Weeks = 6
Months = 7
Years = 8
NoTimeFrame = 9
Names = ['', 'Ticks', 'MicroSeconds', 'Seconds', 'Minutes', 'Days', 'Weeks', 'Months', 'Years', 'NoTimeFrame']
names = ['', 'Ticks', 'MicroSeconds', 'Seconds', 'Minutes', 'Days', 'Weeks', 'Months', 'Years', 'NoTimeFrame']
classmethod getname(tframe, compression=None)[源代码]

Get the name for a timeframe.

参数:
  • tframe -- TimeFrame constant (e.g., TimeFrame.Days).

  • compression -- Compression factor. If None, uses 1.

返回:

Name of the timeframe (singular or plural).

返回类型:

str

classmethod TFrame(name)[源代码]

Get TimeFrame constant from name.

参数:

name -- String name like 'Days', 'Minutes'.

返回:

TimeFrame constant.

classmethod TName(tframe)[源代码]

Get name string from timeframe constant.

参数:

tframe -- TimeFrame constant.

返回:

Name of the timeframe.

返回类型:

str

class backtrader.feeds.VChartCSV[源代码]

基类:CSVFeedBase

VisualChart CSV feed class.

Wrapper class for VChartCSVData feed functionality.

DataCls

VChartCSVData 的别名

class backtrader.feeds.VChartCSVData[源代码]

基类:CSVDataBase

Parses a VisualChart CSV exported file.

Specific parameters (or specific meaning):

  • dataname: The filename to parse or a file-like object

vctframes = {'D': 5, 'I': 4, 'M': 7, 'W': 6}
frompackages = ()
packages = ()
class backtrader.feeds.VChartData[源代码]

基类:DataBase

Support for Visual Chart binary on-disk files for both daily and intradaily formats.

备注

  • dataname: to file or open file-like an object

    If a file-like object is passed, the timeframe parameter will be used to determine which is the actual timeframe.

    Else the file extension (.fd for daily and .min for intraday) will be used.

__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 VChart data feed.

Opens the VisualChart binary file for reading.

stop()[源代码]

Stop the VChart data feed.

Closes the open file handle.

frompackages = ()
packages = ()
class backtrader.feeds.VChartFeed[源代码]

基类:FeedBase

VisualChart feed class.

Wrapper class for VChartData feed functionality.

DataCls

VChartData 的别名

params = (('basepath', ''), ('period', 14), ('movav', None), ('_movav', None), ('lookback', 1), ('upperband', 70.0), ('lowerband', 30.0), ('safediv', False), ('safepct', False), ('fast', 5), ('slow', 34), ('signal', 9), ('mult', 2.0), ('matype', 0), ('dataname', None), ('name', ''), ('compression', 1), ('timeframe', 5), ('fromdate', None), ('todate', None), ('sessionstart', None), ('sessionend', None), ('filters', []), ('tz', None), ('tzinput', None), ('qcheck', 0.0), ('calendar', None))
class backtrader.feeds.VChartFile[源代码]

基类:DataBase

Support for Visual Chart binary on-disk files for both daily and intradaily formats.

备注

  • dataname: Market code displayed by Visual Chart. Example: 015ES for EuroStoxx 50 continuous future

__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 VChartFile data feed.

Opens the VisualChart binary file for reading.

stop()[源代码]

Stop the VChartFile data feed.

Closes the open file handle.

frompackages = ()
packages = ()
class backtrader.feeds.YahooFinance[源代码]

基类:CSVFeedBase

Yahoo Finance feed class.

Wrapper class for YahooFinanceData feed functionality.

DataCls

YahooFinanceData 的别名

params = (('period', 'd'), ('movav', None), ('_movav', None), ('lookback', 1), ('upperband', 70.0), ('lowerband', 30.0), ('safediv', False), ('safepct', False), ('fast', 5), ('slow', 34), ('signal', 9), ('mult', 2.0), ('matype', 0), ('dataname', None), ('name', ''), ('compression', 1), ('timeframe', 5), ('fromdate', None), ('todate', None), ('sessionstart', None), ('sessionend', None), ('filters', []), ('tz', None), ('tzinput', None), ('qcheck', 0.0), ('calendar', None), ('headers', True), ('separator', ','), ('reverse', False), ('adjclose', True), ('adjvolume', True), ('round', True), ('decimals', 2), ('roundvolume', False), ('swapcloses', False), ('proxies', {}), ('urlhist', 'https://finance.yahoo.com/quote/{}/history'), ('urldown', 'https://query1.finance.yahoo.com/v7/finance/download'), ('retries', 3))
class backtrader.feeds.YahooFinanceCSV[源代码]

基类:CSVFeedBase

Yahoo Finance CSV feed class.

Wrapper class for YahooFinanceCSVData feed functionality.

DataCls

YahooFinanceCSVData 的别名

class backtrader.feeds.YahooFinanceCSVData[源代码]

基类:CSVDataBase

Parses pre-downloaded Yahoo CSV Data Feeds (or locally generated if they comply to the Yahoo format)

Specific parameters:

  • dataname

    The filename to parse or a file-like object

  • reverse

    It is assumed that locally stored files have the newest lines at the bottom

    If this is not the case, pass reverse = True

  • adjclose (default: True) Whether to use the dividend/split adjusted close and adjust all values according to it.

  • adjvolume (default: True) Do also adjust volume if adjclose is also True

  • round (default: True) Whether to round the values to a specific number of decimals after having adjusted the close

  • roundvolume (default: 0) Round the resulting volume to the given number of decimals after having adjusted it

  • decimals (default: 2) Number of decimals to round to

  • swapcloses (default: False) [2018-11-16] It would seem that the order of close and adjusted close is now fixed. The parameter is retained, in case the need to swap the columns again arose.

start()[源代码]

Start the Yahoo Finance CSV data feed.

Reverses data order if needed for correct chronological sequence.

frompackages = ()
packages = ()
class backtrader.feeds.YahooFinanceData[源代码]

基类:YahooFinanceCSVData

Executes a direct download of data from Yahoo servers for the given time range.

Specific parameters (or specific meaning):

  • dataname

    The ticker to download ('YHOO' for Yahoo own stock quotes)

  • proxies

    A dict indicating which proxy to go through for the download as in {'http': 'http://myproxy.com'} or {'http': 'http://127.0.0.1:8080'}

  • period

    The timeframe to download data in. Pass 'w' for weekly and 'm' for monthly.

  • reverse

    [2018-11-16] The latest incarnation of Yahoo online downloads returns the data in the proper order. The default value of reverse for the online download is therefore set to False

  • adjclose

    Whether to use the dividend/split adjusted close and adjust all values according to it.

  • urlhist

    The url of the historical quotes in Yahoo Finance used to gather a crumb authorization cookie for the download

  • urldown

    The url of the actual download server

  • retries

    Number of times (each) to try to get a crumb cookie and download the data

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

Start Yahoo Finance data download using v7 API.

Fetches crumb cookie and downloads historical data.

start()[源代码]

Start the Yahoo Finance data feed.

Initiates download and prepares CSV parser.

frompackages = ()
packages = ()
class backtrader.feeds.YahooLegacyCSV[源代码]

基类:YahooFinanceCSVData

This is intended to load files which were downloaded before Yahoo discontinued the original service in May-2017 Used to load data downloaded before May 2017

frompackages = ()
packages = ()
backtrader.feeds.build_mixed_channel(channels=None, bars=None, tick_channels=None, orderbook_channels=None, funding_channels=None, **kwargs)[源代码]

Construct a MixedChannel with the standard per-group arguments.

All extra keyword arguments are forwarded to MixedChannel so callers can pass preload_window, max_memory_mb, adaptive and batch_size without listing them explicitly.

参数:
  • channels -- Optional iterable of generic event channels.

  • bars -- Optional iterable of pre-built bar objects.

  • tick_channels -- Optional iterable of tick event channels.

  • orderbook_channels -- Optional iterable of order-book channels.

  • funding_channels -- Optional iterable of funding-rate channels.

  • **kwargs -- Forwarded to MixedChannel.

返回:

A new MixedChannel instance.

返回类型:

MixedChannel

class backtrader.feeds.date[源代码]

基类:object

date(year, month, day) --> date object

classmethod fromtimestamp(timestamp, /)

Create a date from a POSIX timestamp.

The timestamp is a number, e.g. created via time.time(), that is interpreted as local time.

classmethod today()

Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

classmethod fromordinal()

int -> date corresponding to a proleptic Gregorian ordinal.

classmethod fromisoformat()

str -> Construct a date from a string in ISO 8601 format.

classmethod fromisocalendar()

int, int, int -> Construct a date from the ISO year, week number and weekday.

This is the inverse of the date.isocalendar() function

ctime()

Return ctime() style string.

strftime()

format -> strftime() style string.

isoformat()

Return string in ISO 8601 format, YYYY-MM-DD.

year
month
day
timetuple()

Return time tuple, compatible with time.localtime().

toordinal()

Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.

replace()

Return date with new specified fields.

weekday()

Return the day of the week represented by the date. Monday == 0 ... Sunday == 6

isoweekday()

Return the day of the week represented by the date. Monday == 1 ... Sunday == 7

isocalendar()

Return a named tuple containing ISO year, week number, and weekday.

max = datetime.date(9999, 12, 31)
min = datetime.date(1, 1, 1)
resolution = datetime.timedelta(days=1)
backtrader.feeds.date2num(dt, tz=None)[源代码]

Convert: mod:datetime to the Gregorian date as UTC float days, preserving hours, minutes, seconds and microseconds. Return value is a: func:float.

class backtrader.feeds.datetime[源代码]

基类:date

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints.

hour
minute
second
microsecond
tzinfo
fold
classmethod fromtimestamp()

timestamp[, tz] -> tz's local time from POSIX timestamp.

classmethod utcfromtimestamp()

Construct a naive UTC datetime from a POSIX timestamp.

classmethod now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

classmethod utcnow()

Return a new datetime representing UTC day and time.

classmethod combine()

date, time -> datetime with same date and time fields

classmethod fromisoformat()

string -> datetime from a string in most ISO 8601 formats

timetuple()

Return time tuple, compatible with time.localtime().

timestamp()

Return POSIX timestamp as float.

utctimetuple()

Return UTC time tuple, compatible with time.localtime().

date()

Return date object with same year, month and day.

time()

Return time object with same time but with tzinfo=None.

timetz()

Return time object with same time and tzinfo.

replace()

Return datetime with new specified fields.

astimezone()

tz -> convert to local time in new timezone tz

ctime()

Return ctime() style string.

isoformat()

[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM]. sep is used to separate the year from the time, and defaults to 'T'. The optional argument timespec specifies the number of additional terms of the time to include. Valid options are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds' and 'microseconds'.

classmethod strptime()

string, format -> new datetime parsed from a string (like time.strptime()).

utcoffset()

Return self.tzinfo.utcoffset(self).

tzname()

Return self.tzinfo.tzname(self).

dst()

Return self.tzinfo.dst(self).

max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
min = datetime.datetime(1, 1, 1, 0, 0)
resolution = datetime.timedelta(microseconds=1)
class backtrader.feeds.filter

基类:object

filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

backtrader.feeds.get_logger(name=None)[源代码]

Return a logger under the backtrader namespace.

参数:

name -- Usually __name__ of the calling module. If it already starts with "backtrader" it is used as-is; otherwise it is nested under the backtrader root (e.g. "mystuff" -> "backtrader.mystuff"). None returns the root logger.

返回:

A logger in the backtrader hierarchy.

返回类型:

logging.Logger

class backtrader.feeds.timezone[源代码]

基类:tzinfo

Fixed offset from UTC implementation of tzinfo.

utcoffset()

Return fixed offset.

tzname()

If name is specified when timezone is created, returns the name. Otherwise returns offset as 'UTC(+|-)HH:MM'.

dst()

Return None.

fromutc()

datetime in UTC -> datetime in local time.

max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
utc = datetime.timezone.utc
backtrader.feeds.validate_quote_against_bar(event, *, bar, max_skew_ms=500.0)[源代码]

Validate one quote without mutating a barrier or its decision input.

参数:
返回类型:

QuoteCutoffResult

Overview

Data feeds are the source of market data for strategies. Backtrader supports various data formats and sources.

Built-in Data Feeds

CSV Data

  • GenericCSVData: Flexible CSV reader

  • YahooFinanceCSVData: Yahoo Finance format

  • BacktraderCSVData: Backtrader native format

Pandas

  • PandasData: Load from pandas DataFrame

  • PandasDirectData: Direct DataFrame access

Live Data

  • IBData: Interactive Brokers

  • OandaData: OANDA forex

  • CCXTData: Cryptocurrency exchanges

Using CSV Data

# Generic CSV
data = bt.feeds.GenericCSVData(
    dataname='data.csv',
    dtformat='%Y-%m-%d',
    datetime=0,
    open=1,
    high=2,
    low=3,
    close=4,
    volume=5,
    openinterest=-1
)

# Yahoo Finance CSV
data = bt.feeds.YahooFinanceCSVData(
    dataname='AAPL.csv',
    fromdate=datetime(2020, 1, 1),
    todate=datetime(2021, 1, 1)
)

Using Pandas Data

import pandas as pd

df = pd.read_csv('data.csv', parse_dates=['date'])
df.set_index('date', inplace=True)

data = bt.feeds.PandasData(
    dataname=df,
    datetime=None,  # Use index as datetime
    open='open',
    high='high',
    low='low',
    close='close',
    volume='volume'
)

Resampling Data

# Load minute data
data = bt.feeds.GenericCSVData(dataname='minute_data.csv')
cerebro.adddata(data)

# Resample to hourly
cerebro.resampledata(
    data,
    timeframe=bt.TimeFrame.Minutes,
    compression=60
)

# Resample to daily
cerebro.resampledata(
    data,
    timeframe=bt.TimeFrame.Days,
    compression=1
)

Multiple Data Feeds

# Add multiple stocks
for symbol in ['AAPL', 'GOOGL', 'MSFT']:
    data = bt.feeds.YahooFinanceCSVData(
        dataname=f'{symbol}.csv'
    )
    cerebro.adddata(data, name=symbol)

# Access in strategy
class MyStrategy(bt.Strategy):
    def __init__(self):
        # Access by index
        self.data0 = self.datas[0]

        # Access by name
        self.aapl = self.getdatabyname('AAPL')