mean-reversion
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMean 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
- 区间震荡市场:有明确支撑/阻力位的横盘走势
- 配对价差:协整资产之间的价差会回归至均衡水平
- 超卖/超买极值:平稳序列中RSI、布林带或z-score达到极值
- 资金费率套利:永续合约资金费率回归至基准水平
- 稳定币脱钩:经典的均值回归机会(挂钩价=已知均值)
- 暴跌后修复:PumpFun初始拉盘后的短暂均值回归窗口
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
1. 增广迪基-富勒(ADF)检验
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
检验序列存在单位根(非平稳)的原假设。
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:强烈表明序列平稳
- p < 0.05:表明序列平稳
- p > 0.10:无法拒绝单位根假设——序列大概率非平稳
2. Hurst Exponent
2. Hurst指数
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 |
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衡量时间序列的长期依赖性。
| Hurst值 | 解释 | 交易启示 |
|---|---|---|
| H < 0.5 | 均值回归型 | 采用均值回归策略 |
| H = 0.5 | 随机游走 | 无交易优势 |
| H > 0.5 | 趋势型 | 采用动量策略 |
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
pass3. Variance Ratio Test
3. 方差比检验
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 for complete implementations and interpretation guides.
references/statistical_tests.md比较多期收益率方差与单期收益率方差的比值。
- VR < 1:负自相关(均值回归型)
- VR = 1:随机游走
- VR > 1:正自相关(趋势型)
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)完整实现及解读指南请参考。
references/statistical_tests.mdHalf-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
AR(1)回归法
Fit the autoregressive model:
delta_X_t = alpha + beta * X_{t-1} + epsilonpython
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)拟合自回归模型:
delta_X_t = alpha + beta * X_{t-1} + epsilonpython
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 |
| 参数 | 经验法则 |
|---|---|
| 回溯窗口 | 2倍半衰期 |
| 持有周期 | 1倍半衰期 |
| 最大持有时间 | 3倍半衰期(止损) |
| 信号重算周期 | 0.5倍半衰期 |
Z-Score Signal Framework
Z-Score信号框架
The z-score normalizes the deviation from the mean, providing standardized entry/exit signals.
z = (price - rolling_mean) / rolling_stdZ-score将偏离均值的幅度标准化,提供标准化的进场/离场信号。
z = (price - rolling_mean) / rolling_stdSignal 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) |
| 条件 | 信号 | 操作 |
|---|---|---|
| z < -2.0 | 买入 | 做多(价格低于均值) |
| z > +2.0 | 卖出 | 做空(价格高于均值) |
| z穿越0 | 离场 | 平仓(回归至均值) |
| abs(z) > 3.0 | 止损 | 平仓(回归失败) |
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
...将滚动窗口设置为约2倍半衰期:
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
基于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 for complete entry/exit framework and sizing.
references/strategy_design.md根据Z-score的幅度调整仓位大小,以获得更优的风险调整收益:
python
size = base_size * min(abs(z) / entry_threshold, max_scale)完整的进场/离场框架及仓位管理请参考。
references/strategy_design.mdOrnstein-Uhlenbeck (OU) Process
Ornstein-Uhlenbeck (OU)过程
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) |
OU过程是均值回归的连续时间模型:
dX = theta * (mu - X) * dt + sigma * dW| 参数 | 含义 | 估计方法 |
|---|---|---|
| theta | 均值回归速度 | 由AR(1)的beta计算:theta = -ln(1+beta)/dt |
| mu | 长期均值 | 由AR(1)的截距计算:mu = -alpha/beta |
| sigma | 创新项波动率 | 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,
}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
策略类型
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
将z-score框架直接应用于代币价格序列。最适用于:
- 稳定币(USDC/USDT价差)
- 处于明确区间的代币
- 经ADF检验确认平稳的序列
Pairs Trading
配对交易
Trade the spread between two cointegrated assets:
- Confirm cointegration (see skill)
cointegration-analysis - Compute spread:
S = Y - beta * X - Apply z-score framework to the spread
- Go long spread (buy Y, sell X) when z < -2
- Go short spread (sell Y, buy X) when z > +2
交易两个协整资产之间的价差:
- 确认协整关系(参考技能)
cointegration-analysis - 计算价差:
S = Y - beta * X - 对价差应用z-score框架
- 当z < -2时,做多价差(买入Y,卖出X)
- 当z > +2时,做空价差(卖出Y,买入X)
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)
配对交易的多资产扩展版本:
- 从相关资产的PCA中提取特征投资组合
- 交易最小特征值的投资组合(最具均值回归性)
- 需要较大的资产池(10种以上资产)
Crypto-Specific Considerations
加密货币专属考量
- Most crypto trends: Hurst exponent for BTC, ETH, SOL is typically 0.55-0.70. Raw price mean reversion is rare.
- 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
- Short lookbacks: Crypto mean reversion has short half-lives (hours to days, not weeks)
- Transaction costs: DEX swap fees (0.25-1%) can eat mean-reversion profits. Factor in slippage.
- Regime awareness: Use skill to only trade mean reversion in ranging regimes.
regime-detection
- 多数加密货币呈趋势性:BTC、ETH、SOL的Hurst指数通常在0.55-0.70之间,原始价格的均值回归现象罕见。
- 均值回归机会的来源:
- 配对价差(SOL/ETH比值、BTC dominance)
- 永续合约资金费率
- 现货与期货的基差
- 稳定币脱钩
- DEX间的手续费层级价差
- 短回溯窗口:加密货币的均值回归半衰期较短(数小时至数天,而非数周)
- 交易成本:DEX的滑点手续费(0.25-1%)可能吞噬均值回归利润,需将滑点纳入考量。
- 市场结构识别:使用技能,仅在区间震荡市场中进行均值回归交易。
regime-detection
Integration with Other Skills
与其他技能的集成
| Skill | Integration |
|---|---|
| Find cointegrated pairs for pairs trading |
| RSI, Bollinger Bands as mean-reversion indicators |
| Filter: only trade MR in ranging regimes |
| Backtest mean-reversion strategies |
| Estimate sigma for OU model |
| Factor execution costs into P&L estimates |
| Size positions using Kelly + z-score scaling |
| 技能 | 集成方式 |
|---|---|
| 寻找适合配对交易的协整资产对 |
| 将RSI、布林带作为均值回归指标 |
| 过滤:仅在区间震荡市场中进行均值回归交易 |
| 回测均值回归策略 |
| 为OU模型估计sigma参数 |
| 将执行成本纳入损益估算 |
| 结合Kelly准则与z-score缩放进行仓位管理 |
Files
文件
References
参考文档
- -- ADF, Hurst exponent, variance ratio, and half-life estimation with full implementations and interpretation
references/statistical_tests.md - -- Z-score framework, position sizing, pairs trading setup, risk management, and backtest considerations
references/strategy_design.md
- -- ADF检验、Hurst指数、方差比检验、半衰期估计的完整实现及解读
references/statistical_tests.md - -- Z-score框架、仓位管理、配对交易设置、风险管理及回测考量
references/strategy_design.md
Scripts
脚本
- -- Comprehensive mean-reversion analysis: ADF, Hurst, variance ratio, half-life, OU estimation, z-score signals
scripts/mean_reversion_test.py - -- Scan multiple assets for mean-reverting pairs: correlation, cointegration, spread analysis, ranking
scripts/pairs_scanner.py
- -- 全面的均值回归分析:ADF检验、Hurst指数、方差比检验、半衰期、OU参数估计、z-score信号生成
scripts/mean_reversion_test.py - -- 扫描多资产以寻找均值回归型资产对:相关性分析、协整检验、价差分析、排名
scripts/pairs_scanner.py
Quick Start
快速开始
bash
undefinedbash
undefinedRun mean-reversion analysis on synthetic data
对合成数据进行均值回归分析
python scripts/mean_reversion_test.py --demo
python scripts/mean_reversion_test.py --demo
Scan for mean-reverting pairs
扫描均值回归型资产对
python scripts/pairs_scanner.py --demo
python scripts/pairs_scanner.py --demo
Analyze a specific token (requires BIRDEYE_API_KEY)
分析特定代币(需要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.*BIRDEYE_API_KEY=your_key TOKEN_MINT=So11...1 python scripts/mean_reversion_test.py
*本技能仅提供分析工具及信息,不构成财务建议或交易推荐。*