jpskill.com
🛠️ 開発・MCP コミュニティ

walk-forward-validation

時系列データを考慮した分割方法で、取引戦略や機械学習モデルの性能を検証し、過学習の検出や相場状況に応じた評価を行うことで、より信頼性の高いモデル構築を支援するSkill。

📜 元の英語説明(参考)

Walk-forward validation framework for trading strategies and ML models with time-series-aware splits, overfit detection, and regime-aware validation

🇯🇵 日本人クリエイター向け解説

一言でいうと

時系列データを考慮した分割方法で、取引戦略や機械学習モデルの性能を検証し、過学習の検出や相場状況に応じた評価を行うことで、より信頼性の高いモデル構築を支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o walk-forward-validation.zip https://jpskill.com/download/10452.zip && unzip -o walk-forward-validation.zip && rm walk-forward-validation.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10452.zip -OutFile "$d\walk-forward-validation.zip"; Expand-Archive "$d\walk-forward-validation.zip" -DestinationPath $d -Force; ri "$d\walk-forward-validation.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して walk-forward-validation.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → walk-forward-validation フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

ウォークフォワード検証

取引戦略と ML モデルのためのウォークフォワード検証フレームワークです。標準的な交差検証 (k 分割、ランダム分割) は、ルックアヘッドバイアスを導入し、自己相関を無視するため、金融時系列に対しては壊滅的な失敗を招きます。このスキルでは、ローリングおよび拡張ウィンドウ、パージされた交差検証、組み合わせパージされた交差検証 (CPCV)、および過学習検出メトリクスを含む、適切な時系列検証手法について説明します。

標準的な交差検証が失敗する理由

標準的な k 分割 CV は、データポイントが独立同分布 (IID) であることを前提としています。金融時系列は、次の両方の前提に違反します。

  1. ルックアヘッドバイアス — ランダムな分割により、モデルは将来のデータで学習し、過去のデータを予測できるようになり、パフォーマンスを人為的に向上させます。
  2. 自己相関 — 隣接する観測値は相関しています。月曜日をテストに、火曜日をトレーニングに配置するランダムな分割は、情報をリークします。
  3. レジーム依存性 — 市場はレジーム間を移行します。強気市場でトレーニングされ、強気市場でテストされたモデルは、弱気市場のパフォーマンスについては何も教えてくれません。
  4. ラベルの重複 — ラベルがウィンドウ (例: 24 時間先の収益) で計算される場合、隣接するトレーニング/テストサンプルはラベル計算期間を共有し、情報をリークします。

ウォークフォワードフレームワーク

ローリングウィンドウ (固定トレーニングサイズ)

トレーニングウィンドウは固定サイズを持ち、時間とともに前方にスライドします。これは、古いデータが関連性が低いと思われる場合に推奨されます (暗号通貨では一般的です)。

Window 1: [===TRAIN===][=TEST=]
Window 2:    [===TRAIN===][=TEST=]
Window 3:       [===TRAIN===][=TEST=]

パラメータ:

  • train_size: トレーニングウィンドウ内のバー/日 の数
  • test_size: テストウィンドウ内のバー/日 の数
  • step_size: フォールド間で進む距離 (多くの場合 test_size と等しい)

拡張ウィンドウ (成長するトレーニング)

トレーニングウィンドウは最初から始まり、前方に拡張されます。これにより、利用可能なすべての履歴データが使用されるため、データが不足している場合に役立ちます。

Window 1: [==TRAIN==][=TEST=]
Window 2: [====TRAIN====][=TEST=]
Window 3: [======TRAIN======][=TEST=]

パラメータ:

  • min_train_size: 最初のフォールドの前の最小トレーニングサンプル数
  • test_size: 固定テストウィンドウサイズ
  • step_size: フォールド間で進む距離

それらの間の選択

ファクター ローリング 拡張
データの最新性 最新のデータを優先 すべての履歴を使用
レジームの変化 新しいレジームへの適応が優れている 最近のレジームを希釈する可能性がある
サンプルサイズ 固定、小さい可能性がある 時間とともに増加
暗号通貨の好み 6 か月未満の期間に推奨 レジームが安定したモデルに適している

パージとエンバーゴ

パージ

ラベルがテストセットの時間範囲と重複するトレーニングサンプルを削除します。ラベルが時刻 t から始まる 24 時間先の収益として計算される場合、t + 24h がテスト期間に拡張されるトレーニングサンプルはすべてパージする必要があります。

def purge_train_indices(
    train_idx: list[int],
    test_start: int,
    label_horizon: int,
    timestamps: list[int],
) -> list[int]:
    """Remove train samples whose label windows overlap test period."""
    test_start_time = timestamps[test_start]
    return [
        i for i in train_idx
        if timestamps[i] + label_horizon < test_start_time
    ]

エンバーゴ

パージだけでは排除できない系列相関を考慮するために、トレーニングの終了とテストの開始の間にバッファギャップを追加します。

[===TRAIN===][--EMBARGO--][=TEST=]

一般的なエンバーゴサイズ:

  • 1 分足: 60–240 バー (1–4 時間)
  • 5 分足: 12–48 バー (1–4 時間)
  • 時間足: 6–24 バー (6–24 時間)
  • 日足: 2–5 バー (2–5 日)
  • 暗号通貨の経験則: エンバーゴ >= ラベル計算期間の 2 倍

組み合わせパージされた交差検証 (CPCV)

CPCV (Lopez de Prado, 2018) は、時間的順序を維持しながら、N グループから可能なすべてのトレーニング/テストの組み合わせを生成します。これにより、標準的なウォークフォワードよりもはるかに多くのテストパスが生成され、過学習の統計的テストが可能になります。

主なプロパティ:

  • データを N 個の連続したグループに分割します
  • k 個のテストグループの各組み合わせについて、残りの N-k グループがトレーニングセットを形成します
  • 各トレーニング/テスト境界でパージとエンバーゴを適用します
  • C(N, k) 個のバックテストパスを生成します (例: N=6、k=2 は 15 個のパスを与えます)

完全な CPCV アルゴリズムと数式については、references/methodology.md を参照してください。

過学習検出

デフレートされたシャープレシオ (DSR)

観測されたシャープレシオは、次の要因について調整する必要があります。

  • テストされた戦略の数 (多重検定)
  • 収益の非正規性 (歪度、尖度)
  • バックテストの長さ
import numpy as np
from scipy.stats import norm

def deflated_sharpe_ratio(
    observed_sr: float,
    num_trials: int,
    backtest_length: int,
    skewness: float = 0.0,
    kurtosis: float = 3.0,
) -> float:
    """Compute the probability that observed SR > 0 after deflation.

    Args:
        observed_sr: Annualized Sharpe ratio of the selected strategy.
        num_trials: Number of strategies tested (including discarded ones).
        backtest_length: Number of return observations.
        skewness: Skewness of returns.
        kurtosis: Excess kurtosis of returns.

    Returns:
        p-value (probability SR is genuinely > 0).
    """
    sr_std = np.sqrt(
        (1 - skewness * observed_sr + (kurtosis - 1) / 4 * observed_sr**2)
        / (backtest_length - 1)
    )
    # Expected max SR under null (Euler-Mascheroni approximation)
    euler_mascheroni = 0.5772156649
    expected_max_sr = norm.ppf(1 - 1 / num_trials) * (
        1 - euler_mascheroni
    ) + euler_mascheroni * norm.ppf(1 - 1 / (num_trials * np.e))
    dsr = norm.cdf((observed_sr - expected_max_sr) / sr_std)
    return dsr

DSR が 0.95 未満の場合、観測されたパフォーマンスは、テストされた試行全体での過学習によるものである可能性が高いことを示唆しています。

バックテスト過学習の確率 (PBO)

PBO は CPCV を使用して、サンプル内の最適な戦略がサンプル外の中央値を下回るバックテストパスの割合を測定します。PBO が上記の場合

(原文はここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Walk-Forward Validation

Walk-forward validation framework for trading strategies and ML models. Standard cross-validation (k-fold, random splits) fails catastrophically for financial time series because it introduces lookahead bias and ignores autocorrelation. This skill covers proper time-series validation techniques including rolling and expanding windows, purged cross-validation, combinatorial purged cross-validation (CPCV), and overfit detection metrics.

Why Standard Cross-Validation Fails

Standard k-fold CV assumes data points are independent and identically distributed (IID). Financial time series violate both assumptions:

  1. Lookahead bias — Random splits let the model train on future data and predict past data, artificially inflating performance.
  2. Autocorrelation — Adjacent observations are correlated. A random split that puts Monday in test and Tuesday in train leaks information.
  3. Regime dependence — Markets shift between regimes. A model trained on a bull market and tested on a bull market tells you nothing about bear market performance.
  4. Label overlap — If labels are computed over windows (e.g., 24h forward return), adjacent train/test samples share label computation periods, leaking information.

Walk-Forward Framework

Rolling Window (Fixed Train Size)

The train window has a fixed size and slides forward in time. This is preferred when you believe older data is less relevant (common in crypto).

Window 1: [===TRAIN===][=TEST=]
Window 2:    [===TRAIN===][=TEST=]
Window 3:       [===TRAIN===][=TEST=]

Parameters:

  • train_size: Number of bars/days in the training window
  • test_size: Number of bars/days in the test window
  • step_size: How far to advance between folds (often equals test_size)

Expanding Window (Growing Train)

The train window starts at the beginning and expands forward. This uses all available historical data, which helps when data is scarce.

Window 1: [==TRAIN==][=TEST=]
Window 2: [====TRAIN====][=TEST=]
Window 3: [======TRAIN======][=TEST=]

Parameters:

  • min_train_size: Minimum training samples before first fold
  • test_size: Fixed test window size
  • step_size: How far to advance between folds

Choosing Between Them

Factor Rolling Expanding
Data recency Prioritizes recent data Uses all history
Regime changes Better adapts to new regimes May dilute recent regime
Sample size Fixed, may be small Grows over time
Crypto preference Preferred for < 6mo horizons Better for regime-stable models

Purging and Embargo

Purging

Remove training samples whose labels overlap with the test set's time range. If a label is computed as the 24h forward return starting at time t, any training sample where t + 24h extends into the test period must be purged.

def purge_train_indices(
    train_idx: list[int],
    test_start: int,
    label_horizon: int,
    timestamps: list[int],
) -> list[int]:
    """Remove train samples whose label windows overlap test period."""
    test_start_time = timestamps[test_start]
    return [
        i for i in train_idx
        if timestamps[i] + label_horizon < test_start_time
    ]

Embargo

Add a buffer gap between the end of training and start of testing to account for serial correlation that purging alone does not eliminate.

[===TRAIN===][--EMBARGO--][=TEST=]

Typical embargo sizes:

  • 1-minute bars: 60–240 bars (1–4 hours)
  • 5-minute bars: 12–48 bars (1–4 hours)
  • Hourly bars: 6–24 bars (6–24 hours)
  • Daily bars: 2–5 bars (2–5 days)
  • Crypto rule of thumb: Embargo >= 2x the label computation horizon

Combinatorial Purged Cross-Validation (CPCV)

CPCV (Lopez de Prado, 2018) generates all possible train/test combinations from N groups while maintaining temporal ordering. This produces far more test paths than standard walk-forward, enabling statistical tests for overfitting.

Key properties:

  • Splits data into N contiguous groups
  • For each combination of k test groups, the remaining N-k groups form the training set
  • Applies purging and embargo at each train/test boundary
  • Produces C(N, k) backtest paths (e.g., N=6, k=2 gives 15 paths)

See references/methodology.md for the full CPCV algorithm and formulas.

Overfit Detection

Deflated Sharpe Ratio (DSR)

The observed Sharpe ratio must be adjusted for:

  • Number of strategies tested (multiple testing)
  • Non-normality of returns (skewness, kurtosis)
  • Length of the backtest
import numpy as np
from scipy.stats import norm

def deflated_sharpe_ratio(
    observed_sr: float,
    num_trials: int,
    backtest_length: int,
    skewness: float = 0.0,
    kurtosis: float = 3.0,
) -> float:
    """Compute the probability that observed SR > 0 after deflation.

    Args:
        observed_sr: Annualized Sharpe ratio of the selected strategy.
        num_trials: Number of strategies tested (including discarded ones).
        backtest_length: Number of return observations.
        skewness: Skewness of returns.
        kurtosis: Excess kurtosis of returns.

    Returns:
        p-value (probability SR is genuinely > 0).
    """
    sr_std = np.sqrt(
        (1 - skewness * observed_sr + (kurtosis - 1) / 4 * observed_sr**2)
        / (backtest_length - 1)
    )
    # Expected max SR under null (Euler-Mascheroni approximation)
    euler_mascheroni = 0.5772156649
    expected_max_sr = norm.ppf(1 - 1 / num_trials) * (
        1 - euler_mascheroni
    ) + euler_mascheroni * norm.ppf(1 - 1 / (num_trials * np.e))
    dsr = norm.cdf((observed_sr - expected_max_sr) / sr_std)
    return dsr

A DSR below 0.95 suggests the observed performance is likely due to overfitting across the trials tested.

Probability of Backtest Overfitting (PBO)

PBO uses CPCV to measure the fraction of backtest paths where the in-sample optimal strategy underperforms the median out-of-sample. A PBO above 0.50 indicates more-likely-than-not overfitting.

See references/overfit_detection.md for complete derivations and implementation details.

Crypto-Specific Considerations

  1. Shorter windows: Crypto regimes change faster than equities. A 90-day rolling window may be more appropriate than 252 days.
  2. 24/7 markets: No weekends or holidays to account for, but funding rate resets (every 8h on perps) create microstructure effects.
  3. Survivorship bias: Many tokens delist. Validation must include delisted tokens or at minimum acknowledge this limitation.
  4. Liquidity regime shifts: A token's liquidity profile can change dramatically (new CEX listing, liquidity mining end). Train/test splits should ideally not straddle major liquidity events.
  5. Data availability: Many tokens have < 1 year of data. Expanding windows with small min_train_size may be necessary.

Practical Window Sizes for Crypto

Strategy Timeframe Train Window Test Window Embargo
Scalping (1-5min) 3-7 days 1 day 2-4 hours
Intraday (15min-1h) 14-30 days 3-7 days 12-24 hours
Swing (4h-daily) 30-90 days 7-14 days 2-5 days
Position (daily-weekly) 90-180 days 30 days 5-10 days

Quick Start

from walk_forward import WalkForwardValidator, WalkForwardConfig

config = WalkForwardConfig(
    train_size=90,
    test_size=14,
    step_size=14,
    window_type="rolling",
    embargo_size=3,
    purge_horizon=1,
)

validator = WalkForwardValidator(config)
for fold in validator.split(price_data):
    model.fit(fold.train_X, fold.train_y)
    predictions = model.predict(fold.test_X)
    fold.record_performance(predictions, fold.test_y)

results = validator.aggregate_results()
print(f"OOS Sharpe: {results.oos_sharpe:.3f}")
print(f"Train/Test Sharpe ratio: {results.sharpe_ratio_ratio:.2f}")

Files

References

  • references/methodology.md — Walk-forward theory, window types, purging, embargo, CPCV algorithm with formulas
  • references/overfit_detection.md — Deflated Sharpe ratio, probability of backtest overfitting, multiple testing corrections
  • references/practical_guide.md — Window size selection for crypto, regime considerations, common validation mistakes

Scripts

  • scripts/walk_forward.py — Walk-forward validation engine with rolling and expanding windows; --demo mode with synthetic data
  • scripts/overfit_detector.py — Deflated Sharpe ratio and PBO computation; --demo mode with synthetic backtest results