backtrader.feeds package¶
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[源代码]¶
基类:
objectSpecial 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[源代码]¶
基类:
CSVFeedBaseBacktrader CSV feed class.
Wrapper class for BacktraderCSVData feed functionality.
- DataCls¶
- class backtrader.feeds.BacktraderCSVData[源代码]¶
基类:
CSVDataBaseParses 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[源代码]¶
基类:
objectTime and quality policy shared by 23 and 24 consumers.
- class backtrader.feeds.BarBarrierReason[源代码]¶
基类:
objectStable 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[源代码]¶
基类:
objectResult of one bar ingestion or clock advance.
- decision_input: MinuteDecisionInput | None = None¶
- class backtrader.feeds.BarEvidence[源代码]¶
基类:
objectAn 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_eventsare optional because the 23 consumer is deliberately bar-only.- to_dict()[源代码]¶
Return this bar evidence as a JSON-serialisable dict.
Every field is passed through
_json_safeso the result can be written straight to the run receipt.
- __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)
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.BtApiFeed[源代码]¶
基类:
LiveBarCohortFeedMixin,LiveFeedBaseData feed that backfills and streams bars through BtApiStore.
orderbook_as_ticks=Trueexposes each depth snapshot as a zero-volume midpoint tick bar before callingnotify_orderbook. This gives native broker orders a valid feed price and clock even without trade/bar streams. It requirestimeframe=TimeFrame.Ticksfor 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.
- 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.
- 返回类型:
- tick_ingest_error_counts()[源代码]¶
Counts of real-time SDK ticks dropped per finite ingestion error code.
OUT_OF_ORDER_EVENT_TIMEcounts 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_nsdefaults to this feed's monotonic clock (theclockparam when injected, otherwisetime.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.- 返回:
okand the finite failurereasons.- 返回类型:
FeedTradeQualification
- line_bar_quality()[源代码]¶
Quality of the bar now at
[0]on this feed's lines (iteration 62).Returns a
FeedLineBarQuality, orNonewhen 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") hascomplete=False,volume_complete=Falseand its volume flags inquality_flags; the same facts are on its BarEvent innotify_bar.
- valuation_mark_max_age = None¶
Upper bound in seconds on how old the close of the current bar may be for
valuation_mark();Nonemeans one bar period plusreceive_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_utcis 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, andnow - as_of_utc(nowfrom this feed's injectedclockparam, the wall clock otherwise) is neither negative beyondreceive_time_max_agenor greater than the tighter ofvaluation_mark_max_ageandmax_ageseconds. Otherwise raisesValueErrorwhosecodeattribute is a finite reason; never guesses.
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.Chainer[源代码]¶
基类:
DataBaseClass that chains datas
- __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).
- get_notifications()[源代码]¶
Get notifications from the current data feed.
- 返回:
Notifications from active data feed or empty list.
- 返回类型:
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.ClockMapping[源代码]¶
基类:
objectA 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=Trueexplicitly; live evidence cannot use a synthetic mapping. No process clock is read here.- map_wall_to_mono_ns(wall_time)[源代码]¶
Map a wall time while refusing values outside this mapping's scope.
- validate_pair(wall_time, mono_seconds)[源代码]¶
Check one observed wall/monotonic pair against the error interval.
- conservative_deadline_seconds(wall_deadline)[源代码]¶
Return the earliest monotonic deadline allowed by the error bound.
- __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)¶
- class backtrader.feeds.CryptoHFTData[源代码]¶
基类:
DataBaseLoad 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.Minuteswithcompression=60for hourly bars.fromdateandtodateare 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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.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.feeds.GenericCSV[源代码]¶
基类:
CSVFeedBaseGeneric CSV feed class.
Wrapper class for GenericCSVData feed functionality.
- DataCls¶
GenericCSVData的别名
- class backtrader.feeds.GenericCSVData[源代码]¶
基类:
CSVDataBaseParses 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 objectThe lines parameters (datetime, open, high ...) take numeric values
A value of -1 indicates absence of that field in the CSV source
If
timeis present (parameter time >=0), the source contains separated fields for date and time, which will be combinednullvalueValue 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 typeintrepresenting the number of seconds since Jan 1st, 19702: The value is a Unix timestamp of a typefloat
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.
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.InfluxDB[源代码]¶
基类:
DataBaseInfluxDB 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).
- packages = ()¶
- exception backtrader.feeds.InfluxDBClientError[源代码]¶
基类:
ExceptionException raised for InfluxDB client errors.
- class backtrader.feeds.MT4CSVData[源代码]¶
-
Parses a Metatrader4 History center CSV exported file.
Specific parameters (or specific meaning):
dataname: The filename to parse or a file-like objectUses GenericCSVData and simply modifies the params
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.MinuteDecisionInput[源代码]¶
基类:
objectOne frozen, same-scope multi-leg decision input.
- bars: Mapping[str, BarEvidence]¶
- clock_mapping: ClockMapping¶
- __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)¶
- 参数:
bars (Mapping[str, BarEvidence])
bucket_start (datetime)
bucket_end (datetime)
common_available_at (datetime)
accepted_quotes (Mapping[str, Tuple[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)
- 返回类型:
None
- class backtrader.feeds.MixedChannel[源代码]¶
-
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 singlemerged_channelslist and delegates toStreamingEventQueue. 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[源代码]¶
基类:
objectCausal 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_mappingis not aClockMapping.
- 返回类型:
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_INPUTSbuckets 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.
- ingest(bar, *, now_mono=None, now=None)[源代码]¶
Ingest one feed-created bar without consulting a process clock.
- 参数:
- 返回类型:
- 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_quotebecoming a historical feature.- 参数:
event (Any)
decision_input (MinuteDecisionInput | None)
- 返回类型:
- class backtrader.feeds.PandasData[源代码]¶
基类:
DataBaseUses 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
datanameparameter is a Pandas DataFrameValues 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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.PandasDirectData[源代码]¶
基类:
DataBaseUses 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
datanameparameter is a Pandas DataFrameA 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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.Quandl[源代码]¶
基类:
QuandlCSVExecutes a direct download of data from Quandl servers for the given time range.
Specific parameters (or specific meaning):
datanameThe ticker to download ('YHOO', for example)
baseurlThe server url. Someone might decide to open a Quandl compatible service in the future.
proxiesA dict indicating which proxy to go through for the download as in {'http': 'http://myproxy.com'} or {'http': 'http://127.0.0.1:8080'}
bufferedIf True, the entire socket connection will be buffered locally before parsing starts.
reverseQuandl 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) formatadjcloseWhether to use the dividend/split adjusted close and adjust all values according to it.
apikeyApikey identification in case it may be needed
datasetString 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[源代码]¶
基类:
CSVDataBaseParses 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 objectreverse(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[源代码]¶
基类:
objectSide-effect-free validation result for a quote against a frozen bar.
- class backtrader.feeds.RollOver[源代码]¶
基类:
DataBaseClass 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:
dtis adatetime.datetimeobjectdis 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
checkdatehas returnedTrueIf
Nonethis will evaluate toTrue(execute roll over) internallyElse this must be a callable with this signature:
Checkcondition(d0, d1)
Where:
d0is the current data feed for the active futured1is 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 fromd0is already less than the volume fromd1False: 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.
- __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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.SierraChartCSVData[源代码]¶
-
Parses a SierraChart CSV exported file.
Specific parameters (or specific meaning):
dataname: The filename to parse or a file-like objectUses GenericCSVData and simply modifies the dateformat (dtformat) to
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.TimeFrame[源代码]¶
基类:
objectEnumeration 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).
- 返回类型:
- class backtrader.feeds.VChartCSV[源代码]¶
基类:
CSVFeedBaseVisualChart CSV feed class.
Wrapper class for VChartCSVData feed functionality.
- DataCls¶
VChartCSVData的别名
- class backtrader.feeds.VChartCSVData[源代码]¶
基类:
CSVDataBaseParses 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[源代码]¶
基类:
DataBaseSupport for Visual Chart binary on-disk files for both daily and intradaily formats.
备注
dataname: to file or open file-like an objectIf a file-like object is passed, the
timeframeparameter will be used to determine which is the actual timeframe.Else the file extension (
.fdfor daily and.minfor 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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.VChartFeed[源代码]¶
基类:
FeedBaseVisualChart 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[源代码]¶
基类:
DataBaseSupport 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).
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.YahooFinance[源代码]¶
基类:
CSVFeedBaseYahoo 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[源代码]¶
基类:
CSVFeedBaseYahoo Finance CSV feed class.
Wrapper class for YahooFinanceCSVData feed functionality.
- DataCls¶
- class backtrader.feeds.YahooFinanceCSVData[源代码]¶
基类:
CSVDataBaseParses pre-downloaded Yahoo CSV Data Feeds (or locally generated if they comply to the Yahoo format)
Specific parameters:
datanameThe filename to parse or a file-like object
reverseIt is assumed that locally stored files have the newest lines at the bottom
If this is not the case, pass reverse =
Trueadjclose(default:True) Whether to use the dividend/split adjusted close and adjust all values according to it.adjvolume(default:True) Do also adjustvolumeifadjcloseis alsoTrueround(default:True) Whether to round the values to a specific number of decimals after having adjusted the closeroundvolume(default:0) Round the resulting volume to the given number of decimals after having adjusted itdecimals(default:2) Number of decimals to round toswapcloses(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[源代码]¶
-
Executes a direct download of data from Yahoo servers for the given time range.
Specific parameters (or specific meaning):
datanameThe ticker to download ('YHOO' for Yahoo own stock quotes)
proxiesA dict indicating which proxy to go through for the download as in {'http': 'http://myproxy.com'} or {'http': 'http://127.0.0.1:8080'}
periodThe 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
reversefor the online download is therefore set toFalseadjcloseWhether to use the dividend/split adjusted close and adjust all values according to it.
urlhistThe url of the historical quotes in Yahoo Finance used to gather a
crumbauthorization cookie for the downloadurldownThe url of the actual download server
retriesNumber of times (each) to try to get a
crumbcookie 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.
- frompackages = ()¶
- packages = ()¶
- class backtrader.feeds.YahooLegacyCSV[源代码]¶
-
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
MixedChannelwith the standard per-group arguments.All extra keyword arguments are forwarded to
MixedChannelso callers can passpreload_window,max_memory_mb,adaptiveandbatch_sizewithout 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
MixedChannelinstance.- 返回类型:
- class backtrader.feeds.date[源代码]¶
基类:
objectdate(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[源代码]¶
基类:
datedatetime(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¶
基类:
objectfilter(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
backtradernamespace.- 参数:
name -- Usually
__name__of the calling module. If it already starts with"backtrader"it is used as-is; otherwise it is nested under thebacktraderroot (e.g."mystuff"->"backtrader.mystuff").Nonereturns the root logger.- 返回:
A logger in the backtrader hierarchy.
- 返回类型:
- class backtrader.feeds.timezone[源代码]¶
基类:
tzinfoFixed 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.
- 参数:
event (Any)
bar (BarEvidence)
max_skew_ms (float)
- 返回类型:
Submodules¶
- backtrader.feeds.blaze module
- backtrader.feeds.btcsv module
- backtrader.feeds.chainer module
- backtrader.feeds.csvgeneric module
- backtrader.feeds.influxfeed module
- backtrader.feeds.mt4csv module
- backtrader.feeds.pandafeed module
- backtrader.feeds.quandl module
- backtrader.feeds.rollover module
- backtrader.feeds.sierrachart module
- backtrader.feeds.vchart module
- backtrader.feeds.vchartcsv module
- backtrader.feeds.vchartfile module
- backtrader.feeds.yahoo module