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

cointegration-analysis

複数の株価データが長期的に連動する関係性を、エンゲル・グレンジャー法やヨハンセン法といった手法で分析し、ペアトレーディング戦略に役立てるかを判断するSkill。

📜 元の英語説明(参考)

Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

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

一言でいうと

複数の株価データが長期的に連動する関係性を、エンゲル・グレンジャー法やヨハンセン法といった手法で分析し、ペアトレーディング戦略に役立てるかを判断するSkill。

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

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

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

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

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

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して cointegration-analysis.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → cointegration-analysis フォルダができる
  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 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

コインtegration分析

コインtegrationテストは、長期的な均衡関係を共有する資産のペアを特定し、統計的裁定取引およびペア取引戦略を可能にします。

コインtegrationとは?

2つの価格系列は、個々には非定常(ランダムウォーク)であるものの、それらの線形結合が定常(平均回帰)である場合に、コインtegratedであると言えます。直感的には、価格は一時的に乖離する可能性がありますが、時間の経過とともに均衡スプレッドに戻される力が働きます。

コインtegration vs 相関

プロパティ 相関 コインtegration
測定対象 短期的な共変動 長期的な均衡
定常性 定常的なリターンが必要 非定常な価格で機能
時間軸 急速に変化する可能性 数ヶ月/年単位で安定
取引での利用 モメンタム/トレンドシグナル 平均回帰ペア取引
失敗モード レジーム変化による崩壊 構造的変化による崩壊

2つの資産は、高い相関関係を持つ可能性がありますが、コインtegratedではない可能性があります(例:無関係な2つの上昇トレンド)。逆に、コインtegratedな資産は、一時的な乖離の間、短期的な相関が低い可能性があります。これはまさにペア取引が開始されるタイミングです。

なぜ重要なのか

  • ペア取引: パフォーマンスの低い方をロング、パフォーマンスの高い方をショートし、収束時に利益を得る
  • 統計的裁定取引: スプレッドのzスコアに基づく体系的な平均回帰
  • スプレッド取引: スプレッドを合成商品として直接取引
  • リスクヘッジ: コインtegratedなヘッジ比率は、時間の経過に伴うトラッキングエラーを最小限に抑える

手法

1. Engle-Grangerの二段階法

2つの系列に対する最も一般的なアプローチです。

ステップ1 — YをXにOLS回帰する:

Y_t = α + β * X_t + ε_t

ステップ2 — 残差 ε_t が定常であるかどうかをADFテストでテストする。

  • 残差が定常である場合(p < 0.05)→ YとXはコインtegratedである
  • β はペア取引のヘッジ比率である
  • α はスプレッドの長期的な平均である

重要: Engle-Grangerの臨界値は、標準的なADFの臨界値とは異なります。n=2系列の場合:1% = -3.90、5% = -3.34、10% = -3.04。

非対称性に関する警告: Y~Xのテストは、X~Yとは異なる結果をもたらす可能性があります。常に両方向をテストし、より強い結果を使用してください。

from scipy import stats
import numpy as np
from statsmodels.tsa.stattools import adfuller

# ステップ1: OLS回帰
slope, intercept, _, _, _ = stats.linregress(x_prices, y_prices)
hedge_ratio = slope

# ステップ2: 残差のテスト
residuals = y_prices - hedge_ratio * x_prices - intercept
adf_stat, p_value, _, _, crit_values, _ = adfuller(residuals, maxlag=None, autolag="AIC")

cointegrated = p_value < 0.05

2. Johansenテスト

複数の系列を同時にテストし、コインtegratingな関係の数を返します。3つ以上の系列の場合、Engle-Grangerよりも強力です。

  • VARモデルに基づく: ΔYt = Π·Y{t-1} + Σ Γi·ΔY{t-i} + ε_t
  • Π行列のランクをテストする
  • トレーステストと最大固有値テストを使用する
  • 返り値: コインtegratingベクトル数とベクトル自体
from statsmodels.tsa.vector_ar.vecm import coint_johansen

# data: T×N の価格系列の配列
result = coint_johansen(data, det_order=0, k_ar_diff=1)

# トレース統計量 vs 臨界値 (90%, 95%, 99%)
trace_stats = result.lr1          # トレース統計量
trace_crit = result.cvt           # 臨界値
max_eigen_stats = result.lr2      # 最大固有値統計量
max_eigen_crit = result.cvm       # 臨界値

# コインtegratingベクトル
coint_vectors = result.evec

3. Phillips-Ouliaris

Engle-Grangerに似ていますが、ADFの代わりにPhillips-Perronスタイルの検定統計量を使用します。残差の異分散性と系列相関に対してよりロバストです。statsmodels.tsa.stattools.cointから利用可能です。

from statsmodels.tsa.stattools import coint

# 返り値: 検定統計量、p値、臨界値
t_stat, p_value, crit_values = coint(y_prices, x_prices)
cointegrated = p_value < 0.05

実践的なワークフロー

ステップ1: 相関によるペアのスクリーニング

Pearson相関 > 0.7を使用して事前にフィルタリングし、コインtegrationテストの数を減らします(コインtegrationテストはよりコストがかかります)。

ステップ2: コインtegrationのテスト

Engle-Grangerを両方向で実行します。p < 0.05の閾値を使用します。

ステップ3: ヘッジ比率の推定

単純化のためにOLSを使用します。本番環境では、Total Least SquaresまたはDynamic OLSを検討してください(references/methodology.mdを参照)。

ステップ4: スプレッドの計算

spread = y_prices - hedge_ratio * x_prices - intercept
z_score = (spread - spread.mean()) / spread.std()

ステップ5: スプレッドの平均回帰性のテスト

  • ADFテスト: p < 0.05は定常性を確認する
  • Hurst指数: H < 0.5は平均回帰を示す(H ≈ 0.5 = ランダムウォーク)
  • 半減期: スプレッドに対するAR(1)からのλ; 半減期 = -ln(2)/ln(λ)
    • 実行可能なペア: 半減期が5〜60日の間

ステップ6: スプレッドの取引

スプレッドが平均回帰性を示す場合、それは実行可能なペア取引の候補です。エントリー/エグジットルールとリスク管理については、references/pairs_trading.mdを参照してください。

ローリングコインtegration

コインtegrationの関係は、構造的変化、レジームシフト、または市場力学の進化により、時間の経過とともに崩壊する可能性があります。

ローリングウィンドウアプローチ

ローリング60〜90日のウィンドウでコインtegrationをテストします。

window = 60
rolling_pvalues = []
rolling_hedges = []

for i in range(window, len(prices)):
    y_win = y_prices[i - window:i]
    x_win = x_prices[i - window:i]
    _, p_val, _ = coint(y_win, x_win)
    slope, intercept, _, _, _ = stats.linregress(x_win, y_win)
    rolling_pvalues.append(p_val)
    rolling_hedges.append(slope)

モニタリングシグナル

シグナル 健全 警告 取引停止
ローリングp値 < 0.05 0.05–0.10 > 0.10
ヘッジ比率のドリフト < 10% の変化 10–25% の変化 > 25% の変化
スプレッドの半減期 5–60 日 60–120 日 > 120 日 または < 5

暗号資産ペアの候補

レイヤー1の相関

  • SOL vs ETH — L1セクターのベータ値、トレンド市場でコインtegratedになることが多い
  • SOL vs AVAX — 代替L1の相関

ステーブルコイン

  • USDC vs USDT — 完璧であるはず

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

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

Cointegration Analysis

Cointegration testing identifies pairs of assets that share a long-run equilibrium relationship, enabling statistical arbitrage and pairs trading strategies.

What Is Cointegration?

Two price series are cointegrated when they are individually non-stationary (random walks) but a linear combination of them is stationary (mean-reverting). Intuitively, the prices may wander apart temporarily but are pulled back to an equilibrium spread over time.

Cointegration vs Correlation

Property Correlation Cointegration
Measures Short-term co-movement Long-run equilibrium
Stationarity Requires stationary returns Works with non-stationary prices
Time horizon Can change rapidly Stable over months/years
Trading use Momentum/trend signals Mean-reversion pairs trades
Failure mode Breaks in regime changes Breaks on structural shifts

Two assets can be highly correlated but not cointegrated (e.g., two unrelated uptrends). Conversely, cointegrated assets may have low short-term correlation during temporary divergences — which is exactly when pairs trades are entered.

Why It Matters

  • Pairs trading: Long the underperformer, short the outperformer, profit on convergence
  • Statistical arbitrage: Systematic mean-reversion on spread z-scores
  • Spread trading: Trade the spread directly as a synthetic instrument
  • Risk hedging: Cointegrated hedge ratios minimize tracking error over time

Methods

1. Engle-Granger Two-Step

The most common approach for two series.

Step 1 — Regress Y on X using OLS:

Y_t = α + β * X_t + ε_t

Step 2 — Test the residuals ε_t for stationarity using the ADF test.

  • If residuals are stationary (p < 0.05) → Y and X are cointegrated
  • β is the hedge ratio for the pairs trade
  • α is the long-run mean of the spread

Important: Engle-Granger critical values differ from standard ADF critical values. For n=2 series: 1% = -3.90, 5% = -3.34, 10% = -3.04.

Asymmetry warning: Testing Y~X can give a different result than X~Y. Always test both directions and use the stronger result.

from scipy import stats
import numpy as np
from statsmodels.tsa.stattools import adfuller

# Step 1: OLS regression
slope, intercept, _, _, _ = stats.linregress(x_prices, y_prices)
hedge_ratio = slope

# Step 2: Test residuals
residuals = y_prices - hedge_ratio * x_prices - intercept
adf_stat, p_value, _, _, crit_values, _ = adfuller(residuals, maxlag=None, autolag="AIC")

cointegrated = p_value < 0.05

2. Johansen Test

Tests multiple series simultaneously and returns the number of cointegrating relationships. More powerful than Engle-Granger for >2 series.

  • Based on a VAR model: ΔYt = Π·Y{t-1} + Σ Γi·ΔY{t-i} + ε_t
  • Tests the rank of the Π matrix
  • Uses trace test and maximum eigenvalue test
  • Returns: number of cointegrating vectors and the vectors themselves
from statsmodels.tsa.vector_ar.vecm import coint_johansen

# data: T×N array of price series
result = coint_johansen(data, det_order=0, k_ar_diff=1)

# Trace statistic vs critical values (90%, 95%, 99%)
trace_stats = result.lr1          # Trace statistics
trace_crit = result.cvt           # Critical values
max_eigen_stats = result.lr2      # Max eigenvalue statistics
max_eigen_crit = result.cvm       # Critical values

# Cointegrating vectors
coint_vectors = result.evec

3. Phillips-Ouliaris

Similar to Engle-Granger but uses Phillips-Perron style test statistics instead of ADF. More robust to heteroskedasticity and serial correlation in the residuals. Available via statsmodels.tsa.stattools.coint.

from statsmodels.tsa.stattools import coint

# Returns: test statistic, p-value, critical values
t_stat, p_value, crit_values = coint(y_prices, x_prices)
cointegrated = p_value < 0.05

Practical Workflow

Step 1: Screen Pairs by Correlation

Pre-filter using Pearson correlation > 0.7 to reduce the number of cointegration tests (which are more expensive).

Step 2: Test Cointegration

Run Engle-Granger in both directions. Use p < 0.05 threshold.

Step 3: Estimate Hedge Ratio

Use OLS for simplicity. For production, consider Total Least Squares or Dynamic OLS (see references/methodology.md).

Step 4: Compute Spread

spread = y_prices - hedge_ratio * x_prices - intercept
z_score = (spread - spread.mean()) / spread.std()

Step 5: Test Spread for Mean Reversion

  • ADF test: p < 0.05 confirms stationarity
  • Hurst exponent: H < 0.5 indicates mean reversion (H ≈ 0.5 = random walk)
  • Half-life: λ from AR(1) on spread; half-life = -ln(2)/ln(λ)
    • Viable pairs: half-life between 5 and 60 days

Step 6: Trade the Spread

If the spread is mean-reverting, it is a viable pairs trade candidate. See references/pairs_trading.md for entry/exit rules and risk management.

Rolling Cointegration

Cointegration relationships can break down over time due to structural changes, regime shifts, or evolving market dynamics.

Rolling Window Approach

Test cointegration on rolling 60–90 day windows:

window = 60
rolling_pvalues = []
rolling_hedges = []

for i in range(window, len(prices)):
    y_win = y_prices[i - window:i]
    x_win = x_prices[i - window:i]
    _, p_val, _ = coint(y_win, x_win)
    slope, intercept, _, _, _ = stats.linregress(x_win, y_win)
    rolling_pvalues.append(p_val)
    rolling_hedges.append(slope)

Monitoring Signals

Signal Healthy Warning Stop Trading
Rolling p-value < 0.05 0.05–0.10 > 0.10
Hedge ratio drift < 10% change 10–25% change > 25% change
Spread half-life 5–60 days 60–120 days > 120 days or < 5

Crypto Pairs Candidates

Layer-1 Correlation

  • SOL vs ETH — L1 sector beta, often cointegrated during trending markets
  • SOL vs AVAX — alternative L1 correlation

Stablecoins

  • USDC vs USDT — should be perfectly cointegrated (peg arbitrage)
  • Useful as a sanity check for your cointegration pipeline

Liquid Staking Derivatives

  • mSOL vs jitoSOL — both track SOL staking yield
  • stSOL vs mSOL — Lido vs Marinade staking

Same-Sector Tokens

  • DEX tokens: RAY vs ORCA
  • Lending tokens: cross-protocol comparison
  • Meme tokens: rarely cointegrated, high risk

Common Pitfalls

  1. Spurious cointegration — Two trending series (both up in a bull market) may appear cointegrated. Always test on sufficient data (>200 observations) and check out-of-sample stability.

  2. Structural breaks — A fundamental change (protocol upgrade, tokenomics change) can permanently break cointegration. Monitor rolling p-values.

  3. Look-ahead bias — Estimating the hedge ratio on the full sample and then backtesting on the same sample inflates results. Always use walk-forward estimation.

  4. Too-short sample — Cointegration tests need >100 observations minimum, ideally >200, to have reasonable power.

  5. Ignoring transaction costs — Pairs trades involve 4 transactions per round trip. At 0.3% per leg, that is 1.2% in costs that the spread must overcome.

  6. Asymmetric cointegration — The relationship may only hold in one direction or one regime. Consider threshold cointegration models for production use.

Integration with Other Skills

  • correlation-analysis — Pre-screening pairs by correlation before cointegration testing
  • mean-reversion — Trading the cointegrated spread using mean-reversion entry/exit rules
  • vectorbt — Backtesting pairs strategies with walk-forward validation
  • regime-detection — Identifying when cointegration regimes shift
  • volatility-modeling — Spread volatility forecasting for dynamic position sizing

Files

References

  • references/methodology.md — Engle-Granger details, Johansen derivation, hedge ratio estimation methods, spread construction
  • references/pairs_trading.md — Entry/exit rules, risk management, performance metrics, crypto-specific considerations

Scripts

  • scripts/test_cointegration.py — Full cointegration test pipeline with ADF, Hurst, half-life, rolling stability, and demo mode
  • scripts/pairs_backtest.py — Walk-forward pairs trading backtest with synthetic data and performance reporting