Core Strategy Stocks, Crypto, All Markets

Mean Reversion

Paste into Claude, ChatGPT, or any coding agent

This skill implements mean-reversion trading strategies — identifying assets or spreads that have deviated significantly from their statistical mean and trading the expected reversion. Mean reversion works best in ranging markets and is the natural complement to momentum trading. This skill covers z-score frameworks, Bollinger Band setups, pairs trading with cointegration, crypto funding rate arbitrage, and the statistical tests needed to validate that a series is actually mean-reverting.

When to Use This Skill

  • When an asset appears overextended above or below its historical average
  • When building a pairs trade or spread trade between related assets
  • When crypto perpetual funding rates reach extremes
  • When Bollinger Bands show a squeeze followed by an expansion
  • When testing whether a spread or series is stationary (mean-reverting)
  • When determining if the market regime favors reversion over momentum
  • When the user wants to fade an extreme move (“buy the dip” or “sell the rip”)
  • When constructing a statistical arbitrage portfolio

What This Skill Does

  1. Z-Score Framework: Calculates z-scores for assets and spreads, defines entry/exit thresholds
  2. Bollinger Band Reversion: Identifies %B-based entry setups and bandwidth squeeze signals
  3. Pairs Trading: Tests cointegration, constructs spreads, defines entry/exit rules for pairs
  4. Funding Rate Arbitrage: Exploits extreme funding rates in crypto perpetual futures
  5. Regime Detection: Determines when mean reversion works vs. when it fails (trending markets)
  6. Statistical Validation: Runs ADF test, Hurst exponent, and half-life calculations
  7. Risk Management: Applies tight stops, time-based exits, and max holding periods specific to reversion

How to Use

Z-Score Analysis

Calculate the z-score for ETH/BTC spread. Is it at reversion levels?
What's the z-score of SOL right now relative to its 60-day mean?

Pairs Trading

Are BTC and ETH cointegrated? Set up a pairs trade
Find cointegrated crypto pairs for stat arb

Bollinger Band Setup

Is AAPL showing a Bollinger Band squeeze? Setup a reversion trade

Funding Rate Arbitrage

Funding rate on ETH perps is extremely negative. Should I go long?
Scan for extreme funding rates across crypto perpetuals

Regime Check

Is the current market better for mean reversion or momentum?

Data Sources

With MCP/CLI tools connected:

  • yFinance MCPs (tooyipjee, maxscheijen, Adity-star) — Historical price data for z-scores, Bollinger Bands, cointegration testing
  • Binance MCP — Real-time prices, perpetual futures funding rates, order book data
  • Bybit MCP — Additional funding rate data, perpetual futures markets
  • Empyrical MCP — Statistical analysis, risk metrics, return distribution analysis
  • CoinGecko MCP / CoinGecko Price MCP — Cross-exchange pricing, historical data for spread construction
  • OpenBB CLI — Statistical analysis, pair screening, technical indicators

Without tool access: Ask the user to provide:

  1. Asset(s) and price history (minimum 60 periods for z-score, 250 for cointegration)
  2. Current price and the statistical mean/benchmark
  3. For pairs: prices of both assets over the same time period
  4. For funding: current funding rate and recent history
  5. Current Bollinger Band values (if available)

Proceed with analysis using provided data. Note limitations of sample size.

Methodology

Step 1: Z-Score Framework

The z-score measures how many standard deviations a value is from its mean. It is the foundation of all mean-reversion strategies.

Single Asset Z-Score

Z-SCORE CALCULATION:
  z = (Current_Price - Mean_Price(n)) / StdDev_Price(n)

  Where n = lookback period (typically 20-60 for daily data)

RECOMMENDED LOOKBACK PERIODS:
  | Time Horizon   | Lookback (n) | Mean Type      |
  |----------------|-------------|----------------|
  | Intraday       | 20-50 bars  | SMA or VWAP    |
  | Swing (daily)  | 20-60 days  | SMA(20) or SMA(50)|
  | Position       | 60-120 days | SMA(60)        |
  | Long-term      | 120-252 days| SMA(200)       |

ENTRY/EXIT THRESHOLDS:
  | Z-Score   | Interpretation              | Action                    |
  |-----------|-----------------------------|---------------------------|
  | > +3.0    | Extreme overextension       | Strong short signal        |
  | +2.0 to +3.0 | Significant overextension | Short entry zone          |
  | +1.0 to +2.0 | Mild overextension        | Watchlist for short       |
  | +0.5      | Exit zone for shorts        | Close short positions     |
  |  0.0      | At the mean                 | No signal                 |
  | -0.5      | Exit zone for longs         | Close long positions      |
  | -1.0 to -2.0 | Mild underextension       | Watchlist for long        |
  | -2.0 to -3.0 | Significant underextension| Long entry zone           |
  | < -3.0    | Extreme underextension      | Strong long signal        |

STANDARD RULES:
  Enter: |z| ≥ 2.0
  Exit:  |z| ≤ 0.5 (take profit at partial reversion)
  Stop:  |z| ≥ 3.5 (reversion thesis invalidated -- possible regime change)

Spread Z-Score (for Pairs Trading)

SPREAD Z-SCORE:
  Spread = Price_A - (Hedge_Ratio × Price_B)
  z_spread = (Spread - Mean_Spread(n)) / StdDev_Spread(n)

  Where Hedge_Ratio = β from regression: Price_A = α + β × Price_B + ε

DYNAMIC HEDGE RATIO:
  Use rolling regression (60-day window) to update hedge ratio
  Recalculate weekly to account for changing relationship

  Kalman filter (advanced): Adapts hedge ratio continuously
    β_t = β_{t-1} + K_t × (Price_A_t - α - β_{t-1} × Price_B_t)
    Where K = Kalman gain (typically 0.01-0.05)

Step 2: Bollinger Band Reversion

%B Indicator

BOLLINGER BAND SETUP:
  Middle Band = SMA(20)
  Upper Band = SMA(20) + 2 × StdDev(20)
  Lower Band = SMA(20) - 2 × StdDev(20)

%B CALCULATION:
  %B = (Price - Lower Band) / (Upper Band - Lower Band)

  %B Interpretation:
  | %B Value  | Location          | Reversion Signal    |
  |-----------|-------------------|---------------------|
  | > 1.0     | Above upper band  | Overbought -- short  |
  | 0.8 - 1.0 | Near upper band  | Getting stretched   |
  | 0.2 - 0.8 | Inside bands     | No signal           |
  | 0.0 - 0.2 | Near lower band  | Getting compressed  |
  | < 0.0     | Below lower band  | Oversold -- long     |

REVERSION ENTRY RULES:
  Long:  %B < 0.0 AND %B starts rising (turning point)
  Short: %B > 1.0 AND %B starts falling (turning point)
  Exit:  %B crosses 0.5 (back to middle band)

Bandwidth Squeeze

BANDWIDTH = (Upper Band - Lower Band) / Middle Band

SQUEEZE DETECTION:
  Bandwidth < 6-month minimum bandwidth → SQUEEZE
  A squeeze indicates extremely low volatility -- an expansion is coming

SQUEEZE TRADING STRATEGY:
  1. Identify squeeze (bandwidth at multi-month low)
  2. Wait for bandwidth to START expanding
  3. Trade in the direction of the expansion:
     - Price breaks above upper band → long (breakout)
     - Price breaks below lower band → short (breakdown)
  4. This is NOT a reversion trade -- it is a breakout trade triggered by a reversion setup

KELTNER CHANNEL SQUEEZE (more precise):
  Squeeze = Bollinger Bands are INSIDE Keltner Channels
  Release = Bollinger Bands expand OUTSIDE Keltner Channels
  This gives cleaner squeeze signals than bandwidth alone

Step 3: Pairs Trading

Cointegration Testing

COINTEGRATION: Two series are cointegrated if their spread is stationary
(i.e., mean-reverting), even if the individual series are not.

ENGLE-GRANGER TWO-STEP METHOD:
  Step 1: Run regression → Price_A = α + β × Price_B + ε
  Step 2: Test residuals (ε) for stationarity using ADF test

  If ADF p-value < 0.05 → cointegrated → PAIRS TRADE IS VALID
  If ADF p-value > 0.05 → NOT cointegrated → DO NOT PAIRS TRADE

JOHANSEN TEST (more robust):
  Tests for cointegration among multiple series simultaneously
  Use when evaluating 3+ assets for a basket trade
  Provides both trace statistic and maximum eigenvalue tests

MINIMUM DATA REQUIREMENTS:
  - At least 250 daily observations (1 year)
  - Preferably 500+ observations for reliable results
  - Test on rolling windows -- cointegration can break down over time

COMMON COINTEGRATED PAIRS (verify before trading):
  Crypto: BTC/ETH, ETH/SOL, stablecoins (USDC/USDT)
  Stocks: XOM/CVX (oil majors), GLD/GDX (gold/miners), KO/PEP
  ETFs:   SPY/IVV, EWA/EWC (Australia/Canada commodity economies)

Pairs Trading Entry/Exit Rules

PAIRS TRADE EXECUTION:

  SETUP:
    1. Confirm cointegration (ADF p-value < 0.05)
    2. Calculate hedge ratio (β) via rolling regression
    3. Construct spread: S = Price_A - β × Price_B
    4. Calculate z-score of spread: z = (S - Mean(S,60)) / StdDev(S,60)

  ENTRY:
    Long spread (buy A, sell β units of B):  z < -2.0
    Short spread (sell A, buy β units of B): z > +2.0

  EXIT:
    Take profit: z crosses back to ±0.5 (partial reversion)
    Full exit:   z crosses 0.0 (full reversion to mean)

  STOP LOSS:
    Hard stop: z exceeds ±3.5 (cointegration may be breaking)
    Time stop: Close after 20 trading days if no reversion (max holding period)
    Loss stop: Close if spread loss exceeds 2% of portfolio

  POSITION SIZING:
    Dollar-neutral: Long side value = Short side value (approximately)
    Risk per pair: 1-2% of portfolio on the NET position
    Adjust for spread volatility: smaller size for wider spreads

PAIR TRADE EXAMPLE:
  BTC at $65,000, ETH at $3,500
  Hedge ratio (β) = 0.054 (from regression)
  Spread = $3,500 - 0.054 × $65,000 = $3,500 - $3,510 = -$10
  Mean spread (60d) = +$50
  StdDev spread (60d) = $30
  Z-score = (-$10 - $50) / $30 = -2.0

  Signal: z = -2.0 → BUY ETH, SELL 0.054 BTC per ETH
  Target: z returns to 0 → spread returns to $50
  Expected profit per spread unit: $60

Step 4: Funding Rate Arbitrage

FUNDING RATE MECHANICS:
  Perpetual futures use funding rates to anchor to spot price.
  Positive funding: Longs pay shorts every 8 hours
  Negative funding: Shorts pay longs every 8 hours

ARBITRAGE STRATEGY (Cash-and-Carry):
  When funding is extremely positive (longs paying shorts):
    1. Buy spot asset
    2. Short perpetual futures (same size)
    3. Collect funding payments (shorts receive payment)
    4. Exit when funding normalizes
    Net position: Market-neutral (hedged)
    Profit source: Funding rate income

  When funding is extremely negative (shorts paying longs):
    1. Short spot (or sell existing holdings)
    2. Long perpetual futures (same size)
    3. Collect funding payments (longs receive payment)
    4. Exit when funding normalizes

ENTRY THRESHOLDS:
  | Funding Rate (8h)  | Annualized      | Action                           |
  |--------------------|-----------------|----------------------------------|
  | > 0.05%            | > 54% APR       | Strong short-perp carry trade    |
  | 0.03% - 0.05%      | 33-54% APR      | Moderate carry opportunity       |
  | 0.01% - 0.03%      | 11-33% APR      | Marginal -- only with low costs   |
  | -0.01% to 0.01%    | Neutral          | No opportunity                   |
  | -0.03% to -0.01%   | 11-33% APR      | Moderate long-perp carry trade   |
  | < -0.03%           | > 33% APR       | Strong long-perp carry trade     |

ANNUALIZED FUNDING RATE:
  Annual Rate = Funding_8h × 3 × 365
  Example: 0.05% per 8h = 0.15% per day = 54.75% annualized

RISKS OF FUNDING ARB:
  - Funding can flip direction suddenly (especially around liquidation cascades)
  - Basis risk: spot and perp may temporarily diverge
  - Exchange counterparty risk (especially on CEX)
  - Margin requirements can increase during volatility
  - Slippage entering/exiting the hedged position

Step 5: Regime Detection — When Mean Reversion Fails

CRITICAL: Mean reversion FAILS in trending markets. Detect regime first.

REGIME CLASSIFICATION FOR MEAN REVERSION:

  FAVORABLE (use mean reversion):
    ADX(14) < 20 → no trend, range-bound market
    Hurst exponent < 0.45 → anti-persistent (mean-reverting)
    Price oscillating around SMA(50) -- multiple crosses in last 20 bars
    Bollinger Bandwidth stable or contracting

  UNFAVORABLE (do NOT use mean reversion -- switch to momentum):
    ADX(14) > 30 → strong trend
    Hurst exponent > 0.55 → persistent (trending)
    Price consistently above/below SMA(50) -- no crosses in 20+ bars
    Bollinger Bandwidth expanding rapidly

  TRANSITIONING (reduce size or wait):
    ADX(14) = 20-30
    Hurst exponent = 0.45-0.55 (random walk zone)
    Mixed signals -- reduce position size by 50%

MEAN REVERSION FAILURE MODES:
  1. "Revert to WHAT mean?" -- In a strong trend, the mean itself is shifting
     Solution: Use shorter lookback or adaptive mean
  2. "Catching a falling knife" -- Asset drops z=-2, you buy, it drops to z=-5
     Solution: ALWAYS use stops. z = -3.5 is invalidation level.
  3. "Cointegration breakdown" -- Pair relationship changes fundamentally
     Solution: Re-test cointegration monthly. Exit if ADF p-value > 0.10

Step 6: Statistical Tests

Augmented Dickey-Fuller (ADF) Test

PURPOSE: Tests if a time series is stationary (mean-reverting)
NULL HYPOTHESIS: The series has a unit root (NOT stationary)

INTERPRETATION:
  p-value < 0.01: Strong evidence of stationarity → mean reversion works
  p-value < 0.05: Evidence of stationarity → proceed with caution
  p-value > 0.05: Cannot reject unit root → NOT mean-reverting, do NOT trade
  p-value > 0.10: Series is likely trending → use momentum instead

APPLY ADF TO:
  - Individual asset prices (rarely stationary)
  - Asset returns (usually stationary -- but this is trivial)
  - Spread between cointegrated pairs (this is what matters)
  - Z-score series (should be stationary if properly constructed)

Hurst Exponent

PURPOSE: Measures the tendency of a series to revert to mean vs. trend

CALCULATION: H = log(R/S) / log(n)
  Where R/S = rescaled range statistic over n observations

INTERPRETATION:
  | Hurst (H) | Behavior         | Strategy               |
  |-----------|------------------|------------------------|
  | 0.0 - 0.4 | Anti-persistent  | STRONG mean reversion  |
  | 0.4 - 0.45| Mildly reverting | Mean reversion favored |
  | 0.45 - 0.55| Random walk     | No edge either way     |
  | 0.55 - 0.6 | Mildly trending | Momentum favored       |
  | 0.6 - 1.0 | Persistent       | STRONG momentum        |

PRACTICAL USAGE:
  Calculate Hurst on rolling 120-day windows
  If H < 0.45 → deploy mean-reversion strategies
  If H > 0.55 → switch to momentum strategies
  If H ≈ 0.5  → neither strategy has an edge -- reduce size or sit out

Half-Life of Mean Reversion

PURPOSE: Estimates how long it takes for a deviation to revert halfway to the mean

CALCULATION:
  Run regression: ΔSpread_t = α + β × Spread_{t-1} + ε
  Half-life = -ln(2) / β   [β should be negative for mean reversion]

INTERPRETATION:
  | Half-life | Speed         | Suitability                      |
  |-----------|---------------|----------------------------------|
  | 1-5 days  | Very fast     | Intraday/day trading reversion   |
  | 5-15 days | Fast          | Swing trading reversion           |
  | 15-30 days| Moderate      | Position trading reversion        |
  | 30-60 days| Slow          | Long-term pairs trade             |
  | > 60 days | Very slow     | Capital may be tied up too long   |
  | Infinite  | No reversion  | Series is NOT mean-reverting      |

PRACTICAL RULE:
  Max holding period = 3 × half-life
  If position hasn't reverted by 3× half-life, close for a loss
  Example: Half-life = 10 days → max hold = 30 days

Step 7: Risk Management for Mean Reversion

MEAN-REVERSION-SPECIFIC RISK RULES:

  1. TIGHT STOPS (mandatory):
     Stop at z = ±3.5 (if entered at z = ±2.0, stop is 1.5σ away)
     Dollar risk = Position × 1.5 × StdDev / Mean
     Per risk-management: Keep this under 1-2% of portfolio

  2. TIME-BASED EXITS:
     Max hold = 3 × half-life of the series
     If no reversion by deadline → close position regardless of P&L
     This prevents capital being trapped in a regime-change situation

  3. MAX OPEN REVERSION TRADES:
     Maximum 3-5 uncorrelated reversion trades open simultaneously
     Correlated reversion trades (e.g., multiple BTC pairs) count as ONE trade
     Total reversion portfolio heat: max 10% of portfolio

  4. PYRAMIDING: GENERALLY AVOID
     Unlike momentum, do NOT add to mean-reversion losers
     Exception: Pre-planned add at z = ±3.0 if z = ±2.0 was initial entry
     This must be part of the ORIGINAL plan, not a reaction to losses

  5. ASYMMETRIC SIZING:
     Larger position if: ADF p-value < 0.01, Hurst < 0.4, half-life < 15 days
     Smaller position if: ADF p-value near 0.05, Hurst near 0.5, half-life > 30 days
     Scale between 0.5x and 1.5x base position size

Anti-Patterns

DO NOT do these — they are the most common mean-reversion failures:

  1. Trading reversion in a trending market: If ADX > 30 or Hurst > 0.55, mean reversion will repeatedly stop you out. Check regime FIRST. When in doubt, use Momentum Trading.

  2. No stop-loss (“it will come back”): The most dangerous phrase in mean reversion. Some deviations are permanent — structural changes, delistings, protocol exploits. Always have a hard stop.

  3. Averaging down without a pre-defined plan: Adding to a loser because “it’s even more oversold now” is how accounts get destroyed. Only add at pre-planned levels that were part of the original trade thesis.

  4. Using cointegration from too short a period: Cointegration tested on 30 days of data is meaningless. Require minimum 250 data points. Even then, re-test monthly.

  5. Ignoring funding rate flip risk: Funding rate arbitrage seems risk-free but funding can flip from +0.05% to -0.05% in one settlement, turning a carry trade into a cost. Always size conservatively.

  6. Applying reversion to non-stationary series: Not everything reverts to the mean. Individual stock prices are generally NOT stationary. Spreads between cointegrated pairs ARE. Test stationarity before trading.

  7. Holding too long past half-life: If 3x the half-life has passed without reversion, the regime has likely changed. Take the loss and reassess.

  8. Ignoring transaction costs on tight reversion: Mean reversion often has smaller profit targets than momentum. Ensure that fees, slippage, and funding costs do not eat the expected edge.

Validation Checkpoints

Input Validation

  • Asset(s) identified with sufficient price history (min 60 bars for z-score, 250 for cointegration)
  • Statistical test performed: ADF test for stationarity (p < 0.05 required)
  • Hurst exponent calculated (H < 0.45 confirms mean reversion)
  • Half-life estimated (determines holding period and time stop)
  • Current z-score or %B calculated
  • Regime classified: is this a ranging or trending market?
  • For pairs: cointegration confirmed, hedge ratio calculated
  • For funding arb: current funding rate and 30-day history obtained

Output Validation

  • Entry level defined with z-score or %B justification
  • Exit (take-profit) level defined at z approximately ±0.5
  • Stop-loss defined at z approximately ±3.5 or equivalent dollar amount
  • Time-based exit set at 3x half-life
  • Risk management validated — sized per Risk Management
  • Dollar risk stated explicitly as % of portfolio
  • Regime check performed — strategy appropriate for current market
  • For pairs: both legs specified with hedge ratio and execution plan
  • For funding arb: annualized rate calculated, risks documented

Example

User: “BTC and ETH seem to have diverged recently. Is there a pairs trade here?”

Analysis:

## Pairs Trade Analysis: BTC / ETH

### Cointegration Test
- Data: 365 daily closes for BTC and ETH
- Regression: ETH = 142.5 + 0.054 × BTC + ε
- Hedge ratio (β): 0.054 (buy 1 ETH, short 0.054 BTC per unit)
- ADF test on residuals: t-stat = -3.42, p-value = 0.011
- Result: COINTEGRATED at 5% significance

### Statistical Properties
- Hurst exponent of spread: 0.38 → anti-persistent (mean-reverting)
- Half-life of reversion: 12 days → swing trade timeframe
- Max holding period: 36 days (3 × half-life)

### Current Spread Analysis
- BTC: $67,000, ETH: $3,500
- Spread = $3,500 - (0.054 × $67,000) = $3,500 - $3,618 = -$118
- Mean spread (60d): +$42
- StdDev spread (60d): $65
- Z-score: (-$118 - $42) / $65 = -2.46 → ENTRY ZONE

### Trade Setup
- Signal: z = -2.46 → Long spread (BUY ETH, SHORT 0.054 BTC per ETH)
- Entry: Current levels (z < -2.0)
- Take profit: z = -0.5 → spread at $42 - 0.5 × $65 = $9.50
  Expected profit per unit: -$118 → $9.50 = $127.50
- Stop-loss: z = -3.5 → spread at $42 - 3.5 × $65 = -$185.50
  Max loss per unit: -$118 → -$185.50 = $67.50
- R:R = $127.50 / $67.50 = 1.89:1
- Time stop: 36 days

### Position Sizing (per Risk Management)
- Portfolio: $100,000
- Risk per trade: 1% = $1,000
- Risk per spread unit: $67.50
- Spread units: $1,000 / $67.50 = 14.8 → 14 units
- Long: 14 ETH at $3,500 = $49,000
- Short: 14 × 0.054 = 0.756 BTC at $67,000 = $50,652
- Approximately dollar-neutral
- Portfolio exposure: ~50% gross → within limits for a hedged trade

### Risk Check
- Cointegration confirmed (p = 0.011)
- Hurst = 0.38 (mean-reverting)
- z-score in entry zone (-2.46)
- R:R = 1.89:1
- Time stop set (36 days)
- Dollar risk = $1,000 (1%)
- Re-test cointegration in 30 days

### Verdict
ENTER PAIRS TRADE: Long 14 ETH / Short 0.756 BTC
Expected reversion in ~12 days (half-life).
Monitor spread daily. Exit if z crosses -0.5 or after 36 days.