Skip to content
New: Star-import, signal unraveling, Python 3.12 support, and more

#
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

- MetaAnalyzable

### metrics property

Metrics supported by StatsBuilderMixin.stats().

## StatsBuilderMixin class

    StatsBuilderMixin()

Mixin that implements StatsBuilderMixin.stats().

Required to be a subclass of Wrapping.

Subclasses

- Analyzable

### build_metrics_doc class method

    StatsBuilderMixin.build_metrics_doc(
        source_cls=None
    )

Build metrics documentation.

### metrics class variable

Metrics supported by StatsBuilderMixin.

    HybridConfig(
        start=dict(
            title='Start',
            calc_func=<function StatsBuilderMixin.<lambda> at 0x7ff359501e10>,
            agg_func=None,
            tags='wrapper'
        ),
        end=dict(
            title='End',
            calc_func=<function StatsBuilderMixin.<lambda> at 0x7ff359501ea0>,
            agg_func=None,
            tags='wrapper'
        ),
        period=dict(
            title='Period',
            calc_func=<function StatsBuilderMixin.<lambda> at 0x7ff359501f30>,
            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

    StatsBuilderMixin.override_metrics_doc(
        __pdoc__,
        source_cls=None
    )

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 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. 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 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` must accept (resolved) self and dictionary of merged metric settings. Defaults to True.
  - `use_shortcuts`: Whether to use shortcut properties whenever possible when resolving `calc_func`. Defaults to True.
  - `post_calc_func`: Function to post-process the result of `calc_func`. Must 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.arr_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 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_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 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 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 AttrResolverMixin.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 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.Series` and return a const.

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

  If `agg_func` has been overridden by a metric:

  - Takes effect if global `agg_func` is not None
  - Raises a warning if it's None but the result of calculation has multiple values
`dropna` :`bool`
  Whether to hide metrics that are all NaN.
`silence_warnings` :`bool`
  Whether to silence all warnings.
`template_context` :`mapping`

  Global context to replace templates.

  Gets merged over `template_context` 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 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 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 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.

#### Cookie consent

We use cookies to recognize your repeated visits and preferences, as well as to measure the effectiveness of our documentation and whether users find what they're searching for. With your consent, you're helping us to make our documentation better.

- Google Analytics
- GitHub

Manage settings