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.
Example
>>> from backtrader.utils import OrderedDict, date2num
>>> od = OrderedDict()
>>> od['key'] = 'value'
- class backtrader.utils.OrderedDict[source]¶
Bases:
dictDictionary 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[source]¶
Bases:
dictDictionary 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.
- class backtrader.utils.AutoDictList[source]¶
Bases:
dictDictionary 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.
Example
>>> d = AutoDictList() >>> d['key'].append('value') >>> print(d['key']) ['value']
- class backtrader.utils.AutoOrderedDict[source]¶
Bases:
OrderedDictOrderedDict 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.
Example
>>> d = AutoOrderedDict() >>> d['a']['b'] = 1 # Automatically creates nested dicts >>> d._close() # Prevent further auto-creation
- class backtrader.utils.DotDict[source]¶
Bases:
dictDictionary 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.
Example
>>> d = DotDict() >>> d['key'] = 'value' >>> print(d.key) 'value'
- backtrader.utils.Localizer(tz)[source]¶
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.
- Parameters:
tz – Timezone object to add localize method to.
- Returns:
The same timezone object with a localize method added.
- backtrader.utils.date2num(dt, tz=None)[source]¶
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)[source]¶
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)[source]¶
Convert numeric date to date object.
- Parameters:
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.
- Returns:
Date object extracted from the datetime.
- Return type:
date
- backtrader.utils.num2time(num, tz=None, naive=True)[source]¶
Convert numeric date to time object.
- Parameters:
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.
- Returns:
Time object extracted from the datetime.
- Return type:
time
- backtrader.utils.time2num(tm)[source]¶
Converts the hour/minute/second/microsecond part of tm (datetime.datetime or time) to a num
- backtrader.utils.tzparse(tz)[source]¶
Parse a timezone specification into a tzinfo object.
- Parameters:
tz – Timezone specification (string, tzinfo object, or None).
- Returns:
A tzinfo object. If pytz is available and tz is a string, returns the corresponding pytz timezone. Otherwise returns a Localizer-wrapped tz object.