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
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.
1pip install vectorbt23import vectorbt as vbt4import pandas as pd5import numpy as np67# Fetch BTC data directly through vectorbt8btc_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.
1# Compute moving averages2fast_ma = vbt.MA.run(btc_price, window=20)3slow_ma = vbt.MA.run(btc_price, window=50)45# Generate entry/exit signals6entries = fast_ma.ma_crossed_above(slow_ma)7exits = fast_ma.ma_crossed_below(slow_ma)89# Run the backtest10portfolio = vbt.Portfolio.from_signals(11 btc_price,12 entries=entries,13 exits=exits,14 init_cash=10000,15 fees=0.001, # 0.1% per trade16 slippage=0.001, # 0.1% slippage assumption17)1819# Print the performance report20print(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 return | Net percentage gain/loss after all trades. Compare against buy-and-hold. If your strategy underperforms holding, it is destroying value. |
| Sharpe ratio | Risk-adjusted return. Above 1.0 is acceptable. Above 2.0 is strong. Below 0.5 is noise. Measures return per unit of volatility. |
| Max drawdown | Largest peak-to-trough decline. A strategy with 80% returns but 60% max drawdown is psychologically untradeable for most people. |
| Win rate | Percentage 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 factor | Gross 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.
1# Test multiple MA combinations simultaneously2fast_windows = np.arange(10, 60, 5) # 10, 15, 20, ... 553slow_windows = np.arange(50, 200, 10) # 50, 60, 70, ... 19045fast_ma, slow_ma = vbt.MA.run_combs(6 btc_price,7 window=[fast_windows, slow_windows],8 r=2, short_names=['fast', 'slow']9)1011entries = fast_ma.ma_crossed_above(slow_ma)12exits = fast_ma.ma_crossed_below(slow_ma)1314portfolio = vbt.Portfolio.from_signals(15 btc_price, entries, exits,16 init_cash=10000, fees=0.001, slippage=0.00117)1819# Find the best parameter combination20returns = portfolio.total_return()21print(f"Best params: {returns.idxmax()}")22print(f"Best return: {returns.max():.2%}")Beware look-ahead bias and overfitting
Put this lesson to work
Free on Thrive, no account needed.