Statistical Mean-Reversion Engine [SMRE]## Statistical Mean-Reversion Engine (SMRE)
SMRE is an open-source mean-reversion indicator that combines a rigorous statistical core with up to eight optional confirmation layers, designed primarily for index-futures trading on intraday timeframes (1-minute through 1-hour).
### What it does
For every bar, SMRE fits an Ornstein-Uhlenbeck (OU) process to the recent price series via linear regression on lag-1 prices, yielding four outputs:
- **μ (the mean)** — the equilibrium price the series is reverting to
- **θ (mean-reversion speed)** — how strongly the series pulls back to μ
- **HL (half-life)** — how many bars it takes to revert halfway
- **σ_eq (stationary residual variance)** — used to z-score the current price
The current price's z-score against μ (the "OU Z") is the primary signal. When |OU Z| exceeds a configurable threshold, a mean-reversion entry is considered — but only after the script also confirms that the recent price series is genuinely stationary using three orthogonal statistical tests:
- **Hurst exponent** must be below 0.55 (i.e., the series is not persistently trending)
- **Augmented Dickey-Fuller** t-statistic must be below -2.86 (rejects unit root)
- **Variance Ratio** test at q=4 must be below 1.0 (variance grows sub-linearly with horizon)
If all four conditions pass, the L1 (statistical core) signal fires.
### Why the multi-layer structure (mashup justification)
A single OU-based mean-reversion signal works well in stationary regimes but degrades in trending or volatile conditions. SMRE addresses this by validating each potential entry through up to eight orthogonal confirmation channels, each measuring something the others do not:
- **L2 — Volatility Regime (6-state):** Classifies market state via VIX, ADX, and realized volatility. Suppresses signals during high-trend conditions (regime 6, "Spike") where mean-reversion historically fails.
- **L3 — Spot-Futures Basis (Kalman filter):** Tracks the deviation between actual and theoretical futures pricing. Statistically significant basis dislocations often resolve via mean-reversion.
- **L4 — Options Surface:** Computes ATM implied volatility from straddle pricing and a skew z-score from OTM put/call ratio. Optional; requires user to provide option symbols.
- **L5 — Microstructure:** Blends rolling VWAP and session-anchored VWAP z-scores with VPIN (a volume-clock toxicity proxy) and order-flow imbalance. Captures flow-based exhaustion.
- **L6 — Gamma Walls (GEX) OR Put-Call Ratio:** Two mutually exclusive options. GEX requires OI symbols at five strikes; PCR requires a single broker-published PCR feed. Both detect option-driven price magnets.
- **L7 — Dispersion:** Rolling correlation of index returns with its top 5 constituent stocks' returns. High dispersion (low correlation) penalizes signals; high cohesion boosts them.
- **L7b — Residual Dispersion:** Idiosyncratic residual z-scores (β-adjusted) per constituent. If 3 of 5 stocks show same-sign extreme residuals, the index is detached from constituents — strong mean-reversion candidate.
- **L9 — Cross-Asset Stress:** Sigma-normalized stress across USD/INR, DXY, and crude oil. Penalizes signals during cross-asset hedging cascades.
Each layer outputs a {direction, strength} pair. The Layer 8 fusion engine combines these via a weighted composite score (default weights: L1=0.28, L5=0.22, L3=0.18, L4=0.12, L6/L7b=0.10), then applies a regime multiplier (L2 × L7 × VRP × cross-asset × expiry), clamped to to prevent extreme compounding.
If the absolute composite score crosses one of three thresholds (0.25 / 0.40 / 0.45 by default), a signal is fired at Scalp / Swing / Session horizon respectively. A TCA cost filter then validates that the expected move (distance to μ) exceeds estimated round-trip transaction cost; otherwise the signal is suppressed.
### Originality
The author is not aware of any other public Pine script that implements the full OU-fit chain (mean, mean-reversion speed, half-life, stationary variance) together with all three stationarity tests (Hurst, ADF, Variance Ratio) directly in Pine v6 — every step is computed natively, no external library calls. Additionally, the session-anchored VWAP with running volume-weighted sigma bands, the rolling-beta residual dispersion across multiple constituents, and the Kalman-filtered futures-basis residual are original Pine implementations. The signal telemetry module (a 200-signal FIFO ring buffer with horizon × composite-magnitude bucket attribution) is also an original diagnostic tool.
### How to use
1. **Apply to an index futures chart.** Defaults are pre-configured for NSE NIFTY1! futures, but inputs allow any index — change the VIX symbol, spot/futures symbols, constituent symbols, and currency pairs.
2. **Read the compact dashboard.** It's a single 9-row table (default position: middle-right) showing only what you need to evaluate a setup:
| Row | What it shows | What it means |
|---|---|---|
| Title | Profile + OU window in use | Confirms which calibration is active |
| OU Z-Score | Z-score with half-life (HL) | How extended price is + how long mean-reversion typically takes |
| Stat Validity | H / ADF / VR pass-fail | Whether the recent series is actually stationary (all 3 must pass) |
| Regime | Volatility state + VIX value | Whether market conditions favor mean-reversion |
| Composite | Fused score × regime multiplier | The unified signal strength |
| Confluence | Layers agreeing (out of 6) | How many orthogonal signals support the direction |
| TCA Edge | Expected move in bps + PASS/FAIL | Whether the trade clears transaction costs |
| E / SL / TP | Entry, Stop, Target + Risk:Reward | The trade levels if a signal fires |
| **DECISION** | Direction · Horizon · Side | The actionable output (green=long, red=short, gray=neutral) |
3. **Trade levels and markers.** When a signal fires, entry/stop/target lines auto-plot on the chart. Stop is ATR-based (default 1.2× ATR); target is min(OU mean μ, entry + 2× ATR). Triangle markers plot below (long) or above (short) the bar — small for Scalp, medium for Swing, large for Session.
4. **Optional diagnostic.** A separate Signal Telemetry table (disabled by default; enable via the "Show Telemetry Dashboard" input) tracks the last 200 signals' outcomes (win = price touched μ, loss = stop hit, expired = timeout) and reports hit rate by horizon × composite-magnitude bucket. This is a backward-looking diagnostic, not a backtest.
### Recommended chart and timeframe
This indicator was developed and parameter-tested primarily on NIFTY1! futures. The OU window auto-mapping (1m→32, 2m→20, 5m→12, 15m→32, 30m→20, 1h→24) was selected empirically through parameter sweeps. Users on other instruments should expect to tune the OU window manually or accept the auto-mapped default as a starting point.
The indicator works on any timeframe between 1 minute and daily, though intraday timeframes (1m through 1h) are where the multi-layer confluence adds the most value.
### Important notes
- This is an **indicator**, not a strategy — no backtest equity curve is produced. The telemetry table is a descriptive measure of recent signal outcomes only.
- Many layers are **optional**. If you don't have symbols for options OI, just leave those inputs blank; the script will redistribute composite weight naturally across the active layers.
- Signals can fluctuate intra-bar before bar close, especially in real-time mode. For consistent behavior, evaluate signals on closed bars only.
- The default constituents (top-5 NIFTY weights) need to be changed in the L7 inputs to use this on a different index.
### Disclaimer
This indicator is published for educational and research purposes only. It is not financial advice, not an investment recommendation, and not a solicitation to trade. Past behavior of signals does not guarantee future results. Trading futures, options, and equities carries substantial risk of loss. You are solely responsible for your trading decisions. The author makes no representations about the accuracy, completeness, or suitability of this indicator for any particular purpose. Use at your own risk, and always consult a qualified financial professional before trading.
Pine Script® indicator

