backtrader.utils package

Utilities Module - Common utility functions and classes.

This module provides common utilities used throughout the backtrader framework including data structures, date/time conversions, and helper functions.

Exports:

AutoDict, AutoDictList, AutoOrderedDict, DotDict: Dictionary utilities. OrderedDict: Ordered dictionary from collections. num2date, date2num, num2dt, num2time, time2num: Date/time conversions. tzparse, Localizer, TIME_MAX: Timezone utilities.

示例

>>> from backtrader.utils import OrderedDict, date2num
>>> od = OrderedDict()
>>> od['key'] = 'value'
class backtrader.utils.OrderedDict[源代码]

基类:dict

Dictionary that remembers insertion order

__init__(*args, **kwargs)
clear() None.  Remove all items from od.
popitem(last=True)

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

move_to_end(key, last=True)

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

keys() a set-like object providing a view on D's keys
items() a set-like object providing a view on D's items
values() an object providing a view on D's values
pop(key[, default]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

copy() a shallow copy of od
classmethod fromkeys(iterable, value=None)

Create a new ordered dictionary with keys from iterable and values set to value.

class backtrader.utils.AutoDict[源代码]

基类:dict

Dictionary with automatic nested dict creation and closeable state.

Extends dict with: - Automatic nested dict creation for missing keys - Closeable state (_closed) to prevent further auto-creation - Attribute-style access

_closed

If True, __missing__ raises KeyError instead of creating nested dicts.

_close()[源代码]

Set _closed to True to prevent auto-creation.

_open()[源代码]

Set _closed to False to enable auto-creation.

class backtrader.utils.AutoDictList[源代码]

基类:dict

Dictionary that creates an empty list for missing keys.

When accessing a key that doesn't exist, automatically creates a new empty list for that key.

示例

>>> d = AutoDictList()
>>> d['key'].append('value')
>>> print(d['key'])
['value']
class backtrader.utils.AutoOrderedDict[源代码]

基类:OrderedDict

OrderedDict with automatic nested dict creation and closeable state.

Combines OrderedDict's insertion ordering with AutoDict's automatic nested dict creation and closeable state.

_closed

If True, __missing__ raises KeyError instead of creating nested dicts.

_close()[源代码]

Set _closed to True to prevent auto-creation.

_open()[源代码]

Set _closed to False to enable auto-creation.

示例

>>> d = AutoOrderedDict()
>>> d['a']['b'] = 1  # Automatically creates nested dicts
>>> d._close()  # Prevent further auto-creation
lvalues()[源代码]

Return dictionary values as a list.

Provides Python 2/3 compatible list of values.

返回:

List of all values in the dictionary.

返回类型:

list

class backtrader.utils.DotDict[源代码]

基类:dict

Dictionary with attribute-style access.

Allows accessing dictionary values as attributes using dot notation. If an attribute is not found in the usual places, the dict itself is checked.

示例

>>> d = DotDict()
>>> d['key'] = 'value'
>>> print(d.key)
'value'
backtrader.utils.Localizer(tz)[源代码]

Add a localize method to a timezone object.

This function adds a localize method to tz objects that don't have one, allowing consistent timezone localization across different timezone implementations.

参数:

tz -- Timezone object to add localize method to.

返回:

The same timezone object with a localize method added.

backtrader.utils.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.

backtrader.utils.num2date(x, tz=None, naive=True)[源代码]

x is a float value that gives the number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC plus one. The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not universal practice. For details, see the module docstring. Return value is a: class:datetime instance in timezone tz (default to rcparams TZ value). If x is a sequence, a sequence of: class:datetime objects will be returned.

backtrader.utils.num2dt(num, tz=None, naive=True)[源代码]

Convert numeric date to date object.

参数:
  • num -- Numeric date value (days since 0001-01-01 UTC + 1).

  • tz -- Timezone for the result (optional).

  • naive -- If True, return naive date without timezone info.

返回:

Date object extracted from the datetime.

返回类型:

date

backtrader.utils.num2time(num, tz=None, naive=True)[源代码]

Convert numeric date to time object.

参数:
  • num -- Numeric date value (days since 0001-01-01 UTC + 1).

  • tz -- Timezone for the result (optional).

  • naive -- If True, return naive time without timezone info.

返回:

Time object extracted from the datetime.

返回类型:

time

backtrader.utils.time2num(tm)[源代码]

Converts the hour/minute/second/microsecond part of tm (datetime.datetime or time) to a num

backtrader.utils.tzparse(tz)[源代码]

Parse a timezone specification into a tzinfo object.

参数:

tz -- Timezone specification (string, tzinfo object, or None).

返回:

A tzinfo object. If pytz is available and tz is a string, returns the corresponding pytz timezone. Otherwise returns a Localizer-wrapped tz object.

backtrader.utils.get_backtest_metrics(cerebro, config)[源代码]

Extract raw standard metrics from a completed Cerebro backtest.

Pulls the strategy instance from cerebro.runstrats[0][0] and reads the sharpe, returns, drawdown and trades analyzers plus the broker's final portfolio value. The returned dict contains exactly the keys listed in STANDARD_METRIC_FIELDS and is the raw payload consumed by downstream normalisation or reporting layers.

参数:
  • cerebro (Any) -- A Cerebro instance whose first run strategy has already produced the four expected analyzers (sharpe, returns, drawdown, trades).

  • config (dict[str, Any]) -- Configuration dict. Only config["backtest"] ["initial_cash"] is read, used as the baseline for return_rate.

返回:

Mapping of standard metric name -> value (floats for percentages and counts, broker value for final_value).

返回类型:

dict

backtrader.utils.extract_backtest_metrics(cerebro, config)

Extract raw standard metrics from a completed Cerebro backtest.

Pulls the strategy instance from cerebro.runstrats[0][0] and reads the sharpe, returns, drawdown and trades analyzers plus the broker's final portfolio value. The returned dict contains exactly the keys listed in STANDARD_METRIC_FIELDS and is the raw payload consumed by downstream normalisation or reporting layers.

参数:
  • cerebro (Any) -- A Cerebro instance whose first run strategy has already produced the four expected analyzers (sharpe, returns, drawdown, trades).

  • config (dict[str, Any]) -- Configuration dict. Only config["backtest"] ["initial_cash"] is read, used as the baseline for return_rate.

返回:

Mapping of standard metric name -> value (floats for percentages and counts, broker value for final_value).

返回类型:

dict

backtrader.utils.write_metrics(metrics, base_dir, filename='py_result.json')[源代码]

Serialize metrics as JSON inside base_dir.

参数:
  • metrics (dict[str, Any]) -- Mapping of metric name -> JSON-serialisable value. Typically the output of get_backtest_metrics().

  • base_dir (str) -- Directory where the JSON file will be written. Created implicitly by pathlib.Path (the underlying open will fail if it does not exist).

  • filename (str) -- JSON file name. Defaults to "py_result.json".

返回:

The absolute (or relative) path to the written file.

返回类型:

Path

backtrader.utils.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

backtrader.utils.configure_logging(level='INFO', log_file=None, fmt=None, datefmt=None, console=True, max_bytes=10485760, backup_count=5, propagate=False)[源代码]

Configure the backtrader logger hierarchy (opt-in).

Backtrader emits nothing until you call this. It configures only the backtrader logger (never the root logger), so it will not clobber a host application's logging. Calling it again replaces backtrader-managed handlers (idempotent) while leaving host-added handlers untouched.

参数:
  • level -- Level as int (logging.INFO) or name ("INFO").

  • log_file -- If given, also write to this file via a RotatingFileHandler.

  • fmt -- Message format. Defaults to DEFAULT_FORMAT.

  • datefmt -- Date format. Defaults to DEFAULT_DATEFMT.

  • console -- Whether to add a stderr StreamHandler.

  • max_bytes -- Rotating file handler size before rollover.

  • backup_count -- Number of rotated backups to keep.

  • propagate -- Whether the backtrader logger propagates to the root logger (default False).

返回:

The configured backtrader root logger.

返回类型:

logging.Logger

backtrader.utils.set_level(level, name=None)[源代码]

Set the level of a backtrader logger at runtime.

参数:
  • level -- Level as int or name.

  • name -- Sub-logger name (__name__-style). None targets the root.

backtrader.utils.reset_logging()[源代码]

Remove backtrader-managed handlers and restore the default NullHandler.

Mainly useful in tests to return to the pristine, no-output state.

Submodules