Generic Math & Stats API
Relevant source files
The following files were used as context for generating this wiki page:
The Generic Math & Stats API in vectorbt provides a unified framework for calculating performance metrics and statistical properties across various data types. It is built upon a mixin-based architecture that allows for standardized computation, aggregation, and visualization of data stored in Pandas Series and DataFrames, often accelerated by Numba or Rust backends.
This API serves as the foundation for higher-level modules, such as signal analysis and portfolio backtesting, by providing core functionalities like rolling transformations, window-based statistics, and complex metric resolution. It ensures that any object inheriting from the base wrapping classes can expose a consistent .stats() interface for rapid analysis.
Core Architecture: StatsBuilderMixin
The StatsBuilderMixin is the primary component responsible for the stats() method. it enables objects to define a set of supported metrics and provides the logic to resolve, calculate, and aggregate them.
Metric Configuration
Metrics are defined using a Config object, which acts as a dictionary-like structure containing metadata for each metric. Each metric entry typically includes:
title: The display name of the metric.calc_func: The function or attribute name used to calculate the metric.agg_func: A function to aggregate results across multiple columns (defaults tonp.mean).tags: Labels for filtering metrics (e.g., "wrapper", "generic", "describe").
Sources: vectorbt/generic/stats_builder.py:31-64, vectorbt/generic/stats_builder.py:75-104
The Stats Calculation Flow
The stats() method follows a rigorous pipeline to transform raw data into a statistical summary. This includes merging global and metric-specific settings, applying template substitutions, and filtering based on tags or custom logic.
This diagram illustrates the internal processing logic of the StatsBuilderMixin.stats method.
Sources: vectorbt/generic/stats_builder.py:179-250, vectorbt/generic/stats_builder.py:330-410
Generic Accessor API
The GenericAccessor (accessed via .vbt) integrates the stats and plots builders into Pandas objects. It provides high-performance implementations of common mathematical operations, often dispatching to specialized kernels.
Transformation and Window Functions
The API supports a wide range of rolling and expanding window operations:
- Rolling Operations:
rolling_std,rolling_mean,rolling_apply. - Expanding Operations:
expanding_std,expanding_mean,expanding_apply. - Exponentially Weighted:
ewm_mean,ewm_std.
Sources: vectorbt/generic/accessors.py:209-260
Reduction Operations
Reduction methods allow for collapsing data along axes while supporting grouping and indexing:
reduce: A generic method to apply a reduction function across columns or groups.describe: Generates descriptive statistics (count, mean, std, min, percentiles, max).value_counts: Returns unique value frequencies, supporting mapping for categorical data.
Sources: vectorbt/generic/accessors.py:449-480, vectorbt/generic/accessors.py:651-690
API Parameters for stats()
| Parameter | Type | Description |
|---|---|---|
metrics | Optional[MaybeIterable] | Metrics to calculate. Can be 'all' or specific names. |
tags | Optional[MaybeIterable] | Tags used to filter which metrics to include. |
column | Optional[Label] | Calculate stats for a specific column only. |
group_by | GroupByLike | Grouping logic for aggregating data. |
agg_func | Callable | Function to aggregate across columns (default np.mean). |
settings | Dict | Global settings for calculation and resolution. |
Sources: vectorbt/generic/stats_builder.py:106-155
Low-Level Math Utilities (Rust Engine)
For performance-critical paths, vectorbt utilizes a Rust-based engine. This engine implements fundamental mathematical utilities designed for high precision and numerical stability.
Numerical Stability Functions
The Rust engine provides specialized functions to handle floating-point comparisons and arithmetic, which are essential for deterministic backtesting results.
| Function | Logic | Purpose |
|---|---|---|
is_close | `(a - b).abs() <= max(ABS_TOL, REL_TOL * max( | a |
add | if is_addition_zero(a, b) then 0.0 else a + b | Prevents precision drift in cumulative sums. |
is_less | !is_close(a, b) && a < b | Strict less-than comparison ignoring tolerance. |
get_return | (output - input) / input | Calculates percentage change with 0-check. |
Sources: rust/src/portfolio.rs:43-90
Implementation in Specialized Classes
The Math & Stats API is extended by specialized classes like Trades to handle domain-specific calculations.
Trade Statistics
The Trades class inherits from Ranges and StatsBuilderMixin, adding metrics specific to financial performance:
win_rate: Ratio of winning trades to total trades.profit_factor: Ratio of total profit to total loss.expectancy: Average profitability per trade.sqn: System Quality Number, measuring the "quality" of a trading system.
Sources: vectorbt/portfolio/trades.py:230-268
Class Hierarchy
The relationship between accessors and mixins follows a multiple inheritance pattern to compose functionality.
This diagram shows how GenericAccessor inherits the ability to build statistics and plots while being grounded in the Wrapping base class.
Sources: vectorbt/generic/stats_builder.py:27, vectorbt/generic/accessors.py:169-171
Conclusion
The Generic Math & Stats API provides a robust, extensible framework for data analysis. By separating metric definition (via Config) from the execution engine (via dispatch and Rust/Numba), vectorbt achieves a balance between high-level ease of use and low-level performance. The stats() pipeline ensures that complex transformations remain consistent across different types of data objects, facilitating large-scale strategy research and performance evaluation.