vectorbt
vectorbtは、高度なベクトル化バックテストで、パラメータ最適化やポートフォリオシミュレーションを行い、豊富なパフォーマンス指標を用いて投資戦略を効率的に分析・改善するSkill。
📜 元の英語説明(参考)
High-performance vectorized backtesting with parameter optimization, portfolio simulation, and rich performance metrics
🇯🇵 日本人クリエイター向け解説
vectorbtは、高度なベクトル化バックテストで、パラメータ最適化やポートフォリオシミュレーションを行い、豊富なパフォーマンス指標を用いて投資戦略を効率的に分析・改善するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o vectorbt.zip https://jpskill.com/download/10450.zip && unzip -o vectorbt.zip && rm vectorbt.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10450.zip -OutFile "$d\vectorbt.zip"; Expand-Archive "$d\vectorbt.zip" -DestinationPath $d -Force; ri "$d\vectorbt.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
vectorbt.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
vectorbtフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Vectorized Backtesting with vectorbt
概要
vectorbt は、ベクトル化されたバックテスティングのための Python ライブラリです。これは、バーごとのループの代わりに NumPy/pandas の配列演算を使用して戦略シミュレーションを実行します。これにより、イベント駆動型フレームワーク (backtrader, zipline) よりも 100〜1000 倍高速になり、数千の組み合わせにわたるパラメータ最適化を数秒で実現できます。
主な強み:
- NumPy のベクトル化による驚異的なスピード
- 組み込みのパラメータグリッドサーチと最適化
- 50 以上の組み込みパフォーマンス指標 (シャープレシオ、ソルティノレシオ、カルマーレシオ、最大ドローダウン、プロフィットファクター)
- 豊富なプロット機能 (エクイティカーブ、ドローダウン、トレードマーカー、ヒートマップ)
- ネイティブな pandas 統合 — データは常に DataFrame に保持されます
インストール
uv pip install vectorbt pandas numpy
vectorbt は pandas、NumPy、Plotly を自動的にインストールします。テクニカル指標については、pandas-ta もインストールしてください。
uv pip install vectorbt pandas-ta
コアコンセプト
1. シグナル — ブール値のエントリー/イグジット配列
vectorbt の戦略は、ポジションのエントリーとイグジットを示すブール値の pandas Series (または配列) として表現されます。
import vectorbt as vbt
import pandas as pd
# エントリー: 高速 EMA が低速 EMA を上回ったときに買い
entries = fast_ema > slow_ema
# イグジット: 高速 EMA が低速 EMA を下回ったときに売り
exits = fast_ema < slow_ema
vectorbt は競合するシグナルを自動的に解決します (すでにポジションを持っている間はエントリーできません)。
2. ポートフォリオ — バックテスティングエンジン
vbt.Portfolio.from_signals() は、主要なバックテスティング関数です。価格データとエントリー/イグジットシグナルを受け取り、トレードをシミュレートし、パフォーマンスを計算します。
pf = vbt.Portfolio.from_signals(
close=close_prices,
entries=entries,
exits=exits,
init_cash=10_000,
fees=0.003, # 1トレードあたり 0.3%
slippage=0.005, # 0.5% のスリッページ
freq="1h", # 1時間ごとのデータ
)
3. メトリクス — 組み込みのパフォーマンス分析
# 完全な統計サマリー
print(pf.stats())
# 個別のメトリクス
print(f"Total Return: {pf.total_return():.2%}")
print(f"Sharpe Ratio: {pf.sharpe_ratio():.3f}")
print(f"Max Drawdown: {pf.max_drawdown():.2%}")
print(f"Win Rate: {pf.trades.win_rate():.2%}")
4. パラメータ最適化 — グリッドサーチを数秒で
スカラーの代わりに配列を渡して、多くのパラメータの組み合わせを同時にテストします。
import numpy as np
fast_periods = np.arange(5, 25, 2) # 10 個の値
slow_periods = np.arange(20, 60, 5) # 8 個の値
fast_ma = vbt.MA.run(close, fast_periods, short_name="fast")
slow_ma = vbt.MA.run(close, slow_periods, short_name="slow")
# これにより、80 個のパラメータの組み合わせが自動的に作成されます
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
基本的なワークフロー
ステップ 1: OHLCV データのロード
import pandas as pd
# CSV から
df = pd.read_csv("ohlcv.csv", parse_dates=["timestamp"], index_col="timestamp")
close = df["close"]
# Yahoo Finance から (従来の市場)
btc = vbt.YFData.download("BTC-USD", start="2023-01-01", end="2025-01-01")
close = btc.get("Close")
Solana トークンの場合は、birdeye-api skill を介してデータを取得し、DataFrame にロードします。
ステップ 2: インジケーターの計算
import pandas_ta as ta
# pandas-ta を使用 (pandas-ta skill を参照)
df.ta.ema(length=12, append=True)
df.ta.ema(length=26, append=True)
df.ta.rsi(length=14, append=True)
df.ta.bbands(length=20, std=2, append=True)
# または vectorbt の組み込み機能を使用
rsi = vbt.RSI.run(close, window=14)
bbands = vbt.BBANDS.run(close, window=20, alpha=2)
ステップ 3: エントリー/イグジットシグナルの生成
# EMA クロスオーバー
entries = df["EMA_12"] > df["EMA_26"]
exits = df["EMA_12"] < df["EMA_26"]
# RSI ミーンリバージョン
entries = rsi.rsi_below(30)
exits = rsi.rsi_above(70)
ステップ 4: バックテストの実行
pf = vbt.Portfolio.from_signals(
close=close,
entries=entries,
exits=exits,
init_cash=10_000,
fees=0.003,
slippage=0.005,
size=0.95, # 利用可能な現金の 95% を使用
size_type="percent",
freq="1h",
)
ステップ 5: 結果の分析
# 統計サマリー
print(pf.stats())
# トレードレベルの分析
trades = pf.trades.records_readable
print(f"\nTrade count: {len(trades)}")
print(f"Avg holding period: {trades['Duration'].mean()}")
# エクイティカーブ
pf.plot().show()
# ドローダウンチャート
pf.drawdowns.plot().show()
主要なポートフォリオパラメータ
| パラメータ | 説明 | 例 |
|---|---|---|
close |
価格系列 (pd.Series または DataFrame) | df["close"] |
entries |
ブール値のエントリーシグナル | fast > slow |
exits |
ブール値のイグジットシグナル | fast < slow |
init_cash |
開始資本 | 10_000 |
fees |
1 トレードあたりの手数料 (割合) | 0.003 (0.3%) |
slippage |
1 トレードあたりのスリッページ (割合) | 0.005 (0.5%) |
size |
ポジションサイズ | 0.95 |
size_type |
サイズの解釈方法 | "percent", "amount", "value" |
freq |
データ頻度 | "1h", "4h", "1d" |
direction |
トレード方向 | "both", "longonly", "shortonly" |
accumulate |
ポジションへの追加を許可するかどうか | False |
sl_stop |
ストップロスレベル (割合) | 0.05 (5%) |
tp_stop |
テイクプロフィットレベル (割合) | 0.10 (10%) |
パフォーマンス指標
リターン
total_return()— 期間中の累積リターンannualized_return()— 年間換算の複利リターンdaily_returns()— 日々のリターンの Series
リスク
max_drawdown()— 最大のピークからトラフへの下落annualized_volatility()— 年間換算のリターンの標準偏差value_at_risk()— 指定された信頼水準での VaR
リスク調整後
sharpe_ratio()— 単位ボラティリティあたりの超過リターンsortino_ratio()— 単位下方偏差あたりの超過リターンcalmar_ratio()— 年間換算リターン / 最大ドローダウンomega_ratio()— 確率で重み付けされた損益比率
トレード統計
trades.win_rate()— 収益性の高いトレードの割合trades.profit_factor()— 総利益 / 総損失trades.expectancy()— ave
(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Vectorized Backtesting with vectorbt
Overview
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.
Key strengths:
- Blazing speed via NumPy vectorization
- Built-in parameter grid search and optimization
- 50+ built-in performance metrics (Sharpe, Sortino, Calmar, max drawdown, profit factor)
- Rich plotting (equity curves, drawdowns, trade markers, heatmaps)
- Native pandas integration — your data stays in DataFrames throughout
Installation
uv pip install vectorbt pandas numpy
vectorbt pulls in pandas, NumPy, and Plotly automatically. For technical indicators, also install pandas-ta:
uv pip install vectorbt pandas-ta
Core Concepts
1. Signals — Boolean Entry/Exit Arrays
Strategies in vectorbt are expressed as boolean pandas Series (or arrays) indicating where to enter and exit positions:
import vectorbt as vbt
import pandas as pd
# Entry: buy when fast EMA crosses above slow EMA
entries = fast_ema > slow_ema
# Exit: sell when fast EMA crosses below slow EMA
exits = fast_ema < slow_ema
vectorbt resolves conflicting signals automatically (you can't enter while already in a position).
2. Portfolio — The Backtesting Engine
vbt.Portfolio.from_signals() is the primary backtesting function. It takes price data and entry/exit signals, simulates trades, and computes performance:
pf = vbt.Portfolio.from_signals(
close=close_prices,
entries=entries,
exits=exits,
init_cash=10_000,
fees=0.003, # 0.3% per trade
slippage=0.005, # 0.5% slippage
freq="1h", # hourly data
)
3. Metrics — Built-in Performance Analysis
# Full stats summary
print(pf.stats())
# Individual metrics
print(f"Total Return: {pf.total_return():.2%}")
print(f"Sharpe Ratio: {pf.sharpe_ratio():.3f}")
print(f"Max Drawdown: {pf.max_drawdown():.2%}")
print(f"Win Rate: {pf.trades.win_rate():.2%}")
4. Parameter Optimization — Grid Search in Seconds
Pass arrays instead of scalars to test many parameter combos simultaneously:
import numpy as np
fast_periods = np.arange(5, 25, 2) # 10 values
slow_periods = np.arange(20, 60, 5) # 8 values
fast_ma = vbt.MA.run(close, fast_periods, short_name="fast")
slow_ma = vbt.MA.run(close, slow_periods, short_name="slow")
# This creates 80 parameter combinations automatically
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
Basic Workflow
Step 1: Load OHLCV Data
import pandas as pd
# From CSV
df = pd.read_csv("ohlcv.csv", parse_dates=["timestamp"], index_col="timestamp")
close = df["close"]
# From Yahoo Finance (traditional markets)
btc = vbt.YFData.download("BTC-USD", start="2023-01-01", end="2025-01-01")
close = btc.get("Close")
For Solana tokens, fetch data via the birdeye-api skill and load into a DataFrame.
Step 2: Compute Indicators
import pandas_ta as ta
# Using pandas-ta (see pandas-ta skill)
df.ta.ema(length=12, append=True)
df.ta.ema(length=26, append=True)
df.ta.rsi(length=14, append=True)
df.ta.bbands(length=20, std=2, append=True)
# Or using vectorbt built-ins
rsi = vbt.RSI.run(close, window=14)
bbands = vbt.BBANDS.run(close, window=20, alpha=2)
Step 3: Generate Entry/Exit Signals
# EMA crossover
entries = df["EMA_12"] > df["EMA_26"]
exits = df["EMA_12"] < df["EMA_26"]
# RSI mean reversion
entries = rsi.rsi_below(30)
exits = rsi.rsi_above(70)
Step 4: Run Backtest
pf = vbt.Portfolio.from_signals(
close=close,
entries=entries,
exits=exits,
init_cash=10_000,
fees=0.003,
slippage=0.005,
size=0.95, # use 95% of available cash
size_type="percent",
freq="1h",
)
Step 5: Analyze Results
# Summary statistics
print(pf.stats())
# Trade-level analysis
trades = pf.trades.records_readable
print(f"\nTrade count: {len(trades)}")
print(f"Avg holding period: {trades['Duration'].mean()}")
# Equity curve
pf.plot().show()
# Drawdown chart
pf.drawdowns.plot().show()
Key Portfolio Parameters
| Parameter | Description | Example |
|---|---|---|
close |
Price series (pd.Series or DataFrame) | df["close"] |
entries |
Boolean entry signals | fast > slow |
exits |
Boolean exit signals | fast < slow |
init_cash |
Starting capital | 10_000 |
fees |
Fee per trade (fraction) | 0.003 (0.3%) |
slippage |
Slippage per trade (fraction) | 0.005 (0.5%) |
size |
Position size | 0.95 |
size_type |
How to interpret size | "percent", "amount", "value" |
freq |
Data frequency | "1h", "4h", "1d" |
direction |
Trade direction | "both", "longonly", "shortonly" |
accumulate |
Allow adding to positions | False |
sl_stop |
Stop-loss level (fraction) | 0.05 (5%) |
tp_stop |
Take-profit level (fraction) | 0.10 (10%) |
Performance Metrics
Returns
total_return()— cumulative return over the periodannualized_return()— annualized compound returndaily_returns()— Series of daily returns
Risk
max_drawdown()— maximum peak-to-trough declineannualized_volatility()— annualized standard deviation of returnsvalue_at_risk()— VaR at specified confidence level
Risk-Adjusted
sharpe_ratio()— excess return per unit volatilitysortino_ratio()— excess return per unit downside deviationcalmar_ratio()— annualized return / max drawdownomega_ratio()— probability-weighted gain/loss ratio
Trade Statistics
trades.win_rate()— fraction of profitable tradestrades.profit_factor()— gross profit / gross losstrades.expectancy()— average P&L per tradetrades.avg_winning_trade()— mean profit on winnerstrades.avg_losing_trade()— mean loss on loserstrades.count()— total number of completed trades
Parameter Optimization
Grid Search
fast_windows = [5, 8, 12, 15, 20]
slow_windows = [20, 26, 30, 40, 50]
# Run all 25 combos at once
fast_ma = vbt.MA.run(close, fast_windows, short_name="fast")
slow_ma = vbt.MA.run(close, slow_windows, short_name="slow")
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.003)
# Find best params by Sharpe
sharpe = pf.sharpe_ratio()
best_idx = sharpe.idxmax()
print(f"Best params: {best_idx}, Sharpe: {sharpe[best_idx]:.3f}")
Walk-Forward Validation
Always validate optimized parameters on out-of-sample data:
# Split: 70% train, 30% test
split_idx = int(len(close) * 0.7)
train_close = close.iloc[:split_idx]
test_close = close.iloc[split_idx:]
# Optimize on training data
# ... (run grid search on train_close)
# Validate best params on test data
# ... (run single backtest on test_close with best params)
See references/optimization_guide.md for detailed walk-forward methodology and overfitting prevention.
Crypto-Specific Considerations
24/7 Markets
Crypto markets never close. Use hourly or minute-based frequencies, not business-day frequencies:
# Correct for crypto
pf = vbt.Portfolio.from_signals(close, entries, exits, freq="1h")
# Wrong — business days assume market closures
# pf = vbt.Portfolio.from_signals(close, entries, exits, freq="1B")
Realistic Fees
DEX swaps on Solana typically cost 0.25–1% including AMM fees. CEX spot fees are 0.05–0.1%.
# Solana DEX (conservative)
pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.005)
# CEX spot
pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.001)
Slippage
Low-liquidity tokens can have 1–5% slippage. Always model this:
# High-liquidity (SOL, ETH): 0.1–0.5%
pf = vbt.Portfolio.from_signals(close, entries, exits, slippage=0.003)
# Low-liquidity memecoins: 1–3%
pf = vbt.Portfolio.from_signals(close, entries, exits, slippage=0.02)
Short History
Many tokens have less than 1 year of data. Be cautious about annualizing metrics from short samples.
Common Strategy Patterns
EMA Crossover
fast = vbt.MA.run(close, 12, short_name="fast")
slow = vbt.MA.run(close, 26, short_name="slow")
entries = fast.ma_crossed_above(slow)
exits = fast.ma_crossed_below(slow)
RSI Mean Reversion
rsi = vbt.RSI.run(close, 14)
entries = rsi.rsi_crossed_below(30)
exits = rsi.rsi_crossed_above(70)
Bollinger Band Breakout
bb = vbt.BBANDS.run(close, window=20, alpha=2)
entries = close > bb.upper
exits = close < bb.lower
Stop-Loss and Take-Profit
pf = vbt.Portfolio.from_signals(
close, entries, exits,
sl_stop=0.05, # 5% stop-loss
tp_stop=0.10, # 10% take-profit
)
Related Skills
- pandas-ta — Technical indicator computation (feeds vectorbt signals)
- birdeye-api — Fetch Solana token OHLCV data for backtesting
- trading-visualization — Advanced chart generation for backtest results
- portfolio-analytics — Deeper portfolio-level risk/return analysis
- position-sizing — Optimal position sizing methodology
- risk-management — Portfolio-level risk guardrails
- regime-detection — Market regime awareness for adaptive strategies
Files
References
references/api_guide.md— Complete vectorbt API reference for Portfolio, indicators, plotting, and data loadingreferences/optimization_guide.md— Grid search, walk-forward validation, overfitting prevention, and optimization best practices
Scripts
scripts/backtest_example.py— Three-strategy backtest comparison using synthetic data (EMA crossover, RSI mean reversion, Bollinger breakout)scripts/parameter_sweep.py— EMA crossover parameter grid search with walk-forward validation