Python library for backtesting and analyzing trading strategies at scale
Project description
[!TIP] New in 0.28:
- Plotly 6 support
ticker_kwargsinYFData- Fixed Pandas TA dependency (→ pandas-ta-classic).
:package: Installation
pip install -U vectorbt
To install optional dependencies as well:
pip install -U "vectorbt[full]"
:sparkles: Usage
VectorBT lets you backtest strategies in just a few lines of Python.
- Profit from investing $100 in Bitcoin since 2014:
import vectorbt as vbt
data = vbt.YFData.download("BTC-USD")
price = data.get("Close")
pf = vbt.Portfolio.from_holding(price, init_cash=100)
print(pf.total_profit())
19501.10906763755
- Buy when the 10-day SMA crosses above the 50-day SMA, and sell on the opposite crossover:
fast_ma = vbt.MA.run(price, 10)
slow_ma = vbt.MA.run(price, 50)
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(price, entries, exits, init_cash=100)
print(pf.total_profit())
34417.80960086067
- Generate 1,000 strategies with random signals and test them on BTC and ETH:
import numpy as np
symbols = ["BTC-USD", "ETH-USD"]
data = vbt.YFData.download(symbols, missing_index="drop")
price = data.get("Close")
n = np.random.randint(10, 101, size=1000).tolist()
pf = vbt.Portfolio.from_random_signals(price, n=n, init_cash=100, seed=42)
mean_expectancy = pf.trades.expectancy().groupby(["randnx_n", "symbol"]).mean()
fig = mean_expectancy.unstack().vbt.scatterplot(xaxis_title="randnx_n", yaxis_title="mean_expectancy")
fig.show()
- For hyperparameter optimization fans: test 10,000 window combinations of a dual-SMA crossover strategy on BTC, ETH, and XRP:
symbols = ["BTC-USD", "ETH-USD", "XRP-USD"]
data = vbt.YFData.download(symbols, missing_index="drop")
price = data.get("Close")
windows = np.arange(2, 101)
fast_ma, slow_ma = vbt.MA.run_combs(price, window=windows, r=2, short_names=["fast", "slow"])
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(price, entries, exits, size=np.inf, fees=0.001, freq="1D")
fig = pf.total_return().vbt.heatmap(
x_level="fast_window", y_level="slow_window", slider_level="symbol", symmetric=True,
trace_kwargs=dict(colorbar=dict(title="Total return", tickformat="%")))
fig.show()
Inspect any strategy configuration by indexing with pandas:
print(pf[(10, 20, "ETH-USD")].stats())
Start 2017-11-09 00:00:00+00:00
End 2026-01-03 00:00:00+00:00
Period 2978 days 00:00:00
Start Value 100.0
End Value 1604.093789
Total Return [%] 1504.093789
Benchmark Return [%] 866.094127
Max Gross Exposure [%] 100.0
Total Fees Paid 204.226289
Max Drawdown [%] 70.734951
Max Drawdown Duration 1095 days 00:00:00
Total Trades 81
Total Closed Trades 80
Total Open Trades 1
Open Trade PnL -14.232533
Win Rate [%] 41.25
Best Trade [%] 120.511071
Worst Trade [%] -27.772271
Avg Winning Trade [%] 27.265519
Avg Losing Trade [%] -9.022864
Avg Winning Trade Duration 32 days 20:21:49.090909091
Avg Losing Trade Duration 8 days 16:51:03.829787234
Profit Factor 1.275515
Expectancy 18.979079
Sharpe Ratio 0.861945
Calmar Ratio 0.572758
Omega Ratio 1.20277
Sortino Ratio 1.301377
Name: (10, 20, ETH-USD), dtype: object
Same goes for plotting:
pf[(10, 20, "ETH-USD")].plot().show()
It's not all about backtesting! VectorBT can also help with financial data analysis and visualization.
- Create a GIF that animates Bollinger Bands %B and bandwidth across multiple symbols:
symbols = ["BTC-USD", "ETH-USD", "XRP-USD"]
data = vbt.YFData.download(symbols, period="6mo", missing_index="drop")
price = data.get("Close")
bbands = vbt.BBANDS.run(price)
def plot(index, bbands):
bbands = bbands.loc[index]
fig = vbt.make_subplots(
rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.15,
subplot_titles=("%B", "Bandwidth"))
fig.update_layout(showlegend=False, width=750, height=400)
bbands.percent_b.vbt.ts_heatmap(
trace_kwargs=dict(zmin=0, zmid=0.5, zmax=1, colorscale="Spectral", colorbar=dict(
y=(fig.layout.yaxis.domain[0] + fig.layout.yaxis.domain[1]) / 2, len=0.5
)), add_trace_kwargs=dict(row=1, col=1), fig=fig)
bbands.bandwidth.vbt.ts_heatmap(
trace_kwargs=dict(colorbar=dict(
y=(fig.layout.yaxis2.domain[0] + fig.layout.yaxis2.domain[1]) / 2, len=0.5
)), add_trace_kwargs=dict(row=2, col=1), fig=fig)
return fig
vbt.save_animation("bbands.gif", bbands.wrapper.index, plot, bbands, delta=90, step=3, fps=3)
100%|██████████| 31/31 [00:21<00:00, 1.21it/s]
This is just the tip of the iceberg. Visit the website to learn more.
:link: Links
:balance_scale: License
This work is fair-code distributed under the Apache 2.0 with Commons Clause license.
The source code is open, and everyone (individuals and organizations) may use it for free. However, you may not sell products or services that are primarily this software.
If you have questions or want to request a license exception, please contact the author.
Installing optional dependencies may be subject to a more restrictive license.
:star: Star History
:warning: Disclaimer
This software is for educational purposes only. Do not risk money you cannot afford to lose.
USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file vectorbt-0.28.4.tar.gz.
File metadata
- Download URL: vectorbt-0.28.4.tar.gz
- Upload date:
- Size: 486.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4810815fe23cfa440c0dcc17b3f56e1e09cfbbc74de541000706980b298cbbb3
|
|
| MD5 |
9d64c0270b2dbd28d2f5e2935429a0b2
|
|
| BLAKE2b-256 |
fcf35d776cf70980045a1ff6aa3e5e33f172eae9bfd1a455e540247098c63b9a
|
Provenance
The following attestation bundles were made for vectorbt-0.28.4.tar.gz:
Publisher:
python-publish.yml on polakowo/vectorbt
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
vectorbt-0.28.4.tar.gz -
Subject digest:
4810815fe23cfa440c0dcc17b3f56e1e09cfbbc74de541000706980b298cbbb3 - Sigstore transparency entry: 855770310
- Sigstore integration time:
-
Permalink:
polakowo/vectorbt@6cb7ae3b88ca30ec33e2084b655b3bc02563af2f -
Branch / Tag:
refs/tags/v0.28.4 - Owner: https://github.com/polakowo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@6cb7ae3b88ca30ec33e2084b655b3bc02563af2f -
Trigger Event:
release
-
Statement type:
File details
Details for the file vectorbt-0.28.4-py3-none-any.whl.
File metadata
- Download URL: vectorbt-0.28.4-py3-none-any.whl
- Upload date:
- Size: 420.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5af539e896114f184908f4a7f7582224edb642f8e93a4f50b899c3b07af3ec27
|
|
| MD5 |
c683d99943adb1f86d0ae72007749c7b
|
|
| BLAKE2b-256 |
4fe07f56bf5c2f7d984939061b736ac00bffcc12e802e4502147d20d972da81e
|
Provenance
The following attestation bundles were made for vectorbt-0.28.4-py3-none-any.whl:
Publisher:
python-publish.yml on polakowo/vectorbt
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
vectorbt-0.28.4-py3-none-any.whl -
Subject digest:
5af539e896114f184908f4a7f7582224edb642f8e93a4f50b899c3b07af3ec27 - Sigstore transparency entry: 855770354
- Sigstore integration time:
-
Permalink:
polakowo/vectorbt@6cb7ae3b88ca30ec33e2084b655b3bc02563af2f -
Branch / Tag:
refs/tags/v0.28.4 - Owner: https://github.com/polakowo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@6cb7ae3b88ca30ec33e2084b655b3bc02563af2f -
Trigger Event:
release
-
Statement type: