Raptorbt
RaptorBT is a high-performance backtesting engine written in Rust with Python bindings via PyO3. It serves as a drop-in replacement for VectorBT, providing significant performance improvements while maintaining full metric parity.
Install / Use
/learn @alphabench/RaptorbtREADME
RaptorBT
Blazing-fast backtesting for the modern quant.
RaptorBT is a high-performance backtesting engine written in Rust with Python bindings via PyO3. It serves as a drop-in replacement for VectorBT — delivering HFT-grade compute efficiency with full metric parity.
<p align="center"> <strong>5,800x faster</strong> · <strong>45x smaller</strong> · <strong>100% deterministic</strong> </p>Quick Install
pip install raptorbt
30-Second Example
import numpy as np
import raptorbt
# Configure
config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001)
# Run backtest
result = raptorbt.run_single_backtest(
timestamps=timestamps, open=open, high=high, low=low, close=close,
volume=volume, entries=entries, exits=exits,
direction=1, weight=1.0, symbol="AAPL", config=config,
)
# Results
print(f"Return: {result.metrics.total_return_pct:.2f}%")
print(f"Sharpe: {result.metrics.sharpe_ratio:.2f}")
Developed and maintained by the Alphabench team.
Table of Contents
- Overview
- Performance
- Architecture
- Installation
- Quick Start
- Strategy Types
- Metrics
- Indicators
- Stop-Loss & Take-Profit
- VectorBT Comparison
- API Reference
- Building from Source
- Testing
Overview
RaptorBT was built to address the performance limitations of VectorBT. Benchmarked by the Alphabench team:
| Metric | VectorBT | RaptorBT | Improvement | | ----------------------------- | ------------------- | ------------ | ------------------------- | | Disk Footprint | ~450MB | <10MB | 45x smaller | | Startup Latency | 200-600ms | <10ms | 20-60x faster | | Backtest Speed (1K bars) | 1460ms | 0.25ms | 5,800x faster | | Backtest Speed (50K bars) | 43ms | 1.7ms | 25x faster | | Memory Usage | High (JIT + pandas) | Low (native) | Significant reduction |
Key Features
- 6 Strategy Types: Single instrument, basket/collective, pairs trading, options, spreads, and multi-strategy
- Batch Spread Backtesting: Run multiple spread backtests in parallel via Rayon with GIL released
- Monte Carlo Simulation: Correlated multi-asset forward projection via GBM + Cholesky decomposition
- 33 Metrics: Full parity with VectorBT including Sharpe, Sortino, Calmar, Omega, SQN, Payoff Ratio, Recovery Factor, and more
- 12 Technical Indicators: SMA, EMA, RSI, MACD, Stochastic, ATR, Bollinger Bands, ADX, VWAP, Supertrend, Rolling Min, Rolling Max
- Stop/Target Management: Fixed, ATR-based, and trailing stops with risk-reward targets
- 100% Deterministic: No JIT compilation variance between runs
- Native Parallelism: Rayon-based parallel processing with explicit SIMD optimizations
Performance
Benchmark Results
Tested on Apple Silicon M-series with random walk price data and SMA crossover strategy:
┌─────────────┬────────────┬───────────┬──────────┐
│ Data Size │ VectorBT │ RaptorBT │ Speedup │
├─────────────┼────────────┼───────────┼──────────┤
│ 1,000 bars │ 1,460 ms │ 0.25 ms │ 5,827x │
│ 5,000 bars │ 36 ms │ 0.24 ms │ 153x │
│ 10,000 bars │ 37 ms │ 0.46 ms │ 80x │
│ 50,000 bars │ 43 ms │ 1.68 ms │ 26x │
└─────────────┴────────────┴───────────┴──────────┘
Note: First VectorBT run includes Numba JIT compilation overhead. Subsequent runs are faster but still significantly slower than RaptorBT.
Metric Accuracy
RaptorBT produces identical results to VectorBT:
VectorBT Total Return: 7.2764%
RaptorBT Total Return: 7.2764%
Difference: 0.0000% ✓
Architecture
raptorbt/
├── src/
│ ├── core/ # Core types and error handling
│ │ ├── types.rs # BacktestConfig, BacktestResult, Trade, Metrics
│ │ ├── error.rs # RaptorError enum
│ │ ├── session.rs # SessionTracker, SessionConfig (intraday sessions)
│ │ └── timeseries.rs # Time series utilities
│ │
│ ├── strategies/ # Strategy implementations
│ │ ├── single.rs # Single instrument backtest
│ │ ├── basket.rs # Basket/collective strategies
│ │ ├── pairs.rs # Pairs trading
│ │ ├── options.rs # Options strategies
│ │ ├── spreads.rs # Multi-leg spread strategies
│ │ └── multi.rs # Multi-strategy combining
│ │
│ ├── indicators/ # Technical indicators
│ │ ├── trend.rs # SMA, EMA, Supertrend
│ │ ├── momentum.rs # RSI, MACD, Stochastic
│ │ ├── volatility.rs # ATR, Bollinger Bands
│ │ ├── strength.rs # ADX
│ │ ├── volume.rs # VWAP
│ │ └── rolling.rs # Rolling Min/Max (LLV/HHV)
│ │
│ ├── metrics/ # Performance metrics
│ │ ├── streaming.rs # Streaming metric calculations
│ │ ├── drawdown.rs # Drawdown analysis
│ │ └── trade_stats.rs # Trade statistics
│ │
│ ├── signals/ # Signal processing
│ │ ├── processor.rs # Entry/exit signal processing
│ │ ├── synchronizer.rs # Multi-instrument sync
│ │ └── expression.rs # Signal expressions
│ │
│ ├── stops/ # Stop-loss implementations
│ │ ├── fixed.rs # Fixed percentage stops
│ │ ├── atr.rs # ATR-based stops
│ │ └── trailing.rs # Trailing stops
│ │
│ ├── portfolio/ # Portfolio-level analysis
│ │ ├── monte_carlo.rs # Monte Carlo forward simulation (GBM + Cholesky)
│ │ ├── allocation.rs # Capital allocation
│ │ ├── engine.rs # Portfolio engine
│ │ └── position.rs # Position management
│ │
│ ├── python/ # PyO3 bindings
│ │ ├── bindings.rs # Python function exports
│ │ └── numpy_bridge.rs # NumPy array conversion
│ │
│ └── lib.rs # Library entry point
│
├── Cargo.toml # Rust dependencies
└── pyproject.toml # Python package config
Installation
From Pre-built Wheel
pip install raptorbt
From Source
cd raptorbt
maturin develop --release
Verify Installation
import raptorbt
print("RaptorBT installed successfully!")
Quick Start
Basic Single Instrument Backtest
import numpy as np
import pandas as pd
import raptorbt
# Prepare data
df = pd.read_csv("your_data.csv", index_col=0, parse_dates=True)
# Generate signals (SMA crossover example)
sma_fast = df['close'].rolling(10).mean()
sma_slow = df['close'].rolling(20).mean()
entries = (sma_fast > sma_slow) & (sma_fast.shift(1) <= sma_slow.shift(1))
exits = (sma_fast < sma_slow) & (sma_fast.shift(1) >= sma_slow.shift(1))
# Configure backtest
config = raptorbt.PyBacktestConfig(
initial_capital=100000,
fees=0.001, # 0.1% per trade
slippage=0.0005, # 0.05% slippage
upon_bar_close=True
)
# Optional: Add stop-loss
config.set_fixed_stop(0.02) # 2% stop-loss
# Optional: Add take-profit
config.set_fixed_target(0.04) # 4% take-profit
# Run backtest
result = raptorbt.run_single_backtest(
timestamps=df.index.astype('int64').values,
open=df['open'].values,
high=df['high'].values,
low=df['low'].values,
close=df['close'].values,
volume=df['volume'].values,
entries=entries.values,
exits=exits.values,
direction=1, # 1 = Long, -1 = Short
weight=1.0,
symbol="AAPL",
config=config,
)
# Access results
print(f"Total Return: {result.metrics.total_return_pct:.2f}%")
print(f"Sharpe Ratio: {result.metrics.sharpe_ratio:.2f}")
print(f"Max Drawdown: {result.metrics.max_drawdown_pct:.2f}%")
print(f"Win Rate: {result.metrics.win_rate_pct:.2f}%")
print(f"Total Trades: {result.metrics.total_trades}")
# Get equity curve
equity = result.equity_curve() # Returns numpy array
# Get trades
trades = result.trades() # Returns list of PyTrade objects
Strategy Types
1. Single Instrument
Basic long or short strategy on a single instrument.
# Optional: Instrument-specific configuration
inst_config = raptorbt.PyInstrumentConfig(lot_size=1.0)
result = raptorbt.run_single_backtest(
timestamps=timestamps,
open=open_prices, high=high_prices, low=low_prices,
close=close_prices, volume=volume,
entries=entries, exits=exits,
direction=1, # 1=Long, -1=Short
weight=1.0,
symbol="SYMBOL",
config=config,
instrument_config=inst_config, # Optional: lot_size rounding, capital caps
)
2. Basket/Collective
Trade multiple instruments with synchronized signals.
instruments = [
(timestamps, open1, high1, low1, close1, volume1, entries1, exits1, 1, 0.33, "AAPL"),
(timestamps, open2, high2, low2, close2, volume2, entries2, exits2, 1, 0.33, "GOOGL"),
(timestamps, open3, high3, low3, close3, volume3, entries3, exits3, 1, 0.34, "MSFT"),
]
# Optional: Per-instrument configs for lot_size and capital allocation
instrument_configs = {
"AAPL": raptorbt.PyInstrumentConfig(lot_size=1.
