← Back to Libraries
vectorbt Library
Lightning-fast vectorized backtesting framework. 100x faster than event-driven frameworks using NumPy vectorization and parallel processing.
Difficulty: Advanced
Category: Backtesting
Installation
$ pip install vectorbt
Code Examples
Fast Vectorized Backtesting
Python
import vectorbt as vbt
import yfinance as yf
# Download data
df = yf.download("BTCUSD", period="2y")
# Define fast and slow windows
fast_ma = vbt.MA.run(df['Close'], 10)
slow_ma = vbt.MA.run(df['Close'], 50)
# Generate entry and exit signals
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
# Run portfolio simulation
pf = vbt.Portfolio.from_signals(df['Close'], entries, exits, init_cash=10000)
# Print results
print(pf.stats())
print(f"Total Return: {pf.total_return():.2%}")
print(f"Sharpe Ratio: {pf.sharpe_ratio():.2f}")
print(f"Max Drawdown: {pf.max_drawdown():.2%}")
Parameter Optimization
Python
import vectorbt as vbt
import numpy as np
# Download data
price = vbt.YFData.download("EURUSD=X", period="2y").get('Close')
# Define parameter ranges
fast_windows = np.arange(10, 50, 5)
slow_windows = np.arange(50, 200, 10)
# Run optimization
fast_ma, slow_ma = vbt.MA.run_combs(price, window=[fast_windows, slow_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)
# Find best parameters
print(pf.total_return().idxmax())
print(f"Best Return: {pf.total_return().max():.2%}")
When to Use vectorbt
- Parameter optimization with thousands of combinations
- Portfolio backtesting with multiple assets
- When speed is critical (100x faster than Backtrader)