OPEN-SOURCE SCRIPT

Adaptive Statistical Smoother [Pineify]

536
Adaptive Statistical Smoother [Pineify]

The Adaptive Statistical Smoother is an overlay trend-following indicator that combines a forward-backward zero-lag EMA approximation with an R-Squared trend filter to produce an adaptive moving average that tightly tracks price during trending markets and deliberately diverges during ranging conditions — solving the core problem of traditional moving averages that generate excessive whipsaw signals in sideways price action. Instead of using a fixed smoothing period or a single-pass EMA, the indicator first constructs a bidirectional (zero-phase-shift) EMA baseline that virtually eliminates the lag inherent in standard exponential averages, then modulates how closely the final adaptive MA follows this baseline based on the real-time R-Squared coefficient of determination. When R-Squared confirms a strong linear trend, the MA converges toward the zero-lag target proportionally to trend strength; when R-Squared indicates a ranging market, the MA actively pushes away from price in the last known trend direction, creating a natural buffer zone that suppresses false crossovers. Dynamic standard-deviation volatility bands and R-Squared-filtered buy/sell signals complete the system, giving traders a statistically grounded, self-adjusting trend tool with built-in noise rejection.

Key Features

  • Forward-backward zero-lag EMA approximation — a two-pass EMA computation (forward pass followed by a backward iteration over historical values) that closely approximates a bidirectional filter, virtually eliminating the phase lag that causes standard EMAs to react late to trend changes.

  • R-Squared adaptive trend filter — the Pearson correlation coefficient squared (R²) between price and bar index measures how well a linear trend fits recent data. Values above 0.5 indicate trending conditions; values below indicate ranging. This statistical metric drives the core adaptive behavior of the MA.

  • Dual-regime moving average — during trending markets (R² > 0.5), the adaptive MA blends toward the zero-lag target proportionally to R², tracking price closely. During ranging markets (R² ≤ 0.5), the MA diverges from price in the last known direction, creating a buffer that prevents whipsaw crossovers.

  • Dynamic volatility bands — standard deviation of the source price over the statistical window, scaled by a user-defined multiplier, creates upper and lower bands that automatically expand during volatile periods and contract during quiet ones.

  • R-Squared-filtered buy/sell signals — crossover signals between price and the adaptive MA are only generated when R² exceeds 0.3, ensuring signals fire only when there is statistically meaningful trend strength and suppressing noise during flat markets.

  • Trend-adaptive coloring — the MA line, volatility cloud fill, and bar colors all dynamically switch between bullish and bearish colors based on the current trend state, providing instant visual identification of the prevailing direction.


How It Works

The indicator follows a multi-stage calculation pipeline that transforms raw price data into an adaptive, statistically filtered trend line:

  1. Forward-backward zero-lag baseline: A standard EMA is first computed on the source price. Then a second pass iterates backward over the historical EMA values, applying the same EMA alpha (2 / (smooth + 1)) at each step across the lookback window. This two-pass approach approximates a zero-phase-shift filter — the resulting baseline tracks price turns almost immediately, without the half-period delay of a conventional EMA. This baseline serves as the "target" that the adaptive MA will converge toward when the market is trending.

  2. R-Squared trend detection: The Pearson correlation between closing prices and bar indices over the statistical window is squared to produce R². This coefficient of determination measures the proportion of price variance explained by a linear trend. R² near 1.0 means price is moving in a clean, directional manner; R² near 0.0 means price is oscillating without a clear direction. The 0.5 threshold divides the market into "trending" and "ranging" regimes.

  3. Adaptive MA computation: In trending mode (R² > 0.5), the adaptive MA is computed as a weighted blend: R² × target + (1 − R²) × previous MA. Stronger trends (higher R²) pull the MA closer to the zero-lag target; weaker trends allow it to lag slightly, providing natural smoothing. In ranging mode (R² ≤ 0.5), the MA moves away from price by the magnitude of the target's recent change, in the direction of the last known trend bias. This deliberate divergence creates separation between price and the MA, preventing the repeated false crossovers that plague fixed-parameter moving averages in choppy markets.

  4. Volatility bands and signal generation: Standard deviation bands are added around the adaptive MA to visualize the current volatility regime. Buy and sell signals are generated on price crossovers of the MA, but only when R² exceeds 0.3 — a secondary filter that ensures even the crossover signals carry minimum statistical trend evidence.


Trading Ideas and Insights

  • Trend-following entries with lag reduction: The zero-lag baseline allows the adaptive MA to respond to trend initiations significantly faster than a standard EMA of equivalent smoothing. When a BUY signal fires (price crosses above the MA with R² > 0.3), the entry is closer to the actual trend start than what a conventional moving average crossover would provide, improving the risk/reward ratio of trend-following trades.

  • Whipsaw avoidance in ranging markets: The adaptive divergence mechanism during low-R² periods is specifically designed to prevent the most common failure mode of moving average systems — repeated false crossovers during sideways consolidation. Traders can trust that when a signal does fire, the statistical environment supports a directional move.

  • Volatility band breakout confirmation: When price breaks above the upper band or below the lower band while the adaptive MA is already in the corresponding trend state, it confirms a high-volatility directional expansion. These breakouts can be used to add to existing positions or to set trailing stops at the opposite band.

  • R-Squared as a standalone filter: Even without acting on the buy/sell signals, traders can use the implicit R-Squared regime (visible through the MA's behavior — tight tracking vs. divergence) as a filter for other strategies. Apply your existing entry rules only when the MA is tightly tracking price (trending regime), and stand aside when the MA visibly separates from price (ranging regime).

  • Multi-timeframe trend alignment: Apply the indicator on both a higher timeframe (e.g., daily) and a lower timeframe (e.g., 1-hour). Take lower-timeframe BUY signals only when the higher-timeframe adaptive MA is in bullish state, and SELL signals only when the higher-timeframe is bearish. This multi-timeframe alignment leverages the adaptive nature of the indicator across different time horizons.


How Multiple Indicators Work Together

The Adaptive Statistical Smoother integrates three distinct analytical components into a unified adaptive system, each addressing a specific weakness of traditional moving averages:

  1. Forward-backward zero-lag EMA (lag elimination): Standard moving averages inherently lag price by approximately half their lookback period. The bidirectional EMA approximation addresses this by running a second smoothing pass in reverse over historical values, canceling out the phase shift. This gives the adaptive MA a responsive baseline to track during trends — without the noise sensitivity that comes from simply using a very short-period EMA.

  2. R-Squared trend filter (regime detection): The R-Squared coefficient provides an objective, statistical answer to the question "is the market trending right now?" This replaces subjective visual assessment or fixed-threshold approaches (like ADX) with a measure rooted in linear regression theory. R² directly controls how the adaptive MA behaves — it is not merely a signal filter but the core adaptive mechanism that switches the MA between trend-tracking and range-diverging modes.

  3. Standard deviation volatility bands (context visualization): The bands add a volatility dimension that neither the zero-lag baseline nor the R-Squared filter provides. They show traders the expected range of price movement around the adaptive MA, helping to distinguish between normal retracements within a trend (price stays within bands) and genuine trend reversals (price breaks through bands and crosses the MA).


The synergy is structural: zero-lag EMA (responsive baseline) → R-Squared (regime classification) → adaptive blending/divergence (the adaptive MA itself) → volatility bands (context envelope) → R²-filtered crossover signals (actionable entries/exits). The zero-lag baseline ensures the MA has a fast, accurate target to track; R-Squared determines whether to track it or diverge; and the volatility bands provide the visual context for interpreting the MA's position relative to price. Each component compensates for a specific weakness — lag, false signals in ranges, and lack of volatility context — that would undermine the system if any single component were used alone.

Unique Aspects

  • Statistical regime switching: Unlike adaptive moving averages that use volatility or momentum to adjust their speed (e.g., KAMA, VIDYA), the Adaptive Statistical Smoother uses R-Squared — a measure of trend linearity — to switch between two fundamentally different behaviors: convergence toward a target during trends and deliberate divergence during ranges. This is a qualitatively different approach that directly addresses the root cause of whipsaw (lack of trend) rather than a symptom (high volatility).

  • Bidirectional EMA approximation in Pine Script: True zero-phase-shift filters require processing the entire dataset in both directions, which is not natively possible in real-time bar-by-bar computation. The forward-backward loop in this indicator approximates this by iterating over historical forward-EMA values within the lookback window, achieving near-zero lag without requiring future data — a practical implementation of signal processing theory within Pine Script's constraints.

  • Directional divergence mechanism: During ranging markets, the adaptive MA does not simply freeze or slow down — it actively moves away from price in the last known trend direction. This creates increasing separation that requires a genuine trend resumption (not just noise) to produce a crossover, providing a self-adjusting buffer proportional to the ranging market's volatility.

  • Dual-threshold R-Squared filtering: The indicator uses two R-Squared thresholds for different purposes: 0.5 for the MA's adaptive regime switch (trending vs. ranging behavior) and 0.3 for signal generation (minimum trend evidence for crossover signals). This layered approach means the MA adapts its behavior at a stricter threshold while still allowing signals in moderately trending conditions, balancing responsiveness with noise rejection.


How to Use

  1. Add the indicator to your chart. It overlays directly on the price chart, displaying the adaptive MA line, upper and lower volatility bands, and a shaded volatility cloud between the bands.

  2. Observe the adaptive MA line (thick colored line). When it is green and tightly tracking price, the market is in a statistically confirmed uptrend. When it is red and tracking price closely, the market is in a confirmed downtrend. When the MA visibly separates from price, the R-Squared filter has detected a ranging market and the MA is in divergence mode.

  3. Watch for BUY signals (green "BUY" labels below bars) — these fire when price crosses above the adaptive MA and R-Squared exceeds 0.3, indicating a bullish crossover with minimum statistical trend support. Consider entering long positions or closing short positions.

  4. Watch for SELL signals (red "SELL" labels above bars) — these fire when price crosses below the adaptive MA and R-Squared exceeds 0.3, indicating a bearish crossover with trend confirmation. Consider entering short positions or closing long positions.

  5. Use the volatility bands (shaded cloud) to gauge the expected price range around the adaptive MA. Price touching the upper band in an uptrend suggests extended momentum; price touching the lower band in a downtrend suggests extended selling pressure. Reversals from band extremes back toward the MA can serve as mean-reversion opportunities within the prevailing trend.

  6. Monitor bar colors for a quick visual scan of the current trend state across the chart — green bars indicate bullish trend, red bars indicate bearish trend.

  7. Adjust the Statistical Window to match your trading timeframe. Shorter windows (10–15) make the R-Squared filter more responsive to recent price behavior — suitable for intraday or short-term swing trading. Longer windows (25–50) provide a more stable trend assessment — suitable for position trading on daily or weekly charts.


Customization

  • Statistical Window (default: 20): The lookback period for both the R-Squared calculation and the standard deviation bands. This is the most impactful parameter. Shorter values make the indicator more responsive — the R-Squared filter reacts faster to regime changes and the volatility bands adjust more quickly. Longer values produce smoother, more stable readings that filter out short-term noise but may delay regime detection. Start with 20 for daily charts and adjust based on your asset's typical trend duration.

  • Forward-Backward Smoothing (default: 10): Controls the EMA period used in the zero-lag approximation. Lower values (5–7) produce a baseline that tracks price very closely, making the adaptive MA highly responsive during trends but potentially more sensitive to noise. Higher values (15–20) produce a smoother baseline with slightly more residual lag but better noise rejection. The interaction between this parameter and the Statistical Window determines the overall character of the indicator.

  • Volatility Multiplier (default: 1.5): Scales the standard deviation bands around the adaptive MA. Higher values (2.0–3.0) produce wider bands that contain more price action — useful for volatile assets or for identifying only extreme deviations. Lower values (0.5–1.0) produce tighter bands that price breaks more frequently — useful for identifying smaller volatility expansions or for more active trading styles.

  • Bullish / Bearish Colors: Fully customizable colors applied to the adaptive MA line, volatility bands, cloud fill, signal labels, and bar coloring. Adjust to match your chart theme or to improve visibility on different background colors.


Conclusion

The Adaptive Statistical Smoother brings a statistically rigorous approach to trend following by combining a forward-backward zero-lag EMA approximation with an R-Squared-driven adaptive regime filter. The zero-lag baseline eliminates the inherent delay of conventional moving averages, while the R-Squared coefficient provides an objective, real-time assessment of whether the market is trending or ranging. During trends, the adaptive MA converges toward the responsive baseline proportionally to trend strength; during ranges, it deliberately diverges to create a whipsaw-resistant buffer zone. Dynamic volatility bands add a contextual envelope, and dual-threshold R-Squared filtering ensures that buy and sell signals carry minimum statistical trend evidence. Whether used as a standalone trend-following system or as an adaptive trend filter for other strategies, the Adaptive Statistical Smoother provides a self-adjusting framework that adapts its behavior to the current market regime — tracking trends closely when they exist and stepping aside when they do not.

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.