OPEN-SOURCE SCRIPT

Statistical Reversion Engine [JOAT]

1 018
Statistical Reversion Engine [JOAT]

Introduction

The Statistical Reversion Engine (SRE) is an advanced open-source mean reversion indicator that combines statistical deviation bands, premium/discount zone analysis, DCA level calculation, Z-score measurement, and enhanced reversion probability scoring to identify high-probability mean reversion opportunities. This indicator quantifies price deviation from statistical mean using multiple calculation methods (SMA, EMA, VWAP, HMA) and provides probabilistic assessment of reversion likelihood through multi-factor analysis including deviation magnitude, volatility regime, and historical reversion patterns.

Unlike basic Bollinger Band indicators that simply plot standard deviation bands, SRE employs a sophisticated statistical framework that calculates Z-scores, premium/discount percentages, enhanced reversion probability (incorporating volatility and premium factors), and tracks historical reversion speed to provide traders with quantitative mean reversion intelligence. The indicator also generates DCA (Dollar Cost Averaging) levels with volatility-adjusted spacing for systematic position building.

快照

Why This Indicator Exists

This indicator addresses the challenge of identifying when price has deviated sufficiently from mean to warrant mean reversion trades. Traditional mean reversion indicators lack probabilistic quantification and don't account for volatility regime or historical reversion patterns. SRE systematically reveals:

  • Multiple Mean Calculations: SMA, EMA, VWAP (session/continuous), HMA for flexible mean definition
  • Statistical Deviation Bands: 1σ, 2σ, 3σ bands with customizable multipliers
  • Z-Score Calculation: Quantifies deviation in standard deviation units
  • Premium/Discount Analysis: Percentage deviation from mean with zone classification
  • Enhanced Reversion Probability: Multi-factor scoring (Z-score + premium + volatility)
  • DCA Level Generation: Volatility-adjusted levels for systematic position building
  • Historical Reversion Tracking: Measures average bars to return to mean after extreme deviation


Each component provides unique intelligence. Mean calculation defines center, deviation bands show extremes, Z-score quantifies magnitude, premium/discount shows percentage, probability scores likelihood, DCA levels provide entry framework, and historical tracking provides context.

Core Components Explained

1. Flexible Mean Calculation System

SRE supports four mean calculation methods:

Pine Script®
f_calculate_mean(string type, int length) => float result = close if type == "SMA" result := ta.sma(close, length) else if type == "EMA" result := ta.ema(close, length) else if type == "VWAP" result := session_reset ? ta.vwap(hlc3) : ta.vwma(hlc3, length) else if type == "HMA" result := ta.hma(close, length) result


Mean selection impacts reversion behavior:
- SMA: Simple average, slower to respond
- EMA: Exponential weighting, faster response
- VWAP: Volume-weighted, institutional reference
- HMA: Hull Moving Average, smoothest with minimal lag

2. Statistical Deviation Band System

Three deviation bands calculated using standard deviation:

Pine Script®
float mean_line = f_calculate_mean(mean_type, mean_length) float stdev = f_calculate_stdev(close, deviation_period) float upper_band_1 = mean_line + (stdev * band_multiplier_1) // 1σ float lower_band_1 = mean_line - (stdev * band_multiplier_1) float upper_band_2 = mean_line + (stdev * band_multiplier_2) // 2σ float lower_band_2 = mean_line - (stdev * band_multiplier_2) float upper_band_3 = mean_line + (stdev * band_multiplier_3) // 3σ float lower_band_3 = mean_line - (stdev * band_multiplier_3)


Default multipliers: 1.0, 2.0, 3.0 (customizable)
- 1σ: 68% of price action (normal range)
- 2σ: 95% of price action (extended range)
- 3σ: 99.7% of price action (extreme range)

3. Z-Score Calculation & Classification

Z-score quantifies deviation in standard deviation units:

Pine Script®
f_calculate_zscore(float price, float mean, float stdev) => float zscore = stdev > 0 ? (price - mean) / stdev : 0.0 zscore float zscore = f_calculate_zscore(close, mean_line, stdev)


Z-score interpretation:
- |Z| < 1.0: Normal deviation (40% reversion probability)
- |Z| 1.0-1.5: Moderate deviation (60% reversion probability)
- |Z| 1.5-2.0: Extended deviation (75% reversion probability)
- |Z| 2.0-2.5: Extreme deviation (85% reversion probability)
- |Z| > 3.0: 3-sigma event (95% reversion probability)

4. Premium/Discount Zone Analysis

Percentage deviation from mean with zone classification:

Pine Script®
f_calculate_premium_discount(float price, float mean) => float pct = mean > 0 ? ((price - mean) / mean) * 100 : 0.0 pct float premium_discount_pct = f_calculate_premium_discount(close, mean_line) string current_zone = premium_discount_pct >= premium_threshold * 2 ? "Extreme Premium" : premium_discount_pct >= premium_threshold ? "Premium" : premium_discount_pct <= discount_threshold * 2 ? "Extreme Discount" : premium_discount_pct <= discount_threshold ? "Discount" : "Fair Value"


Zone classification (default thresholds):
- Extreme Premium: >3.0% above mean (strong sell zone)
- Premium: 1.5-3.0% above mean (sell zone)
- Fair Value: -1.5% to +1.5% (neutral zone)
- Discount: -3.0% to -1.5% below mean (buy zone)
- Extreme Discount: <-3.0% below mean (strong buy zone)

5. Enhanced Reversion Probability Scoring

Multi-factor probability calculation:

Pine Script®
f_enhanced_reversion_prob(float z, float premium_pct, float vol_rank) => float base_prob = f_reversion_probability(z) // Adjust for premium/discount magnitude float premium_factor = math.abs(premium_pct) > 3 ? 1.2 : math.abs(premium_pct) > 2 ? 1.1 : math.abs(premium_pct) > 1 ? 1.0 : 0.9 // Adjust for volatility (lower vol = higher reversion probability) float vol_factor = vol_rank < 30 ? 1.2 : vol_rank < 50 ? 1.1 : vol_rank < 70 ? 1.0 : 0.85 math.min(base_prob * premium_factor * vol_factor, 99)


Enhanced probability accounts for:
- Base Z-score probability
- Premium/discount magnitude (larger deviation = higher probability)
- Volatility regime (lower volatility = more predictable reversion)

6. Volatility-Adjusted DCA Level Generation

DCA levels automatically adjust spacing based on volatility:

Pine Script®
float current_atr = ta.atr(14) float atr_pct = close > 0 ? (current_atr / close) * 100 : 0 float vol_multiplier = atr_pct > 3 ? 1.5 : atr_pct > 2 ? 1.2 : atr_pct > 1 ? 1.0 : 0.8 for i = 1 to dca_levels float adjusted_spacing = (dca_spacing * vol_multiplier) / 100 float buy_level = mean_line * (1 - adjusted_spacing * i) float sell_level = mean_line * (1 + adjusted_spacing * i) array.push(dca_buy_levels, buy_level) array.push(dca_sell_levels, sell_level)


Volatility adjustment:
- High vol (ATR% >3): 1.5x spacing (wider levels)
- Elevated vol (ATR% 2-3): 1.2x spacing
- Normal vol (ATR% 1-2): 1.0x spacing (default)
- Low vol (ATR% <1): 0.8x spacing (tighter levels)

7. Historical Reversion Speed Tracking

Measures average bars to return to mean after extreme deviation:

Pine Script®
var array<int> reversion_times = array.new_int(0) var bool tracking_reversion = false var int reversion_start_bar = 0 if math.abs(zscore) >= 2.5 and not tracking_reversion tracking_reversion := true reversion_start_bar := bar_index if tracking_reversion and math.abs(zscore) < 0.5 int reversion_time = bar_index - reversion_start_bar array.push(reversion_times, reversion_time) tracking_reversion := false float avg_reversion_time = array.size(reversion_times) > 0 ? array.avg(reversion_times) : na


Average reversion time provides context for expected holding period.

快照

Visual Elements

  • Mean Line: Electric lime line showing statistical mean
  • Deviation Bands: 1σ (lime), 2σ (violet), 3σ (deep violet) with gradient fills
  • Premium/Discount Zones: Background coloring (violet for premium, lime for discount)
  • DCA Levels: Dotted lines with "B1, B2, B3..." (buy) and "S1, S2, S3..." (sell) labels
  • Z-Score Label: Current Z-score displayed on price
  • Gradient Zone Fills: Progressive transparency between bands
  • Mean Reversion Signals: Triangle markers for strong buy/sell setups
  • Reversion Probability Heatmap: Background intensity based on enhanced probability
  • Dashboard: Real-time metrics including zone, P/D%, Z-score, reversion probability, mean value, distance, enhanced probability, deviation percentile, mean trend, nearest DCA, average reversion time, bars since extreme


Input Parameters

Mean Calculation:
  • Mean Type: SMA, EMA, VWAP, HMA (default: VWAP)
  • Mean Length: Period for mean calculation (default: 20)
  • Session Reset (VWAP): Toggle session anchoring (default: true)


Deviation Bands:
  • Band 1 Multiplier: 1σ multiplier (default: 1.0)
  • Band 2 Multiplier: 2σ multiplier (default: 2.0)
  • Band 3 Multiplier: 3σ multiplier (default: 3.0)
  • Deviation Period: Standard deviation calculation period (default: 20)


Premium/Discount:
  • Premium Threshold (%): Threshold for premium zone (default: 1.5%)
  • Discount Threshold (%): Threshold for discount zone (default: -1.5%)


DCA Levels:
  • Enable DCA Levels: Toggle DCA display (default: true)
  • Number of DCA Levels: Levels to generate (default: 5)
  • DCA Spacing (%): Base spacing between levels (default: 1.5%)


Visualization:
  • Show Deviation Bands: Toggle band display (default: true)
  • Show Band Fills: Toggle gradient fills (default: true)
  • Show Premium/Discount Zones: Toggle background coloring (default: true)
  • Show Z-Score Label: Toggle Z-score display (default: true)


How to Use This Indicator

Step 1: Identify Current Zone
Check dashboard "Zone" row. Extreme Discount = strong buy zone, Extreme Premium = strong sell zone.

Step 2: Assess Z-Score Magnitude
|Z| >2.0 indicates extended deviation. |Z| >3.0 is 3-sigma event (rare, high reversion probability).

Step 3: Check Enhanced Reversion Probability
Dashboard shows enhanced probability accounting for volatility and premium factors. >80% is high probability.

Step 4: Monitor Mean Trend
"Rising" mean suggests uptrend, "Falling" suggests downtrend. Trade with mean trend for higher probability.

Step 5: Use DCA Levels for Entry
Enter positions at DCA levels (B1, B2, B3 for longs; S1, S2, S3 for shorts) to average into position.

Step 6: Wait for Strong Signals
Triangle markers appear when:
- Extreme zone + enhanced probability >80% + band crossover
- These are highest conviction mean reversion setups

快照

Best Practices

  • Mean reversion works best in ranging markets - avoid strong trends
  • 3-sigma events (|Z| >3.0) have highest reversion probability but occur rarely
  • Use DCA levels to build positions systematically rather than all-in entries
  • Enhanced probability >80% indicates high-quality setup
  • Mean trend provides context - reversion against trend is lower probability
  • Volatility-adjusted DCA spacing prevents over-concentration in high vol
  • Average reversion time helps set realistic profit target timeframes
  • Combine with higher timeframe trend - mean reversion with trend is safer
  • Deviation percentile >90% indicates extreme deviation
  • Bars since extreme >50 suggests extended deviation may persist


Indicator Limitations

  • Mean reversion fails during strong trending markets
  • 3-sigma events can persist longer than expected during major news
  • DCA levels don't account for fundamental catalysts
  • Enhanced probability is statistical, not deterministic
  • Historical reversion time doesn't guarantee future reversion speed
  • VWAP mean resets daily - may not be appropriate for all timeframes
  • Standard deviation assumes normal distribution - markets have fat tails
  • Premium/discount thresholds may need adjustment for different instruments


Technical Implementation

Built with Pine Script v6 using:
  • Four mean calculation methods (SMA, EMA, VWAP, HMA)
  • Three-tier deviation band system with customizable multipliers
  • Z-score calculation with standard deviation
  • Premium/discount percentage with zone classification
  • Enhanced reversion probability (Z-score + premium + volatility)
  • Volatility-adjusted DCA level generation
  • Historical reversion speed tracking with arrays
  • Deviation percentile ranking
  • Mean trend detection (fast vs slow mean)
  • Gradient zone fills with progressive transparency
  • Reversion probability heatmap background
  • Comprehensive dashboard with 12 metrics


The code is fully open-source and can be modified to suit individual trading styles.

Originality Statement

This indicator is original in its comprehensive statistical mean reversion approach. While Bollinger Bands and mean reversion are established concepts, this indicator is justified because:

  • It combines four mean calculation methods with three-tier deviation bands
  • Enhanced reversion probability incorporates Z-score, premium magnitude, and volatility regime
  • Volatility-adjusted DCA level generation adapts to market conditions
  • Historical reversion speed tracking provides empirical context
  • Premium/discount zone classification adds percentage-based perspective
  • Mean trend detection (fast vs slow) provides directional context
  • Deviation percentile ranking shows historical extremity
  • Integration of statistical measures (Z-score, stdev, percentile) with practical tools (DCA levels, signals)


Each component contributes unique information: mean defines center, deviation bands show extremes, Z-score quantifies magnitude, premium/discount shows percentage, enhanced probability scores likelihood, DCA levels provide framework, historical tracking provides context, and mean trend shows direction. The indicator's value lies in presenting these complementary perspectives simultaneously with unified statistical framework.

Disclaimer

This indicator is provided for educational and informational purposes only. It is not financial advice. Mean reversion probabilities do not guarantee outcomes. Trading involves substantial risk of loss. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.

-Made with passion by officialjackofalltrades

免責聲明

這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。