Python library for backtesting and analyzing trading strategies at scale
npx @tessl/cli install tessl/pypi-vectorbt@0.28.00
# VectorBT
1
2
A comprehensive Python library for backtesting and analyzing trading strategies at scale. VectorBT provides high-performance vectorized operations for processing financial data, enables complex portfolio analysis with detailed performance metrics, and offers built-in integrations with popular data sources and advanced visualization capabilities.
3
4
## Package Information
5
6
- **Package Name**: vectorbt
7
- **Language**: Python
8
- **Installation**: `pip install vectorbt`
9
10
## Core Imports
11
12
```python
13
import vectorbt as vbt
14
```
15
16
Common for accessing specific functionality:
17
18
```python
19
from vectorbt import Portfolio, MA, RSI, MACD, BBANDS
20
from vectorbt.data import YFData, BinanceData, CCXTData
21
from vectorbt.records import Orders, Trades, Positions
22
from vectorbt.signals import RAND, STX
23
from vectorbt.labels import FMEAN, TRENDLB
24
```
25
26
## Basic Usage
27
28
```python
29
import vectorbt as vbt
30
import pandas as pd
31
32
# Fetch historical data
33
data = vbt.YFData.download("AAPL", start="2020-01-01", end="2023-01-01")
34
price = data.get("Close")
35
36
# Create a simple moving average crossover strategy
37
fast_window = 10
38
slow_window = 50
39
fast_ma = vbt.MA.run(price, fast_window)
40
slow_ma = vbt.MA.run(price, slow_window)
41
42
# Generate entry and exit signals
43
entries = fast_ma.ma_crossed_above(slow_ma.ma)
44
exits = fast_ma.ma_crossed_below(slow_ma.ma)
45
46
# Run backtest
47
portfolio = vbt.Portfolio.from_signals(
48
close=price,
49
entries=entries,
50
exits=exits,
51
init_cash=10000
52
)
53
54
# Analyze performance
55
print(f"Total Return: {portfolio.total_return():.2%}")
56
print(f"Sharpe Ratio: {portfolio.sharpe_ratio():.2f}")
57
print(f"Max Drawdown: {portfolio.max_drawdown():.2%}")
58
59
# Visualize results
60
portfolio.plot().show()
61
```
62
63
## Architecture
64
65
VectorBT follows a modular design built on high-performance vectorized operations:
66
67
- **Base Layer**: ArrayWrapper and core utilities for efficient pandas/NumPy integration
68
- **Data Layer**: Unified data acquisition from multiple sources (Yahoo Finance, Binance, CCXT)
69
- **Analysis Layer**: Technical indicators, signal generation, and statistical analysis
70
- **Portfolio Layer**: Comprehensive backtesting engine with detailed record keeping
71
- **Visualization Layer**: Integrated plotting capabilities with Plotly
72
73
The library is designed for maximum reusability across quantitative finance applications, enabling efficient testing of thousands of strategy variations simultaneously using vectorized computations.
74
75
## Capabilities
76
77
### Portfolio Simulation & Analysis
78
79
Core backtesting engine for strategy evaluation with comprehensive performance metrics, trade analysis, and risk management. Includes order execution simulation, position tracking, and detailed performance attribution.
80
81
```python { .api }
82
class Portfolio:
83
@classmethod
84
def from_signals(cls, close, entries, exits, **kwargs): ...
85
@classmethod
86
def from_orders(cls, close, orders, **kwargs): ...
87
def total_return(self): ...
88
def sharpe_ratio(self): ...
89
def max_drawdown(self): ...
90
```
91
92
[Portfolio Analysis](./portfolio-analysis.md)
93
94
### Data Sources & Management
95
96
Unified data acquisition and management system supporting multiple financial data providers with automatic synchronization, caching, and preprocessing capabilities.
97
98
```python { .api }
99
class YFData:
100
@classmethod
101
def download(cls, symbols, **kwargs): ...
102
def update(self): ...
103
104
class BinanceData:
105
@classmethod
106
def download(cls, symbols, **kwargs): ...
107
```
108
109
[Data Management](./data-management.md)
110
111
### Technical Indicators
112
113
Comprehensive library of technical indicators with factory pattern for creating custom indicators. Includes traditional indicators (MA, RSI, MACD) and advanced statistical measures.
114
115
```python { .api }
116
class MA:
117
@classmethod
118
def run(cls, close, window, **kwargs): ...
119
120
class RSI:
121
@classmethod
122
def run(cls, close, window=14, **kwargs): ...
123
124
class MACD:
125
@classmethod
126
def run(cls, close, **kwargs): ...
127
```
128
129
[Technical Indicators](./indicators-signals.md)
130
131
### Signal Generation & Processing
132
133
Advanced signal generation system for creating entry/exit rules with support for stop losses, take profits, and complex conditional logic. Includes random signal generators for strategy testing.
134
135
```python { .api }
136
class RAND:
137
@classmethod
138
def run(cls, shape, prob=0.1, **kwargs): ...
139
140
class STX:
141
@classmethod
142
def run(cls, entries, stops, **kwargs): ...
143
```
144
145
[Indicators & Signals](./indicators-signals.md)
146
147
### Label Generation for Machine Learning
148
149
Look-ahead analysis tools for generating labels from future price movements, enabling machine learning model training on financial time series data.
150
151
```python { .api }
152
class FMEAN:
153
@classmethod
154
def run(cls, close, window, **kwargs): ...
155
156
class TRENDLB:
157
@classmethod
158
def run(cls, close, **kwargs): ...
159
```
160
161
[Label Generation](./label-generation.md)
162
163
### Records Management
164
165
Core record classes for managing and analyzing trading data including orders, trades, positions, and drawdowns with efficient sparse data structures.
166
167
```python { .api }
168
class Records: ...
169
class MappedArray: ...
170
class Orders: ...
171
class Trades: ...
172
class Positions: ...
173
class Drawdowns: ...
174
```
175
176
[Records Management](./records-management.md)
177
178
### Generic Time Series Tools
179
180
Advanced tools for time series analysis including range analysis, drawdown detection, and data splitting strategies for backtesting and cross-validation.
181
182
```python { .api }
183
class Ranges: ...
184
class RangeSplitter: ...
185
class RollingSplitter: ...
186
class ExpandingSplitter: ...
187
```
188
189
[Generic Analysis](./generic-analysis.md)
190
191
### Utility Functions & Configuration
192
193
Core utilities for configuration management, caching, plotting, and template systems. Includes asynchronous job scheduling and data transformation utilities.
194
195
```python { .api }
196
vbt.settings: Config
197
def make_figure(**kwargs): ...
198
def cached_property(func): ...
199
class Config: ...
200
```
201
202
[Utilities & Configuration](./utilities-config.md)
203
204
## Types
205
206
```python { .api }
207
# Core types available in vectorbt._typing
208
import numpy as np
209
import pandas as pd
210
from typing import Union
211
from enum import IntEnum
212
213
Scalar = Union[int, float, complex, np.number]
214
Array = np.ndarray
215
SeriesFrame = Union[pd.Series, pd.DataFrame]
216
ArrayLike = Union[Array, SeriesFrame]
217
218
# Portfolio enums (from vectorbt.portfolio.enums)
219
class Direction(IntEnum):
220
LongOnly = 0
221
ShortOnly = 1
222
Both = 2
223
224
class OrderSide(IntEnum):
225
Buy = 0
226
Sell = 1
227
228
class OrderStatus(IntEnum):
229
Filled = 0
230
Ignored = 1
231
Rejected = 2
232
233
class SizeType(IntEnum):
234
Amount = 0
235
Value = 1
236
Percent = 2
237
TargetPercent = 3
238
239
# Signal enums (from vectorbt.signals.enums)
240
class StopType(IntEnum):
241
StopLoss = 0
242
TrailStop = 1
243
TakeProfit = 2
244
245
class FactoryMode(IntEnum):
246
Entries = 0
247
Exits = 1
248
Both = 2
249
Chain = 3
250
251
# Label enums (from vectorbt.labels.enums)
252
class TrendMode(IntEnum):
253
Binary = 0
254
BinaryCont = 1
255
BinaryContSat = 2
256
PctChange = 3
257
PctChangeNorm = 4
258
```
259
260
## Pandas Accessors
261
262
VectorBT extends pandas with the `.vbt` accessor providing direct access to all functionality:
263
264
- `.vbt.signals.*` - Signal analysis methods
265
- `.vbt.returns.*` - Return analysis methods
266
- `.vbt.ohlc.*` - OHLC data specific methods
267
- `.vbt.px.*` - Price data methods
268
269
```python
270
# Example accessor usage
271
price.vbt.returns.sharpe_ratio()
272
signals.vbt.signals.first()
273
```