backtrader.parameters module¶
New Parameter System for Backtrader
This module implements a modern parameter system that replaces the metaclass-based parameter handling with descriptor-based approach. This provides better type safety, validation, and maintainability while maintaining backward compatibility.
Key Components: - ParameterDescriptor: Core descriptor for parameter handling - ParameterManager: Parameter storage and management - ParameterizedBase: Base class for parameterized objects (without metaclass) - Type checking and validation mechanisms - Python 3.6+ __set_name__ support
- class backtrader.parameters.ParameterDescriptor[源代码]¶
基类:
objectAdvanced parameter descriptor with type checking and validation.
This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:
Automatic type checking and conversion
Value validation
Default value handling
Documentation support
Python 3.6+ __set_name__ support
- __init__(default=None, type_=None, validator=None, doc=None, name=None, required=False)[源代码]¶
Initialize parameter descriptor.
- 参数:
default (Any) -- Default value for the parameter
type -- Expected type for the parameter (enables type checking)
validator (Callable[[Any], bool] | None) -- Function to validate parameter values
doc (str | None) -- Documentation string for the parameter
name (str | None) -- Parameter name (usually set by __set_name__)
required (bool) -- Whether this parameter is required (no default allowed)
- __set_name__(owner, name)[源代码]¶
Called when the descriptor is assigned to a class attribute. This is a Python 3.6+ feature that automatically sets the parameter name.
- class backtrader.parameters.ParameterManager[源代码]¶
基类:
objectEnhanced Parameter storage and management system.
This class manages parameter values for an object, replacing the functionality of AutoInfoClass. It provides efficient storage, inheritance support, batch operations, and advanced features like change tracking, callbacks, and transactional updates.
New Features in Day 32-33: - Parameter change history and tracking - Change callbacks and notifications - Parameter locking mechanism - Parameter groups for organization - Advanced inheritance with conflict resolution - Lazy default value evaluation - Transactional batch updates
- __init__(descriptors, initial_values=None, enable_history=True, enable_callbacks=True)[源代码]¶
Initialize parameter manager.
- get(name, default=None, _MISSING=<object object>)[源代码]¶
Get parameter value with optimized caching and lazy evaluation support.
- set(name, value, force=False, trigger_callbacks=True, skip_validation=False)[源代码]¶
Set parameter value with validation and dependency updates.
- copy()[源代码]¶
Create a copy of this parameter manager.
- 返回:
New ParameterManager instance with same values
- 返回类型:
- inherit_from(parent, strategy='merge', conflict_resolution='parent', selective=None)[源代码]¶
Inherit parameters from another ParameterManager.
- 参数:
parent (ParameterManager) -- Parent ParameterManager to inherit from
strategy (str) -- Inheritance strategy ('merge', 'replace', 'add_only', 'selective')
conflict_resolution (str) -- How to resolve conflicts ('parent', 'child', 'error', 'raise')
selective (List[str] | None) -- Only inherit specific parameters (list of names)
- 返回类型:
None
- add_change_callback(callback, param_name=None)[源代码]¶
Add a callback function that will be called when parameters change.
- clear_history(name=None)[源代码]¶
Clear change history.
- 参数:
name (str | None) -- Specific parameter name, or None to clear all history
- 返回类型:
None
- class backtrader.parameters.ParameterAccessor[源代码]¶
基类:
objectParameter accessor that provides dict-like and attribute-like access to parameters.
This class serves as a bridge between the new parameter system and the old MetaParams-style parameter access patterns. It provides backward compatibility by supporting both attribute access (obj.p.param_name) and dict-like access.
- __init__(param_manager)[源代码]¶
Initialize with a parameter manager.
NOTE: Originally attempted to pre-create instance attributes for performance, but this causes parameter synchronization issues. When parameters are modified through other means (like broker.set_cash()), instance attributes won't update. Therefore maintain dynamic lookup to ensure latest values are always retrieved.
- 参数:
param_manager (ParameterManager)
- class backtrader.parameters.LegacyParamsSchema[源代码]¶
基类:
objectCallable legacy params schema backed by the modern parameter manager.
The object keeps the old class-level params protocol (_gettuple, _getpairs, _getkeys) while creating instance-level ParameterAccessor objects. This removes the dynamic per-instance empty parameter classes that survived the metaclass-removal migration.
- __init__(name='Params', params=(), module=None)[源代码]¶
Build a schema from a legacy
paramsdeclaration.
- __call__(**kwargs)[源代码]¶
Build a parameter accessor, adding unknown names as None defaults.
- 参数:
**kwargs -- Parameter values; names absent from the schema are accepted and default to None.
- 返回:
Accessor over the resolved parameter set, with history and callbacks disabled.
- 返回类型:
- get(name, default=None)[源代码]¶
Look a parameter up by name, falling back to its known aliases.
- 参数:
name -- Parameter name or one of its entries in
_ALIASES.default -- Value returned when the name and its aliases are absent.
- 返回:
The parameter default, or
defaultwhen nothing matched.
- backtrader.parameters.make_legacy_parameter_accessor(params=(), values=None, name='Params')[源代码]¶
Create a legacy-compatible parameter accessor from old params declarations.
- 参数:
name (str)
- class backtrader.parameters.ParameterizedBase[源代码]¶
基类:
objectEnhanced base class for objects with parameters - without metaclass.
This class provides the modern parameter system interface while maintaining backward compatibility with the old MetaParams-based system. It uses regular class mechanisms instead of metaclass.
- classmethod __init_subclass__(**kwargs)[源代码]¶
Called when a class is subclassed. Replaces metaclass functionality.
This method sets up the class for lazy parameter descriptor resolution to avoid inheritance contamination issues.
- set_param(name, value, validate=True)[源代码]¶
Set parameter value with optional validation.
- 参数:
- 抛出:
AttributeError -- If parameter manager not initialized
ValueError -- If validation fails
- 返回类型:
None
- reset_param(name)[源代码]¶
Reset parameter to its default value.
- 参数:
name (str) -- Parameter name
- 抛出:
AttributeError -- If parameter manager not initialized
ValueError -- If parameter doesn't exist or is locked
- 返回类型:
None
- copy_params_from(other, param_names=None, exclude=None)[源代码]¶
Copy parameters from another ParameterizedBase instance.
- 参数:
other (ParameterizedBase) -- Source object to copy parameters from
param_names (List[str] | None) -- Specific parameter names to copy (None for all)
exclude (List[str] | None) -- Parameter names to exclude from copying
- 返回类型:
None
- backtrader.parameters.FloatParam(default=None, min_val=None, max_val=None, doc=None)[源代码]¶
Create a float parameter descriptor with validation.
- 参数:
- 返回类型:
- backtrader.parameters.BoolParam(default=None, doc=None)[源代码]¶
Create a boolean parameter descriptor.
- 参数:
doc (str)
- 返回类型:
- backtrader.parameters.StringParam(default=None, min_length=None, max_length=None, doc=None)[源代码]¶
Create a string parameter descriptor with length validation.
- 参数:
- 返回类型:
- backtrader.parameters.String(min_length=None, max_length=None)[源代码]¶
Create a string validator function.
- backtrader.parameters.OneOf(*choices)[源代码]¶
Create a validator that checks if value is one of the given choices.
- backtrader.parameters.create_param_descriptor(name, default=None, doc=None)[源代码]¶
Create a basic parameter descriptor.
- 参数:
- 返回:
ParameterDescriptor instance
- 返回类型:
- backtrader.parameters.derive_params(base_params, new_params, other_base_params=None)[源代码]¶
Derive parameters by combining base parameters with new ones.
- 参数:
base_params -- Base parameter descriptors or tuples
new_params -- New parameter descriptors or tuples
other_base_params -- Additional base parameters
- 返回:
Dictionary of combined parameter descriptors
- class backtrader.parameters.ParamsBridge[源代码]¶
基类:
objectBridge class for transitioning from MetaParams to new parameter system.
This class provides utilities for converting between the old MetaParams system and the new descriptor-based system during the migration period.
- static extract_params_from_metaparams_class(cls)[源代码]¶
Extract parameter descriptors from a MetaParams-based class.
- 参数:
cls -- Class with MetaParams-based parameters
- 返回:
Dictionary of parameter descriptors
- 返回类型:
- exception backtrader.parameters.ParameterValidationError[源代码]¶
基类:
ValueErrorSpecific exception for parameter validation errors.
- exception backtrader.parameters.ParameterAccessError[源代码]¶
-
Specific exception for parameter access errors.