Introduction to VectorBT
Relevant source files
The following files were used as context for generating this wiki page:
VectorBT is a high-performance Python library designed for backtesting and analyzing trading strategies at scale. Unlike traditional backtesters that loop through historical data points or strategies one by one, VectorBT "thinks in matrices," packing thousands of configurations into NumPy arrays and processing them simultaneously. This approach allows users to perform massive grid searches and parameter sweeps in seconds rather than hours.
Sources: README.md:31-33, README.md:46-48
The library serves both human researchers and AI agents by providing a mature stack for large-scale experimentation. It integrates deeply with the Python scientific ecosystem, including NumPy, Pandas, and Numba, and offers an optional Rust-based acceleration engine for maximum performance.
Sources: README.md:35-37, pyproject.toml:35-42
Core Architecture and Execution Engines
VectorBT utilizes a layered architecture where high-level Pandas-native APIs dispatch heavy computations to optimized kernels. The system supports multiple execution backends to balance flexibility and speed.
Execution Engines
The library can dispatch operations to different engines based on global settings or per-call parameters.
| Engine | Description |
|---|---|
numba | Uses Just-In-Time (JIT) compilation for NumPy-based kernels. |
rust | Uses precompiled Rust kernels for high performance without JIT overhead. |
auto | Automatically selects Rust if available and supported, otherwise falls back to Numba. |
Sources: rust/README.md:52-58, vectorbt/_settings.py:126
Execution Flow
The following diagram illustrates how a user request for an indicator (e.g., Moving Average) is resolved through the engine layer.
The engine resolver lives in vectorbt/_engine.py and transparently handles kernel selection.
Sources: rust/README.md:15-18, rust/README.md:42-50
Data Structures and Accessors
VectorBT extends Pandas objects using custom accessors, primarily under the .vbt namespace. These accessors provide high-performance operations while maintaining the familiar Pandas API.
Key Accessor Classes
GenericAccessor: Base accessor for all Series and DataFrames.GenericSRAccessor: Specialized forpd.Series.GenericDFAccessor: Specialized forpd.DataFrame.
Sources: vectorbt/generic/accessors.py:186-192, vectorbt/generic/accessors.py:1016-1020
Functionality Mapping
The accessors implement a wide range of vectorized operations, many of which are registered via configuration:
| Category | Key Methods |
|---|---|
| Transformation | fillna, bfill, ffill, cumsum, pct_change |
| Rolling Ops | rolling_mean, rolling_std, rolling_apply |
| Comparisons | crossed_above, crossed_below |
| Reductions | min, max, mean, median, sum, count |
Sources: vectorbt/generic/accessors.py:202-230, vectorbt/generic/accessors.py:650-700
Backtesting and Portfolio Simulation
The core of VectorBT's simulation logic resides in highly optimized Numba kernels (e.g., vectorbt/portfolio/nb.py). These kernels handle order execution, position tracking, and revaluation without Python overhead.
Simulation Logic Flow
Simulation can be performed in column-major or row-major order, supporting complex scenarios like cash sharing among multiple assets.
Simulation Contexts
The simulation engine uses specific "Context" named tuples to pass data through the stack:
SimulationContext: Global state of the simulation.GroupContext: State specific to a group of columns (e.g., assets sharing cash).OrderContext: Information available at the time an individual order is generated.
Sources: vectorbt/portfolio/nb.py:1330-1360
Analysis and Visualization
VectorBT includes a robust "Stats" and "Plots" building system to generate comprehensive reports.
Stats Builder Mixin
The StatsBuilderMixin allows classes to define metrics that can be calculated across all assets or groups. It supports filtering by tags and provides automatic aggregation.
# Example metric definition
start = dict(
title="Start",
calc_func=lambda self: self.wrapper.index[0],
agg_func=None,
tags="wrapper"
)
Sources: vectorbt/generic/stats_builder.py:58-64
Interactive Plotting
Visualization is powered by Plotly, supporting various interactive charts including OHLC, Candlestick, heatmaps, and distribution plots. Default themes and layouts are managed globally via the settings object.
Sources: vectorbt/_settings.py:165-200, vectorbt/generic/accessors.py:1180-1200
Global Settings and Configuration
The vectorbt.settings object is a nested, frozen-key configuration that controls library-wide behavior, including caching, broadcasting rules, and default trading parameters (fees, slippage).
| Sub-config | Purpose |
|---|---|
caching | Enables/disables result caching for expensive operations. |
broadcasting | Defines how arrays of different shapes are aligned. |
portfolio | Sets default init_cash, fees, slippage, and direction. |
plotting | Controls default themes (light/dark) and chart dimensions. |
Sources: vectorbt/_settings.py:125-160, vectorbt/_settings.py:270-300
Conclusion
VectorBT provides a high-performance framework for quantitative research by abstracting the complexities of vectorized execution. By leveraging optimized kernels in Numba and Rust, and providing a flexible Pandas-native interface, it enables researchers to move from simple strategy backtests to massive parameter optimizations and portfolio analysis with minimal code and maximum efficiency.
Sources: README.md:31-40, rust/README.md:15-20