$npx -y skills add agiprolabs/claude-trading-skills --skill vectorbtHigh-performance vectorized backtesting with parameter optimization, portfolio simulation, and rich performance metrics
| 1 | # Vectorized Backtesting with vectorbt |
| 2 | |
| 3 | ## Overview |
| 4 | |
| 5 | vectorbt is a Python library for **vectorized backtesting** — running strategy simulations using NumPy/pandas array operations instead of bar-by-bar loops. This makes it 100–1000x faster than event-driven frameworks (backtrader, zipline), enabling parameter optimization across thousands of combinations in seconds. |
| 6 | |
| 7 | **Key strengths:** |
| 8 | - Blazing speed via NumPy vectorization |
| 9 | - Built-in parameter grid search and optimization |
| 10 | - 50+ built-in performance metrics (Sharpe, Sortino, Calmar, max drawdown, profit factor) |
| 11 | - Rich plotting (equity curves, drawdowns, trade markers, heatmaps) |
| 12 | - Native pandas integration — your data stays in DataFrames throughout |
| 13 | |
| 14 | ## Installation |
| 15 | |
| 16 | ```bash |
| 17 | uv pip install vectorbt pandas numpy |
| 18 | ``` |
| 19 | |
| 20 | vectorbt pulls in pandas, NumPy, and Plotly automatically. For technical indicators, also install pandas-ta: |
| 21 | |
| 22 | ```bash |
| 23 | uv pip install vectorbt pandas-ta |
| 24 | ``` |
| 25 | |
| 26 | ## Core Concepts |
| 27 | |
| 28 | ### 1. Signals — Boolean Entry/Exit Arrays |
| 29 | |
| 30 | Strategies in vectorbt are expressed as boolean pandas Series (or arrays) indicating where to enter and exit positions: |
| 31 | |
| 32 | ```python |
| 33 | import vectorbt as vbt |
| 34 | import pandas as pd |
| 35 | |
| 36 | # Entry: buy when fast EMA crosses above slow EMA |
| 37 | entries = fast_ema > slow_ema |
| 38 | # Exit: sell when fast EMA crosses below slow EMA |
| 39 | exits = fast_ema < slow_ema |
| 40 | ``` |
| 41 | |
| 42 | vectorbt resolves conflicting signals automatically (you can't enter while already in a position). |
| 43 | |
| 44 | ### 2. Portfolio — The Backtesting Engine |
| 45 | |
| 46 | `vbt.Portfolio.from_signals()` is the primary backtesting function. It takes price data and entry/exit signals, simulates trades, and computes performance: |
| 47 | |
| 48 | ```python |
| 49 | pf = vbt.Portfolio.from_signals( |
| 50 | close=close_prices, |
| 51 | entries=entries, |
| 52 | exits=exits, |
| 53 | init_cash=10_000, |
| 54 | fees=0.003, # 0.3% per trade |
| 55 | slippage=0.005, # 0.5% slippage |
| 56 | freq="1h", # hourly data |
| 57 | ) |
| 58 | ``` |
| 59 | |
| 60 | ### 3. Metrics — Built-in Performance Analysis |
| 61 | |
| 62 | ```python |
| 63 | # Full stats summary |
| 64 | print(pf.stats()) |
| 65 | |
| 66 | # Individual metrics |
| 67 | print(f"Total Return: {pf.total_return():.2%}") |
| 68 | print(f"Sharpe Ratio: {pf.sharpe_ratio():.3f}") |
| 69 | print(f"Max Drawdown: {pf.max_drawdown():.2%}") |
| 70 | print(f"Win Rate: {pf.trades.win_rate():.2%}") |
| 71 | ``` |
| 72 | |
| 73 | ### 4. Parameter Optimization — Grid Search in Seconds |
| 74 | |
| 75 | Pass arrays instead of scalars to test many parameter combos simultaneously: |
| 76 | |
| 77 | ```python |
| 78 | import numpy as np |
| 79 | |
| 80 | fast_periods = np.arange(5, 25, 2) # 10 values |
| 81 | slow_periods = np.arange(20, 60, 5) # 8 values |
| 82 | |
| 83 | fast_ma = vbt.MA.run(close, fast_periods, short_name="fast") |
| 84 | slow_ma = vbt.MA.run(close, slow_periods, short_name="slow") |
| 85 | |
| 86 | # This creates 80 parameter combinations automatically |
| 87 | entries = fast_ma.ma_crossed_above(slow_ma) |
| 88 | exits = fast_ma.ma_crossed_below(slow_ma) |
| 89 | ``` |
| 90 | |
| 91 | ## Basic Workflow |
| 92 | |
| 93 | ### Step 1: Load OHLCV Data |
| 94 | |
| 95 | ```python |
| 96 | import pandas as pd |
| 97 | |
| 98 | # From CSV |
| 99 | df = pd.read_csv("ohlcv.csv", parse_dates=["timestamp"], index_col="timestamp") |
| 100 | close = df["close"] |
| 101 | |
| 102 | # From Yahoo Finance (traditional markets) |
| 103 | btc = vbt.YFData.download("BTC-USD", start="2023-01-01", end="2025-01-01") |
| 104 | close = btc.get("Close") |
| 105 | ``` |
| 106 | |
| 107 | For Solana tokens, fetch data via the `birdeye-api` skill and load into a DataFrame. |
| 108 | |
| 109 | ### Step 2: Compute Indicators |
| 110 | |
| 111 | ```python |
| 112 | import pandas_ta as ta |
| 113 | |
| 114 | # Using pandas-ta (see pandas-ta skill) |
| 115 | df.ta.ema(length=12, append=True) |
| 116 | df.ta.ema(length=26, append=True) |
| 117 | df.ta.rsi(length=14, append=True) |
| 118 | df.ta.bbands(length=20, std=2, append=True) |
| 119 | |
| 120 | # Or using vectorbt built-ins |
| 121 | rsi = vbt.RSI.run(close, window=14) |
| 122 | bbands = vbt.BBANDS.run(close, window=20, alpha=2) |
| 123 | ``` |
| 124 | |
| 125 | ### Step 3: Generate Entry/Exit Signals |
| 126 | |
| 127 | ```python |
| 128 | # EMA crossover |
| 129 | entries = df["EMA_12"] > df["EMA_26"] |
| 130 | exits = df["EMA_12"] < df["EMA_26"] |
| 131 | |
| 132 | # RSI mean reversion |
| 133 | entries = rsi.rsi_below(30) |
| 134 | exits = rsi.rsi_above(70) |
| 135 | ``` |
| 136 | |
| 137 | ### Step 4: Run Backtest |
| 138 | |
| 139 | ```python |
| 140 | pf = vbt.Portfolio.from_signals( |
| 141 | close=close, |
| 142 | entries=entries, |
| 143 | exits=exits, |
| 144 | init_cash=10_000, |
| 145 | fees=0.003, |
| 146 | slippage=0.005, |
| 147 | size=0.95, # use 95% of available cash |
| 148 | size_type="percent", |
| 149 | freq="1h", |
| 150 | ) |
| 151 | ``` |
| 152 | |
| 153 | ### Step 5: Analyze Results |
| 154 | |
| 155 | ```python |
| 156 | # Summary statistics |
| 157 | print(pf.stats()) |
| 158 | |
| 159 | # Trade-level analysis |
| 160 | trades = pf.trades.records_readable |
| 161 | print(f"\nTrade count: {len(trades)}") |
| 162 | print(f"Avg holding period: {trades['Duration'].mean()}") |
| 163 | |
| 164 | # Equity curve |
| 165 | pf.plot().show() |
| 166 | |
| 167 | # Drawdown chart |
| 168 | pf.drawdowns.plot().show() |
| 169 | ``` |
| 170 | |
| 171 | ## Key Portfolio Parameters |
| 172 | |
| 173 | | Parameter | Description | Example | |
| 174 | |-----------|-------------|---------| |
| 175 | | `close` | Price series (pd.Series or DataFrame) | `df["close"]` | |
| 176 | | `entries` | Boolean entry signals | `fast > slow` | |
| 177 | | `exits` | Boolean exit signals | `fast < slow` | |
| 178 | | `init_cash` | Starting capital | `10_000` | |
| 179 | | `fees` | Fee per trade (fraction) | `0.003` (0.3%) | |
| 180 | | `slippage` | Slippage per trade (fraction) | `0.005` (0.5%) | |
| 181 | | `size` | Position size | `0.95` | |
| 182 | | `size_ |