Skip to main content

Backtesting with vectorbt

vectorbt vs backtrader comparison, realistic assumptions, transaction costs, slippage modeling, and building your first Python backtest.

From Thrive on YouTube

Watch the matching Thrive video

Watch the series
The True Cost of Trading: Fees, Spread, Slippage and Funding

The True Cost of Trading: Fees, Spread, Slippage and Funding

Part of Funding Rates, Liquidations and Open Interest. Education only. Not financial advice.

Why vectorbt

Traditional backtesting frameworks process one candle at a time: loop through history, check conditions, simulate trades. Vectorbt uses NumPy array operations to process entire price histories simultaneously. A backtest that takes minutes in a loop-based framework finishes in milliseconds with vectorbt. This speed matters when you need to test thousands of parameter combinations.

python-Installation and basic setup
1pip install vectorbt
2
3import vectorbt as vbt
4import pandas as pd
5import numpy as np
6
7# Fetch BTC data directly through vectorbt
8btc_price = vbt.YFData.download('BTC-USD', start='2020-01-01').get('Close')

Building a Simple SMA Crossover Backtest

The classic starter: buy when a fast moving average crosses above a slow moving average, sell when it crosses below. The strategy is simple, which makes it perfect for learning the framework.

python-SMA crossover strategy
1# Compute moving averages
2fast_ma = vbt.MA.run(btc_price, window=20)
3slow_ma = vbt.MA.run(btc_price, window=50)
4
5# Generate entry/exit signals
6entries = fast_ma.ma_crossed_above(slow_ma)
7exits = fast_ma.ma_crossed_below(slow_ma)
8
9# Run the backtest
10portfolio = vbt.Portfolio.from_signals(
11 btc_price,
12 entries=entries,
13 exits=exits,
14 init_cash=10000,
15 fees=0.001, # 0.1% per trade
16 slippage=0.001, # 0.1% slippage assumption
17)
18
19# Print the performance report
20print(portfolio.stats())

Reading the Performance Report

The stats output contains everything you need to evaluate a strategy. Focus on these numbers. They separate real edges from lucky streaks.

Total returnNet percentage gain/loss after all trades. Compare against buy-and-hold. If your strategy underperforms holding, it is destroying value.
Sharpe ratioRisk-adjusted return. Above 1.0 is acceptable. Above 2.0 is strong. Below 0.5 is noise. Measures return per unit of volatility.
Max drawdownLargest peak-to-trough decline. A strategy with 80% returns but 60% max drawdown is psychologically untradeable for most people.
Win ratePercentage of profitable trades. A 40% win rate with a 3:1 average win/loss ratio is better than 70% win rate with 0.5:1 ratio. Win rate alone is meaningless.
Profit factorGross profits / gross losses. Above 1.5 is good. Above 2.0 is excellent. Below 1.0 means the strategy loses money.

Multiple Strategy Comparison

Vectorbt's real power is testing many parameter combinations at once. Instead of running one backtest, run hundreds: test every combination of fast and slow MA windows and see which performs best.

python-Parameter sweep
1# Test multiple MA combinations simultaneously
2fast_windows = np.arange(10, 60, 5) # 10, 15, 20, ... 55
3slow_windows = np.arange(50, 200, 10) # 50, 60, 70, ... 190
4
5fast_ma, slow_ma = vbt.MA.run_combs(
6 btc_price,
7 window=[fast_windows, slow_windows],
8 r=2, short_names=['fast', 'slow']
9)
10
11entries = fast_ma.ma_crossed_above(slow_ma)
12exits = fast_ma.ma_crossed_below(slow_ma)
13
14portfolio = vbt.Portfolio.from_signals(
15 btc_price, entries, exits,
16 init_cash=10000, fees=0.001, slippage=0.001
17)
18
19# Find the best parameter combination
20returns = portfolio.total_return()
21print(f"Best params: {returns.idxmax()}")
22print(f"Best return: {returns.max():.2%}")

Beware look-ahead bias and overfitting

If your backtest uses future information (even accidentally), results are meaningless. Common traps: using a moving average that includes today's close to generate today's signal, optimizing parameters on the same data you test on, and survivorship bias (only testing assets that survived). The best parameter set in a sweep is almost always overfit. It found the noise, not the signal. Always validate on out-of-sample data.

Put this lesson to work

Free on Thrive, no account needed.