vectorbtで高速バックテスト(yfinance連携)完全ガイド

Python実装・コード

vectorbtはNumPyベースの超高速バックテストライブラリです。Backtraderより数百倍速く、数万パターンの最適化を数秒で実行できます。この記事ではyfinanceと組み合わせた使い方を解説します。

インストール

pip install vectorbt yfinance

vectorbtの基本

import vectorbt as vbt
import numpy as np
import pandas as pd

# yfinanceからデータ取得
price = vbt.YFData.download("7203.T", period="3y").get("Close")

# 移動平均クロス戦略(2行で実装!)
fast_ma = vbt.MA.run(price, 25)
slow_ma = vbt.MA.run(price, 75)

# エントリー・エグジットシグナル
entries = fast_ma.ma_crossed_above(slow_ma)  # ゴールデンクロス
exits = fast_ma.ma_crossed_below(slow_ma)    # デッドクロス

# ポートフォリオシミュレーション
pf = vbt.Portfolio.from_signals(
    price, entries, exits,
    init_cash=1_000_000,
    fees=0.001,  # 手数料0.1%
    freq="D"
)

print(pf.stats())

結果の詳細分析

# 主要指標の一覧
stats = pf.stats()
print("\n=== パフォーマンス統計 ===")
print(stats)

# 個別指標の取得
print(f"\n総リターン: {pf.total_return():.1%}")
print(f"年率リターン: {pf.annualized_return():.1%}")
print(f"シャープレシオ: {pf.sharpe_ratio():.2f}")
print(f"ソルティノレシオ: {pf.sortino_ratio():.2f}")
print(f"最大ドローダウン: {pf.max_drawdown():.1%}")
print(f"取引回数: {pf.trades.count()}")
print(f"勝率: {pf.trades.win_rate():.1%}")
print(f"期待値: {pf.trades.expectancy():.2f}")

# 可視化
pf.plot().show()

超高速パラメーター最適化

# 数百パターンを一括処理(vectorbtの真骨頂)
fast_windows = np.arange(5, 50, 5)   # 5,10,15...45
slow_windows = np.arange(20, 200, 10) # 20,30,40...190

fast_ma = vbt.MA.run(price, fast_windows, short_name="fast")
slow_ma = vbt.MA.run(price, 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(
    price, entries, exits,
    init_cash=1_000_000,
    fees=0.001,
    freq="D"
)

# シャープレシオで並び替え
sharpe = pf.sharpe_ratio()
best = sharpe.stack().nlargest(10)
print("シャープレシオTop10:")
print(best.round(2))

# ヒートマップで可視化
sharpe.vbt.heatmap(
    x_level="fast_window",
    y_level="slow_window",
    symmetric=True,
    title="移動平均クロス シャープレシオ ヒートマップ"
).show()

複数銘柄の同時バックテスト

# 複数銘柄を一括処理
tickers = ["7203.T", "9984.T", "6758.T", "AAPL", "NVDA"]
data = vbt.YFData.download(tickers, period="2y")
close = data.get("Close")

# 各銘柄に同じ戦略を適用
fast = vbt.MA.run(close, 25)
slow = vbt.MA.run(close, 75)

entries = fast.ma_crossed_above(slow)
exits = fast.ma_crossed_below(slow)

pf = vbt.Portfolio.from_signals(
    close, entries, exits,
    init_cash=100_000,
    fees=0.001,
    freq="D"
)

# 銘柄別パフォーマンス
results = pd.DataFrame({
    "総リターン": pf.total_return(),
    "シャープ": pf.sharpe_ratio(),
    "最大DD": pf.max_drawdown(),
    "取引回数": pf.trades.count(),
    "勝率": pf.trades.win_rate(),
}).round(3)
print(results)

RSI戦略の実装

# RSI戦略をvectorbtで実装
price = vbt.YFData.download("7203.T", period="3y").get("Close")
rsi = vbt.RSI.run(price, window=14)

# 売られすぎ(30以下)で買い、買われすぎ(70以上)で売り
entries = rsi.rsi_crossed_below(30)   # RSIが30を下回る
exits = rsi.rsi_crossed_above(70)     # RSIが70を上回る

pf_rsi = vbt.Portfolio.from_signals(
    price, entries, exits,
    init_cash=1_000_000,
    fees=0.001,
    freq="D"
)

print("=== RSI戦略 ===")
print(f"総リターン: {pf_rsi.total_return():.1%}")
print(f"シャープレシオ: {pf_rsi.sharpe_ratio():.2f}")
print(f"取引回数: {pf_rsi.trades.count()}")

Backtraderとの速度比較

同じMA Cross戦略で1000パターンを最適化した場合の実行時間の目安:

  • Backtrader(optstrategy):約180秒
  • vectorbt:約1.5秒

vectorbtはNumPy配列で全計算をベクトル化しているため、ループ処理のBacktraderより圧倒的に高速です。

まとめ

vectorbtはシンプルなAPIと超高速処理が特徴で、大規模なパラメーター最適化に最適です。yfinanceとの連携も簡単で、数行のコードで本格的なバックテストが実行できます。

タイトルとURLをコピーしました