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

mean-reversion

ハースト指数や半減期推定、Zスコアなどの指標を用いて、平均回帰戦略に基づいた投資判断や分析をサポートし、統計的な検定やモデリングも行えるようにするSkill。

📜 元の英語説明(参考)

Mean-reversion strategy tools including Hurst exponent, half-life estimation, z-score signals, ADF testing, and Ornstein-Uhlenbeck modeling

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

一言でいうと

ハースト指数や半減期推定、Zスコアなどの指標を用いて、平均回帰戦略に基づいた投資判断や分析をサポートし、統計的な検定やモデリングも行えるようにするSkill。

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

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

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

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

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

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

平均回帰

平均回帰とは、価格、スプレッド、またはその他の金融変数が、そこから逸脱した後、長期的な平均に戻ろうとする統計的な傾向のことです。平均回帰系列は、その平均をオーバーシュートし、その後修正して戻り、取引可能な予測可能な振動を作り出します。

平均回帰が機能する場合

  • レンジ相場: 明確なサポート/レジスタンスのある横ばいの価格変動
  • ペアスプレッド: 共積分された資産間のスプレッドが均衡に戻る
  • 売られすぎ/買われすぎの極端な状態: 定常系列における RSI、Bollinger Band、または z-score の極端な状態
  • ファンディングレート裁定取引: 永久ファンディングレートがベースラインに戻る
  • ステーブルコインのデペッグ: 典型的な平均回帰の機会 (ペッグ = 既知の平均)
  • 暴落後の回復: PumpFun の最初の暴落後の短い平均回帰期間

平均回帰が機能しない場合

  • 強力なトレンド相場 (ほとんどの暗号資産のほとんどの時間)
  • レジームの変化: 定常的だったものが非定常的になる
  • 構造的な変化: トークンの移行、プロトコルのアップグレード、上場廃止
  • 低い流動性: ワイドスプレッドが平均回帰の利益を消費する

平均回帰のテスト

平均回帰を取引する前に、その系列が平均回帰的であることを統計的に確認する必要があります。3つの補完的なテストがあります。

1. 拡張 Dickey-Fuller (ADF) テスト

系列が単位根 (非定常) を持つという帰無仮説をテストします。

from scipy import stats
import numpy as np

def adf_test(series: np.ndarray, max_lag: int = 0) -> dict:
    """ADF テストを実行します。帰無仮説を棄却 (p < 0.05) → 定常 → 平均回帰。"""
    # 完全な実装については references/statistical_tests.md を参照してください
    # 本番環境では statsmodels.tsa.stattools.adfuller を使用してください
    pass
  • p < 0.01: 定常性の強い証拠
  • p < 0.05: 定常性の証拠
  • p > 0.10: 単位根を棄却できない -- おそらく非定常

2. Hurst 指数

時系列の長期依存性を測定します。

Hurst Value 解釈 取引上の意味
H < 0.5 平均回帰的 平均回帰を取引する
H = 0.5 ランダムウォーク エッジなし
H > 0.5 トレンド モメンタムを取引する
def hurst_exponent(series: np.ndarray) -> float:
    """R/S 法で Hurst 指数を計算します。H < 0.5 → 平均回帰。"""
    # 完全な R/S アルゴリズムについては references/statistical_tests.md を参照してください
    pass

3. 分散比テスト

複数期間のリターン分散を単一期間の分散と比較します。

  • VR < 1: 負の自己相関 (平均回帰)
  • VR = 1: ランダムウォーク
  • VR > 1: 正の自己相関 (トレンド)
def variance_ratio(series: np.ndarray, q: int = 5) -> float:
    """ホライズン q で分散比を計算します。VR < 1 → 平均回帰。"""
    returns = np.diff(np.log(series))
    var_1 = np.var(returns)
    returns_q = np.diff(np.log(series[::q]))
    var_q = np.var(returns_q)
    return var_q / (q * var_1)

完全な実装と解釈ガイドについては、references/statistical_tests.md を参照してください。


半減期推定

半減期は、逸脱がそのサイズの半分に減衰するのにかかる期間を示します。これは、平均回帰取引にとって最も重要なパラメータです。

AR(1) 回帰法

自己回帰モデルを適合させます: delta_X_t = alpha + beta * X_{t-1} + epsilon

def half_life(series: np.ndarray) -> float:
    """AR(1) 回帰から平均回帰半減期を推定します。

    戻り値:
        期間単位の半減期。負の値は平均回帰的ではないことを意味します。
    """
    y = np.diff(series)
    x = series[:-1]
    x = np.column_stack([np.ones(len(x)), x])
    beta = np.linalg.lstsq(x, y, rcond=None)[0][1]
    if beta >= 0:
        return -1.0  # 平均回帰的ではない
    return -np.log(2) / np.log(1 + beta)

半減期の使用

パラメータ 経験則
ルックバックウィンドウ 半減期の 2 倍
保有期間 半減期の 1 倍
最大保有期間 半減期の 3 倍 (ストップ)
シグナル再計算 半減期の 0.5 倍

Z-Score シグナルフレームワーク

z-score は平均からの逸脱を正規化し、標準化されたエントリー/イグジットシグナルを提供します。

z = (price - rolling_mean) / rolling_std

シグナルルール

条件 シグナル アクション
z < -2.0 買い ロングエントリー (価格が平均を下回る)
z > +2.0 売り ショートエントリー (価格が平均を上回る)
z が 0 をクロス イグジット ポジションをクローズ (平均に戻った)
abs(z) > 3.0 ストップ ポジションをクローズ (回帰に失敗した)

ルックバックウィンドウ

ローリングウィンドウを半減期の約 2 倍に設定します。

def z_score_signals(
    prices: np.ndarray,
    lookback: int,
    entry_z: float = 2.0,
    exit_z: float = 0.0,
    stop_z: float = 3.0,
) -> np.ndarray:
    """z-score ベースの平均回帰シグナルを生成します。

    戻り値:
        シグナルの配列: 1 (ロング), -1 (ショート), 0 (フラット)。
    """
    rolling_mean = pd.Series(prices).rolling(lookback).mean().values
    rolling_std = pd.Series(prices).rolling(lookback).std().values
    z = (prices - rolling_mean) / rolling_std
    # 完全なシグナル生成については scripts/mean_reversion_test.py を参照してください
    ...

Z-Score を使用したポジションサイジング

リスク調整後のリターンを向上させるために、z-score の大きさでポジションサイズを調整します。

size = base_size * min(abs(z) / entry_threshold, max_scale)

完全なエントリー/イグジットフレームワークとサイジングについては、references/strategy_design.md を参照してください。


Ornstein-Uhlenbeck (OU) プロセス

OU プロセスは、平均回帰の連続時間モデルです。

dX = theta * (mu - X) * dt + sigma * dW
パラメータ 意味 推定
theta 平均回帰の速度 AR(1) のベータから: theta = -ln(1+beta)/dt
mu 長期的な平均 AR(1) の切片から: mu = -alpha/beta
sigma イノベーションのボラティリティ AR(1) からの残差標準偏差

パラメータ推定


def estimate_ou_params(series: np.ndarray, dt: float = 1.0) -
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Mean Reversion

Mean reversion is the statistical tendency for prices, spreads, or other financial variables to return toward a long-run average after deviating from it. A mean-reverting series overshoots its mean, then corrects back -- creating predictable oscillations that can be traded.

When Mean Reversion Works

  • Ranging markets: Sideways price action with clear support/resistance
  • Pairs spreads: Spread between cointegrated assets reverts to equilibrium
  • Oversold/overbought extremes: RSI, Bollinger Band, or z-score extremes in stationary series
  • Funding rate arbitrage: Perpetual funding rates revert to baseline
  • Stablecoin depegs: Classic mean-reversion opportunity (peg = known mean)
  • Post-dump recovery: Brief mean-reversion windows after initial PumpFun dumps

When Mean Reversion Fails

  • Strong trending markets (most crypto most of the time)
  • Regime changes: what was stationary becomes non-stationary
  • Structural breaks: token migration, protocol upgrade, delistings
  • Low liquidity: wide spreads consume mean-reversion profits

Testing for Mean Reversion

Before trading mean reversion, you must statistically confirm the series is mean-reverting. Three complementary tests:

1. Augmented Dickey-Fuller (ADF) Test

Tests the null hypothesis that a series has a unit root (non-stationary).

from scipy import stats
import numpy as np

def adf_test(series: np.ndarray, max_lag: int = 0) -> dict:
    """Run ADF test. Reject null (p < 0.05) → stationary → mean-reverting."""
    # See references/statistical_tests.md for full implementation
    # Use statsmodels.tsa.stattools.adfuller for production
    pass
  • p < 0.01: Strong evidence of stationarity
  • p < 0.05: Evidence of stationarity
  • p > 0.10: Cannot reject unit root -- likely non-stationary

2. Hurst Exponent

Measures the long-range dependence of a time series.

Hurst Value Interpretation Trading Implication
H < 0.5 Mean-reverting Trade mean reversion
H = 0.5 Random walk No edge
H > 0.5 Trending Trade momentum
def hurst_exponent(series: np.ndarray) -> float:
    """Compute Hurst exponent via R/S method. H < 0.5 → mean-reverting."""
    # See references/statistical_tests.md for full R/S algorithm
    pass

3. Variance Ratio Test

Compares variance of multi-period returns to single-period variance.

  • VR < 1: Negative autocorrelation (mean-reverting)
  • VR = 1: Random walk
  • VR > 1: Positive autocorrelation (trending)
def variance_ratio(series: np.ndarray, q: int = 5) -> float:
    """Compute variance ratio at horizon q. VR < 1 → mean-reverting."""
    returns = np.diff(np.log(series))
    var_1 = np.var(returns)
    returns_q = np.diff(np.log(series[::q]))
    var_q = np.var(returns_q)
    return var_q / (q * var_1)

See references/statistical_tests.md for complete implementations and interpretation guides.


Half-Life Estimation

The half-life tells you how many periods it takes for a deviation to decay to half its size. This is the single most important parameter for mean-reversion trading.

AR(1) Regression Method

Fit the autoregressive model: delta_X_t = alpha + beta * X_{t-1} + epsilon

def half_life(series: np.ndarray) -> float:
    """Estimate mean-reversion half-life from AR(1) regression.

    Returns:
        Half-life in periods. Negative means non-mean-reverting.
    """
    y = np.diff(series)
    x = series[:-1]
    x = np.column_stack([np.ones(len(x)), x])
    beta = np.linalg.lstsq(x, y, rcond=None)[0][1]
    if beta >= 0:
        return -1.0  # Not mean-reverting
    return -np.log(2) / np.log(1 + beta)

Using Half-Life

Parameter Rule of Thumb
Lookback window 2x half-life
Holding period 1x half-life
Maximum hold 3x half-life (stop)
Signal recalc 0.5x half-life

Z-Score Signal Framework

The z-score normalizes the deviation from the mean, providing standardized entry/exit signals.

z = (price - rolling_mean) / rolling_std

Signal Rules

Condition Signal Action
z < -2.0 Buy Enter long (price below mean)
z > +2.0 Sell Enter short (price above mean)
z crosses 0 Exit Close position (returned to mean)
abs(z) > 3.0 Stop Close position (reversion failed)

Lookback Window

Set the rolling window to approximately 2x the half-life:

def z_score_signals(
    prices: np.ndarray,
    lookback: int,
    entry_z: float = 2.0,
    exit_z: float = 0.0,
    stop_z: float = 3.0,
) -> np.ndarray:
    """Generate z-score-based mean-reversion signals.

    Returns:
        Array of signals: 1 (long), -1 (short), 0 (flat).
    """
    rolling_mean = pd.Series(prices).rolling(lookback).mean().values
    rolling_std = pd.Series(prices).rolling(lookback).std().values
    z = (prices - rolling_mean) / rolling_std
    # See scripts/mean_reversion_test.py for full signal generation
    ...

Position Sizing with Z-Score

Scale position size with z-score magnitude for better risk-adjusted returns:

size = base_size * min(abs(z) / entry_threshold, max_scale)

See references/strategy_design.md for complete entry/exit framework and sizing.


Ornstein-Uhlenbeck (OU) Process

The OU process is the continuous-time model of mean reversion:

dX = theta * (mu - X) * dt + sigma * dW
Parameter Meaning Estimation
theta Speed of mean reversion From AR(1) beta: theta = -ln(1+beta)/dt
mu Long-run mean From AR(1) intercept: mu = -alpha/beta
sigma Volatility of innovations Residual std from AR(1)

Parameter Estimation

def estimate_ou_params(series: np.ndarray, dt: float = 1.0) -> dict:
    """Estimate OU process parameters from observed series.

    Returns:
        Dict with keys: theta, mu, sigma, half_life.
    """
    y = np.diff(series)
    x = series[:-1]
    x_with_const = np.column_stack([np.ones(len(x)), x])
    params = np.linalg.lstsq(x_with_const, y, rcond=None)[0]
    alpha, beta = params[0], params[1]

    theta = -np.log(1 + beta) / dt
    mu = -alpha / beta if beta != 0 else np.mean(series)
    residuals = y - (alpha + beta * x)
    sigma = np.std(residuals) * np.sqrt(2 * theta / (1 - np.exp(-2 * theta * dt)))

    return {
        "theta": theta,
        "mu": mu,
        "sigma": sigma,
        "half_life": np.log(2) / theta if theta > 0 else -1,
    }

Strategy Types

Single-Asset Mean Reversion

Apply z-score framework directly to a token's price series. Works best on:

  • Stablecoins (USDC/USDT spread)
  • Tokens in established ranges
  • After confirming stationarity with ADF test

Pairs Trading

Trade the spread between two cointegrated assets:

  1. Confirm cointegration (see cointegration-analysis skill)
  2. Compute spread: S = Y - beta * X
  3. Apply z-score framework to the spread
  4. Go long spread (buy Y, sell X) when z < -2
  5. Go short spread (sell Y, buy X) when z > +2

Statistical Arbitrage

Multi-asset extension of pairs trading:

  • Eigenportfolios from PCA of correlated assets
  • Trade the smallest eigenvalue portfolios (most mean-reverting)
  • Requires larger universe (10+ assets)

Crypto-Specific Considerations

  1. Most crypto trends: Hurst exponent for BTC, ETH, SOL is typically 0.55-0.70. Raw price mean reversion is rare.
  2. Where to find mean reversion:
    • Pairs spreads (SOL/ETH ratio, BTC dominance)
    • Funding rates on perpetuals
    • Basis between spot and futures
    • Stablecoin depegs
    • Fee tier spreads across DEXs
  3. Short lookbacks: Crypto mean reversion has short half-lives (hours to days, not weeks)
  4. Transaction costs: DEX swap fees (0.25-1%) can eat mean-reversion profits. Factor in slippage.
  5. Regime awareness: Use regime-detection skill to only trade mean reversion in ranging regimes.

Integration with Other Skills

Skill Integration
cointegration-analysis Find cointegrated pairs for pairs trading
pandas-ta RSI, Bollinger Bands as mean-reversion indicators
regime-detection Filter: only trade MR in ranging regimes
vectorbt Backtest mean-reversion strategies
volatility-modeling Estimate sigma for OU model
slippage-modeling Factor execution costs into P&L estimates
position-sizing Size positions using Kelly + z-score scaling

Files

References

  • references/statistical_tests.md -- ADF, Hurst exponent, variance ratio, and half-life estimation with full implementations and interpretation
  • references/strategy_design.md -- Z-score framework, position sizing, pairs trading setup, risk management, and backtest considerations

Scripts

  • scripts/mean_reversion_test.py -- Comprehensive mean-reversion analysis: ADF, Hurst, variance ratio, half-life, OU estimation, z-score signals
  • scripts/pairs_scanner.py -- Scan multiple assets for mean-reverting pairs: correlation, cointegration, spread analysis, ranking

Quick Start

# Run mean-reversion analysis on synthetic data
python scripts/mean_reversion_test.py --demo

# Scan for mean-reverting pairs
python scripts/pairs_scanner.py --demo

# Analyze a specific token (requires BIRDEYE_API_KEY)
BIRDEYE_API_KEY=your_key TOKEN_MINT=So11...1 python scripts/mean_reversion_test.py

This skill provides analytical tools and information only. It does not constitute financial advice or trading recommendations.