Skip to content

stats_builder module

Mixin for building statistics out of performance metrics.


MetaStatsBuilderMixin class

MetaStatsBuilderMixin(
    *args,
    **kwargs
)

Meta class that exposes a read-only class property StatsBuilderMixin.metrics.

Superclasses

  • builtins.type

Subclasses


metrics property

Metrics supported by StatsBuilderMixin.stats().


StatsBuilderMixin class

StatsBuilderMixin()

Mixin that implements StatsBuilderMixin.stats().

Required to be a subclass of Wrapping.

Subclasses


build_metrics_doc class method

StatsBuilderMixin.build_metrics_doc(
    source_cls=None
)

Build metrics documentation.


metrics class variable

Metrics supported by StatsBuilderMixin.

Config({
    "start": {
        "title": "Start",
        "calc_func": "<function StatsBuilderMixin.<lambda> at 0x136173420>",
        "agg_func": null,
        "tags": "wrapper"
    },
    "end": {
        "title": "End",
        "calc_func": "<function StatsBuilderMixin.<lambda> at 0x136172fc0>",
        "agg_func": null,
        "tags": "wrapper"
    },
    "period": {
        "title": "Period",
        "calc_func": "<function StatsBuilderMixin.<lambda> at 0x136173060>",
        "apply_to_timedelta": true,
        "agg_func": null,
        "tags": "wrapper"
    }
})

Returns StatsBuilderMixin._metrics, which gets (deep) 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

StatsBuilderMixin.override_metrics_doc(
    __pdoc__,
    source_cls=None
)

Call this method on each subclass that overrides metrics.


stats method

StatsBuilderMixin.stats(
    metrics=None,
    tags=None,
    column=None,
    group_by=None,
    agg_func=<function mean>,
    silence_warnings=None,
    template_mapping=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:

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 in tags, keeps this metric.
  • check_{filter} and inv_check_{filter}: Whether to check this metric against a filter defined in filters. True (or False for inverse) means to keep this metric.
  • calc_func (required): Calculation function for custom metrics. Should 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 resolve calc_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). If calc_func is a function, arguments from merged metric settings are matched with arguments in the signature (see below). If resolve_calc_func is False, calc_func should accept (resolved) self and dictionary of merged metric settings. Defaults to True.
  • post_calc_func: Function to post-process the result of calc_func. Should accept (resolved) self, output of calc_func, and dictionary of merged metric settings, and return whatever is acceptable to be returned by calc_func. Defaults to None.
  • fill_wrap_kwargs: Whether to fill wrap_kwargs with to_timedelta and silence_warnings. Defaults to False.
  • apply_to_timedelta: Whether to apply ArrayWrapper.to_timedelta() on the result. To disable this globally, pass to_timedelta=False in settings. 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 of calc_func. Passes only optional arguments. Defaults to True. See AttrResolver.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 AttrResolver.resolve_attr().
  • template_mapping: 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_func is True, the calculation function may "request" any of the following arguments by accepting them or if pass_{arg} was found in the settings dict:

  • Each of AttrResolver.self_aliases: original object (ungrouped, with no column selected)
  • group_by: won't be passed if it was used in resolving the first attribute of calc_func specified as a path, use pass_group_by=True to pass anyway
  • column
  • metric_name
  • agg_func
  • silence_warnings
  • to_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 AttrResolver.resolve_attr())

Pass metrics='all' to calculate all supported metrics.

tags : str or iterable

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() and obj.stats(column='a'). They both accomplish the same thing but in different ways: obj['a'].stats() computes statistics of the column 'a' only, while obj.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 ColumnGrouper.
agg_func : callable

Aggregation function to aggregate statistics across all columns. Defaults to mean.

Should take pd.Series and return a const.

Has only effect if column was specified or this object contains only one column of data.

If agg_func has been overridden by a metric:

  • it only takes effect if global agg_func is not None
  • will raise a warning if it's None but the result of calculation has multiple values
silence_warnings : bool
Whether to silence all warnings.
template_mapping : mapping

Global mapping to replace templates.

Gets merged over template_mapping from StatsBuilderMixin.stats_defaults.

Applied on settings and 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 should 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 mapping. Defaults to None.
  • inv_warning_message: Same as warning_message but for inverse checks.

Gets merged over filters from StatsBuilderMixin.stats_defaults.

settings : dict

Global settings and resolution arguments.

Extends/overrides settings from 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 vectorbt.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 vectorbt.portfolio.base for examples.


stats_defaults property

Defaults for StatsBuilderMixin.stats().

See stats_builder in settings.


writeable_attrs property

Set of writeable attributes that will be saved/copied along with the config.