backtrader.metabase module¶
Base classes and mixins for the Backtrader framework.
This module provides the foundational infrastructure that replaces the original metaclass-based design. It includes parameter management, object factories, and various mixin classes used throughout the framework.
- Key Components:
ObjectFactory: Factory class for creating objects with lifecycle hooks
BaseMixin: Base mixin providing factory-based object creation
ParamsMixin: Mixin for parameter management without metaclasses
AutoInfoClass: Dynamic class for parameter/info storage
ParameterManager: Static utility for handling parameter operations
ItemCollection: Collection class with index and name-based access
- Utility Functions:
findbases: Recursively find base classes of a given type
findowner: Search call stack for owner objects
is_class_type: Cached type checking via MRO inspection
patch_strategy_clk_update: Runtime patch for Strategy clock updates
示例
Creating a class with parameters:
class MyIndicator(ParamsMixin):
params = (('period', 20), ('multiplier', 2.0))
def __init__(self):
print(f"Period: {self.p.period}")
备注
This module was created during the metaclass removal refactoring to provide equivalent functionality using explicit initialization patterns.
- class backtrader.metabase.OwnerContext[源代码]¶
基类:
objectContext manager for tracking owner objects during indicator creation.
This class provides an alternative to sys._getframe() based owner lookup by maintaining an explicit owner stack in thread-local storage.
- Usage:
- with OwnerContext.set_owner(strategy):
# All indicators created here will have strategy as their owner sma = SMA(data, period=20)
The owner stack allows nested contexts, so indicators creating sub-indicators will correctly assign ownership.
- static get_current_owner(cls_filter=None)[源代码]¶
Get the current owner from the context stack.
- 参数:
cls_filter -- Optional class type to filter owners. If provided, only returns an owner that is an instance of this class.
- 返回:
The current owner object, or None if no owner is set or no owner matches the filter.
- static set_owner(owner)[源代码]¶
Set the current owner for indicator creation.
- 参数:
owner -- The owner object (typically a Strategy or Indicator).
- 生成器:
None. The owner is available via get_current_owner() within the context.
- static push_owner(owner)[源代码]¶
Push an owner onto the stack (non-context-manager version).
- 参数:
owner -- The owner object to push.
- backtrader.metabase.is_class_type(cls, type_name)[源代码]¶
OPTIMIZED: Check if a class is of a certain type by checking __mro__. Results are cached for better performance.
- 参数:
cls -- The class to check
type_name -- The type name to look for (e.g., 'Strategy', 'Indicator')
- 返回:
True if the class has the type in its MRO
- 返回类型:
- backtrader.metabase.patch_strategy_clk_update()[源代码]¶
CRITICAL FIX: Patch the Strategy class's _clk_update method to prevent the "max() iterable argument is empty" error that occurs when no data sources have any length yet.
- backtrader.metabase.findbases(kls, topclass)[源代码]¶
Recursively find all base classes that inherit from topclass.
This function traverses the class hierarchy using __bases__ and recursively collects all base classes that are subclasses of the specified topclass.
- 参数:
kls -- The class to search bases for.
topclass -- The top-level class to filter by (only bases that are subclasses of this class are included).
- 返回:
- A list of base classes in order from most ancestral to most
immediate parent.
- 返回类型:
备注
This function uses recursion, but the depth is limited by Python's recursion limit. In practice, class hierarchies rarely exceed this.
- backtrader.metabase.findowner(owned, cls, startlevel=2, skip=None)[源代码]¶
Find the owner object in the call stack or context.
This function first checks the OwnerContext for an explicitly set owner, then falls back to traversing the call stack to find an object that: 1. Is an instance of the specified class (cls) 2. Is not the owned object itself 3. Is not the skip object (if provided)
This is commonly used to find parent containers (e.g., Strategy finding its Cerebro, or Indicator finding its Strategy).
- 参数:
owned -- The object looking for its owner.
cls -- The class type the owner must be an instance of.
startlevel -- Stack frame level to start searching from (default: 2, skips this function and the caller).
skip -- Optional object to skip during the search.
- 返回:
The owner object if found, None otherwise.
备注
Uses OwnerContext for explicit owner management. The legacy sys._getframe() based lookup has been removed for better portability and performance.
- class backtrader.metabase.ObjectFactory[源代码]¶
基类:
objectFactory class to replace MetaBase functionality.
This class provides a static method for creating objects with lifecycle hooks similar to the original metaclass implementation.
- The creation process follows these steps:
doprenew: Pre-new processing (class modification)
donew: Object creation
dopreinit: Pre-initialization processing
doinit: Main initialization
dopostinit: Post-initialization processing
- class backtrader.metabase.BaseMixin[源代码]¶
基类:
objectMixin providing factory-based object creation without metaclass.
This mixin provides default implementations for the lifecycle hooks used by ObjectFactory. Subclasses can override these methods to customize object creation and initialization.
- classmethod doprenew(*args, **kwargs)[源代码]¶
Called before object creation.
- 参数:
*args -- Positional arguments for object creation.
**kwargs -- Keyword arguments for object creation.
- 返回:
(cls, args, kwargs) - Class and arguments to use.
- 返回类型:
- classmethod donew(*args, **kwargs)[源代码]¶
Create a new object instance.
- 参数:
*args -- Positional arguments for object creation.
**kwargs -- Keyword arguments for object creation.
- 返回:
(_obj, args, kwargs) - New instance and remaining arguments.
- 返回类型:
- classmethod dopreinit(_obj, *args, **kwargs)[源代码]¶
Called before __init__ to modify arguments.
- 参数:
_obj -- The object instance.
*args -- Positional arguments for __init__.
**kwargs -- Keyword arguments for __init__.
- 返回:
(_obj, args, kwargs) - Object and arguments for __init__.
- 返回类型:
- classmethod doinit(_obj, *args, **kwargs)[源代码]¶
Call __init__ on the object.
- 参数:
_obj -- The object instance.
*args -- Positional arguments for __init__.
**kwargs -- Keyword arguments for __init__.
- 返回:
(_obj, args, kwargs) - Object and remaining arguments.
- 返回类型:
- class backtrader.metabase.AutoInfoClass[源代码]¶
基类:
objectDynamic class for storing parameter and info key-value pairs.
This class provides a flexible mechanism for storing and retrieving configuration data (parameters, plot info, etc.) with support for inheritance and derivation.
- Class Methods:
_getpairsbase: Get base class pairs as OrderedDict. _getpairs: Get all pairs (including inherited) as OrderedDict. _getrecurse: Check if recursive derivation is enabled. _derive: Create a derived class with additional parameters. _getkeys: Get all parameter keys. _getdefaults: Get all default values. _getitems: Get all key-value pairs. _gettuple: Get pairs as tuple of tuples.
- Instance Methods:
isdefault: Check if a parameter has its default value. notdefault: Check if a parameter differs from default. get/_get: Get a parameter value with optional default.
- class backtrader.metabase.ParameterManager[源代码]¶
基类:
objectManager for handling parameter operations without metaclass.
This class provides static methods for setting up and deriving parameter classes, handling package imports, and managing parameter inheritance.
- class backtrader.metabase.ParamsMixin[源代码]¶
基类:
BaseMixinMixin class that provides parameter management capabilities
- static __new__(cls, *args, **kwargs)[源代码]¶
Create instance and set up parameters before __init__ is called
- property params¶
Instance-level params property for backward compatibility
- property p¶
Provide p property for backward compatibility
- backtrader.metabase.ParamsBase¶
ParamsMixin的别名
- class backtrader.metabase.ItemCollection[源代码]¶
基类:
objectCollection that allows access by both index and name.
This class holds a list of items that can be accessed either by their numeric index or by a string name. Names are set as attributes on the collection instance.
示例
collection = ItemCollection() collection.append(my_strategy, name='mystrat') collection[0] # Access by index collection.mystrat # Access by name