Agent skill

Mean Reversion

by agiprolabs in agiprolabs/claude-trading-skills

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

MITAuto-check passedBusiness, Finance & HR

Install Mean Reversion

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill mean-reversion -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills mean-reversion --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/mean-reversion .claude/skills/mean-reversion && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
mean-reversion
GitHub stars
410
Token cost
~2.5k tokens
SKILL.md length
772 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

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

  • Works in 3 steps: Augmented Dickey-Fuller (ADF) Test → Hurst Exponent → Variance Ratio Test
  • Business, Finance & HR work in your project
  • SKILL.md covers When Mean Reversion Works, When Mean Reversion Fails, Testing for Mean Reversion and Half-Life Estimation, plus 7 more sections
  • Runs Python scripts from its folder; calls python; needs BIRDEYE_API_KEY

What it does

Mean Reversion is an agent skill from agiprolabs/claude-trading-skills. Mean-reversion strategy tools including Hurst exponent, half-life estimation, z-score signals, ADF testing, and Ornstein-Uhlenbeck modeling

Its SKILL.md is about 2.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/statistical_tests.md`, `references/strategy_design.md` and `scripts/mean_reversion_test.py`).

It sits in Business, Finance & HR. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

When your agent uses it

  • Business, Finance & HR work in your project

Example prompts

  • “/mean-reversion”

Requirements

  • Python 3
  • A credential in BIRDEYE_API_KEY

Workflow steps

3 steps, taken from the step headings in SKILL.md.

  1. Augmented Dickey-Fuller (ADF) Test
  2. Hurst Exponent
  3. Variance Ratio Test

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 2 files in scripts/ (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • python

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • BIRDEYE_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Mean Reversion loads about 2.5k tokens when it runs, and up to ~6.5k if it reads all its reference files. Until then it costs about 39 tokens; SKILL.md has 772 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~39
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 772 words, ~2,487 tokens.

Download SKILL.mdSave it as .claude/skills/mean-reversion/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
mean-reversion
description
Mean-reversion strategy tools including Hurst exponent, half-life estimation, z-score signals, ADF testing, and Ornstein-Uhlenbeck modeling

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).

python
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 ValueInterpretationTrading Implication
H < 0.5Mean-revertingTrade mean reversion
H = 0.5Random walkNo edge
H > 0.5TrendingTrade momentum
python
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)
python
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

python
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
ParameterRule of Thumb
Lookback window2x half-life
Holding period1x half-life
Maximum hold3x half-life (stop)
Signal recalc0.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
ConditionSignalAction
z < -2.0BuyEnter long (price below mean)
z > +2.0SellEnter short (price above mean)
z crosses 0ExitClose position (returned to mean)
abs(z) > 3.0StopClose position (reversion failed)
Lookback Window

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

python
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:

python
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
ParameterMeaningEstimation
thetaSpeed of mean reversionFrom AR(1) beta: theta = -ln(1+beta)/dt
muLong-run meanFrom AR(1) intercept: mu = -alpha/beta
sigmaVolatility of innovationsResidual std from AR(1)
Parameter Estimation
python
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

Show full SKILL.md (321 more words)Show less
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

SkillIntegration
cointegration-analysisFind cointegrated pairs for pairs trading
pandas-taRSI, Bollinger Bands as mean-reversion indicators
regime-detectionFilter: only trade MR in ranging regimes
vectorbtBacktest mean-reversion strategies
volatility-modelingEstimate sigma for OU model
slippage-modelingFactor execution costs into P&L estimates
position-sizingSize 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

bash
# 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.

© agiprolabs, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (scripts, references) in skills/mean-reversion of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/statistical_tests.md
  • references/strategy_design.md
  • scripts/mean_reversion_test.py
  • scripts/pairs_scanner.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Mean Reversion next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Mean Reversion compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Mean Reversion this skillagiprolabs/claude-trading-skills410—~2.5kAutomated safety check: PassMIT
Technical Analysttradermonty/claude-trading-skills3k4 repos~4.6kAutomated safety check: PassMIT
Theme Detectortradermonty/claude-trading-skills3k2 repos~4.9kAutomated safety check: PassMIT
Creating Financial ModelsChen-zexi/open-ptc-agent7293 repos~1.3kAutomated safety check: PassMIT
Stock APIzhangxiangliang/stock-api2k—~507Automated safety check: PassMIT
Itr Walakaranb192/itr-wala871—~3.6kAutomated safety check: PassMIT

Similar skills

  • Technical Analyst

    tradermonty/claude-trading-skills

    This skill should be used when analyzing weekly price charts for stocks, stock indices, cryptocurrencies, or forex pairs.

    3k GitHub starsUsed in 4 repos~4.6k tokens
    Business, Finance & HRAuto-check passed
  • Theme Detector

    tradermonty/claude-trading-skills

    Detect and analyze trending market themes across sectors. An agent skill from tradermonty/claude-trading-skills.

    3k GitHub starsUsed in 2 repos~4.9k tokens
    Business, Finance & HRAuto-check passed
  • Creating Financial Models

    Chen-zexi/open-ptc-agent

    This skill provides an advanced financial modeling suite with DCF analysis, sensitivity testing, Monte Carlo simulations, and scenario planning for investment decisions

    729 GitHub starsUsed in 3 repos~1.3k tokens
    Business, Finance & HRAuto-check passed
  • Stock API

    zhangxiangliang/stock-api

    Fetch real-time stock quotes, K-line (candlestick) history, and search symbols for China A-shares, Hong Kong, and US markets.

    2k GitHub stars~507 tokensUpdated yesterday
    Business, Finance & HRAuto-check passed
  • Itr Wala

    karanb192/itr-wala

    File Indian income tax returns (ITR) for FY 2025-26 / AY 2026-27.

    871 GitHub stars~3.6k tokensUpdated 5 days ago
    Business, Finance & HRAuto-check passed
  • Tushare Data

    zillionare/zillionare

    面向中文自然语言的 Tushare 数据研究技能。用于把“看看这只股票最近怎么样”“帮我查财报趋势”“最近哪个板块最强”“北向资金在买什么”“给我导出一份行情数据”这类请求,转成可执行的数据获取、清洗、对比、筛选、导出与简要分析流程。适用于 A 股、指数、ETF/基金、财务、估值、资金流、公告新闻、板块概念与宏观数据等研究场景。

    321 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Backtrader

    agiprolabs/claude-trading-skills

    Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Cointegration Analysis

    agiprolabs/claude-trading-skills

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

    410 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Mean Reversion

What does Mean Reversion do?

Mean-reversion strategy tools including Hurst exponent, half-life estimation, z-score signals, ADF testing, and Ornstein-Uhlenbeck modeling. Mean Reversion is an agent skill from agiprolabs/claude-trading-skills.

When should I use Mean Reversion?

Mean Reversion fits situations like: business, Finance & HR work in your project.

How do I install Mean Reversion in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill mean-reversion -a claude-code`. Or copy the skill folder (skills/mean-reversion in agiprolabs/claude-trading-skills) into .claude/skills/mean-reversion in your project. Claude Code loads it when a task matches its description.

How do I install Mean Reversion in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill mean-reversion -a codex`. Or copy the skill folder (skills/mean-reversion in agiprolabs/claude-trading-skills) into .agents/skills/mean-reversion in your project. Codex loads it when a task matches its description.

Can I use Mean Reversion in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agiprolabs/claude-trading-skills --skill mean-reversion -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/mean-reversion, .gemini/skills/mean-reversion, .github/skills/mean-reversion and .opencode/skills/mean-reversion in your project.

What does Mean Reversion need to run?

Going by SKILL.md and its folder, Mean Reversion needs Python for the scripts in its folder, the command-line tools its instructions call (python) and credentials named BIRDEYE_API_KEY. Our summary lists: Python 3; A credential in BIRDEYE_API_KEY.

Does Mean Reversion access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Mean Reversion safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Mean Reversion use?

Mean Reversion is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Mean Reversion use?

About 2.5k tokens (SKILL.md is roughly 9.9k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4k tokens, read only when the agent opens those files.

What are the alternatives to Mean Reversion?

Skills that share tags, products or a category with Mean Reversion: Technical Analyst (tradermonty/claude-trading-skills, 3k stars), Theme Detector (tradermonty/claude-trading-skills, 3k stars), Creating Financial Models (Chen-zexi/open-ptc-agent, 729 stars) and Stock API (zhangxiangliang/stock-api, 2k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Mean Reversion?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.