stats_builder module¶
Mixin for building statistics out of performance metrics.
MetaStatsBuilderMixin class¶
Meta class that exposes a read-only class property StatsBuilderMixin.metrics.
Superclasses
builtins.type
Subclasses
metrics property¶
Metrics supported by StatsBuilderMixin.stats().
StatsBuilderMixin class¶
Mixin that implements StatsBuilderMixin.stats().
Required to be a subclass of Wrapping.
Subclasses
build_metrics_doc class method¶
Build metrics documentation.
metrics class variable¶
Metrics supported by StatsBuilderMixin.
HybridConfig(
start_index=dict(
title='Start Index',
calc_func=<function StatsBuilderMixin.<lambda> at 0x132497e20>,
agg_func=None,
tags='wrapper'
),
end_index=dict(
title='End Index',
calc_func=<function StatsBuilderMixin.<lambda> at 0x132497ec0>,
agg_func=None,
tags='wrapper'
),
total_duration=dict(
title='Total Duration',
calc_func=<function StatsBuilderMixin.<lambda> at 0x132497f60>,
apply_to_timedelta=True,
agg_func=None,
tags='wrapper'
)
)
Returns StatsBuilderMixin._metrics, which gets (hybrid-) copied upon creation of each instance. Thus, changing this config won't affect the class.
To change metrics, you can either change the config in-place, override this property, or overwrite the instance variable StatsBuilderMixin._metrics.
override_metrics_doc class method¶
Call this method on each subclass that overrides StatsBuilderMixin.metrics.
stats method¶
StatsBuilderMixin.stats(
metrics=None,
tags=None,
column=None,
group_by=None,
agg_func=<function mean>,
dropna=None,
silence_warnings=None,
template_context=None,
settings=None,
filters=None,
metric_settings=None
)
Compute various metrics on this object.
Args
metrics:str,tuple,iterable,or dict-
Metrics to calculate.
Each element can be either:
- Metric name (see keys in StatsBuilderMixin.metrics)
- Tuple of a metric name and a settings dict as in StatsBuilderMixin.metrics
- Tuple of a metric name and a template of instance CustomTemplate
- Tuple of a metric name and a list of settings dicts to be expanded into multiple metrics
The settings dict can contain the following keys:
title: Title of the metric. Defaults to the name.tags: Single or multiple tags to associate this metric with. If any of these tags is intags, keeps this metric.check_{filter}andinv_check_{filter}: Whether to check this metric against a filter defined infilters. True (or False for inverse) means to keep this metric.calc_func(required): Calculation function for custom metrics. Must return either a scalar for one column/group, pd.Series for multiple columns/groups, or a dict of such for multiple sub-metrics.resolve_calc_func: whether to resolvecalc_func. If the function can be accessed by traversing attributes of this object, you can specify the path to this function as a string (see deep_getattr() for the path format). Ifcalc_funcis a function, arguments from merged metric settings are matched with arguments in the signature (see below). Ifresolve_calc_funcis False,calc_funcmust accept (resolved) self and dictionary of merged metric settings. Defaults to True.use_shortcuts: Whether to use shortcut properties whenever possible when resolvingcalc_func. Defaults to True.post_calc_func: Function to post-process the result ofcalc_func. Must accept (resolved) self, output ofcalc_func, and dictionary of merged metric settings, and return whatever is acceptable to be returned bycalc_func. Defaults to None.fill_wrap_kwargs: Whether to fillwrap_kwargswithto_timedeltaandsilence_warnings. Defaults to False.apply_to_timedelta: Whether to apply ArrayWrapper.arr_to_timedelta() on the result. To disable this globally, passto_timedelta=Falseinsettings. Defaults to False.pass_{arg}: Whether to pass any argument from the settings (see below). Defaults to True if this argument was found in the function's signature. Set to False to not pass. If argument to be passed was not found,pass_{arg}is removed.resolve_path_{arg}: Whether to resolve an argument that is meant to be an attribute of this object and is the first part of the path ofcalc_func. Passes only optional arguments. Defaults to True. See AttrResolverMixin.resolve_attr().resolve_{arg}: Whether to resolve an argument that is meant to be an attribute of this object and is present in the function's signature. Defaults to False. See AttrResolverMixin.resolve_attr().use_shortcuts_{arg}: Whether to use shortcut properties whenever possible when resolving an argument. Defaults to True.select_col_{arg}: Whether to select the column from an argument that is meant to be an attribute of this object. Defaults to False.template_context: Mapping to replace templates in metric settings. Used across all settings.- Any other keyword argument that overrides the settings or is passed directly to
calc_func.
If
resolve_calc_funcis True, the calculation function may "request" any of the following arguments by accepting them or ifpass_{arg}was found in the settings dict:- Each of AttrResolverMixin.self_aliases: original object (ungrouped, with no column selected)
group_by: won't be passed if it was used in resolving the first attribute ofcalc_funcspecified as a path, usepass_group_by=Trueto pass anywaycolumnmetric_nameagg_funcsilence_warningsto_timedelta: replaced by True if None and frequency is set- Any argument from
settings - Any attribute of this object if it meant to be resolved (see AttrResolverMixin.resolve_attr())
Pass
metrics='all'to calculate all supported metrics. tags:stroriterable-
Tags to select.
See match_tags().
column:str-
Name of the column/group.
Hint
There are two ways to select a column:
obj['a'].stats()andobj.stats(column='a'). They both accomplish the same thing but in different ways:obj['a'].stats()computes statistics of the column 'a' only, whileobj.stats(column='a')computes statistics of all columns first and only then selects the column 'a'. The first method is preferred when you have a lot of data or caching is disabled. The second method is preferred when most attributes have already been cached. group_by:any- Group or ungroup columns. See Grouper.
agg_func:callable-
Aggregation function to aggregate statistics across all columns. By default, takes the mean of all columns. If None, returns all columns as a DataFrame.
Must take
pd.Seriesand return a const.Takes effect if
columnwas specified or this object contains only one column of data.If
agg_funchas been overridden by a metric:- Takes effect if global
agg_funcis not None - Raises a warning if it's None but the result of calculation has multiple values
- Takes effect if global
dropna:bool- Whether to hide metrics that are all NaN.
silence_warnings:bool- Whether to silence all warnings.
template_context:mapping-
Context used to substitute templates.
Gets merged over
template_contextfrom StatsBuilderMixin.stats_defaults.Applied on
settingsand then on each metric settings. filters:dict-
Filters to apply.
Each item consists of the filter name and settings dict.
The settings dict can contain the following keys:
filter_func: Filter function that must accept resolved self and merged settings for a metric, and return either True or False.warning_message: Warning message to be shown when skipping a metric. Can be a template that will be substituted using merged metric settings as context. Defaults to None.inv_warning_message: Same aswarning_messagebut for inverse checks.
Gets merged over
filtersfrom StatsBuilderMixin.stats_defaults. settings:dict-
Global settings and resolution arguments.
Extends/overrides
settingsfrom StatsBuilderMixin.stats_defaults. Gets extended/overridden by metric settings. metric_settings:dict-
Keyword arguments for each metric.
Extends/overrides all global and metric settings.
For template logic, see vectorbtpro.utils.template.
For defaults, see StatsBuilderMixin.stats_defaults.
Hint
There are two types of arguments: optional (or resolution) and mandatory arguments. Optional arguments are only passed if they are found in the function's signature. Mandatory arguments are passed regardless of this. Optional arguments can only be defined using settings (that is, globally), while mandatory arguments can be defined both using default metric settings and {metric_name}_kwargs. Overriding optional arguments using default metric settings or {metric_name}_kwargs won't turn them into mandatory. For this, pass pass_{arg}=True.
Hint
Make sure to resolve and then to re-use as many object attributes as possible to utilize built-in caching (even if global caching is disabled).
Usage
See vectorbtpro.portfolio.base.
stats_defaults property¶
Defaults for StatsBuilderMixin.stats().
See stats_builder.