VectorBT vs Backtrader: Choosing Your Backtesting Framework
VectorBT and Backtrader are two very different Python backtesting frameworks. VectorBT is fast and pandas-native; Backtrader is event-driven and flexible. Here's how to choose.
Backtesting is the process of simulating a trading strategy on historical data to estimate its performance. In Python, two popular backtesting frameworks serve very different needs: VectorBT (vectorized, extremely fast) and Backtrader (event-driven, highly flexible).
VectorBT: Speed First
VectorBT treats your entire historical price series as numpy arrays and runs calculations in C-level speed via numba JIT compilation. It’s 10-100x faster than Backtrader for large parameter sweeps.
Best for:
- Parameter optimization over thousands of parameter combinations
- Long histories with millions of rows
- Strategy ideas that don’t require complex order management
- Quick prototyping and signal research
import vectorbt as vbt
import pandas as pd
import numpy as np
# Download data
btc = vbt.CCXTData.download('BTC/USDT', start='2020-01-01')
# Define simple dual moving average strategy
fast_ma = btc.close.vbt.wrapper.run_window(20, win_type='simple')
slow_ma = btc.close.vbt.wrapper.run_window(50, win_type='simple')
entries = fast_ma > slow_ma
exits = fast_ma < slow_ma
# Run backtest
pf = vbt.Portfolio.from_signals(
btc.close,
entries,
exits,
fees=0.001, # 0.1% per trade
slippage=0.0005
)
# Analyze
total_return = pf.total_return()
sharpe = pf.sharpe_ratio()
max_dd = pf.max_drawdown()
print(f"Total return: {total_return:.2%}")
print(f"Sharpe: {sharpe:.2f}")
print(f"Max drawdown: {max_dd:.2%}")
# Parameter sweep
param_names = ['fast_window', 'slow_window']
param_product = vbt.ParamProduct([10, 20, 30, 40, 50], [50, 100, 150, 200])
results = vbt.backtest(
lambda params: (fast_ma > slow_ma, fast_ma < slow_ma),
param_product
)
Backtrader: Realism First
Backtrader is event-driven: it simulates each bar (candle) and processes orders through a broker simulation. It supports live trading, multiple data feeds, and complex order types.
Best for:
- Strategies with complex order management
- Portfolio-level allocation across multiple assets
- Strategies requiring realistic fill modeling
- Live trading integration
import backtrader as bt
class SMAStrategy(bt.Strategy):
params = (('fast', 20), ('slow', 50),)
def __init__(self):
self.fast_ma = bt.indicators.SMA(self.data.close, period=self.p.fast)
self.slow_ma = bt.indicators.SMA(self.data.close, period=self.p.slow)
self.crossover = bt.indicators.CrossOver(self.fast_ma, self.slow_ma)
def next(self):
if self.crossover > 0: # Golden cross
self.buy()
elif self.crossover < 0: # Death cross
self.sell()
cerebro = bt.Cerebro()
cerebro.addstrategy(SMAStrategy)
data = bt.feeds.YahooFinanceData(dataname='AAPL',
fromdate='2020-01-01',
todate='2024-01-01')
cerebro.adddata(data)
cerebro.broker.setcommission(commission=0.001)
cerebro.run()
print(f'Final portfolio value: {cerebro.broker.getvalue():.2f}')
Key Differences
| Feature | VectorBT | Backtrader |
|---|---|---|
| Speed | Extremely fast (numba) | Moderate (Python loops) |
| Order model | Simple signal-based | Full order lifecycle |
| Parameter sweeps | Native, fast | Manual or OptReturn |
| Multi-asset | Yes | Yes (via datas) |
| Live trading | No | Yes (via brokers) |
| Fill modeling | Simplified | Realistic |
| Learning curve | Low | Moderate |
Which to Choose
Use VectorBT when: You’re in the research phase, testing many parameter combinations, and need speed. Great for signal discovery and factor research.
Use Backtrader when: You need realistic order handling, multi-asset portfolio simulation, or you plan to eventually run the strategy live.
Use both: Run initial screening in VectorBT; validate promising strategies in Backtrader for realism.
Common Pitfalls
VectorBT: Its simplified order model can produce optimistic results. A strategy that looks great in VectorBT may perform worse in Backtrader or live due to fill timing.
Backtrader: Slow for parameter sweeps. If you’re testing 10,000 parameter combinations, Backtrader will take days.
References
- McKinney, Python for Data Analysis, Ch. 11. O’Reilly, 2023. ISBN: 978-1-492-07231-9.
- Chan, Quantitative Trading, Ch. 1. Wiley, 2008. ISBN: 978-0-470-28488-9.
- López de Prado, Advances in Financial Machine Learning, Ch. 10. Wiley, 2018. ISBN: 978-1-119-48208-6.