OPEN-SOURCE SCRIPT

LOWESS Adaptive Envelope [BackQuant]

167
LOWESS Adaptive Envelope [BackQuant]

Overview
LOWESS Adaptive Envelope is a nonparametric trend-fit and volatility envelope tool built around LOWESS (Locally Weighted Scatterplot Smoothing). Instead of smoothing price with a fixed-form moving average, this indicator performs a rolling set of local weighted linear regressions across a chosen historical window and stitches those local fits into a single smooth curve that adapts to changing market structure.

On top of the fitted curve, the script builds an adaptive envelope whose width is driven by the local magnitude of the model’s residuals (how far price deviates from the fit). That means the envelope automatically expands when the market is noisy or trending aggressively, and contracts when price is stable or mean-reverting cleanly.

The output is a complete “structure map”:
  • A LOWESS fitted centerline (trend estimate).
  • Upper and lower adaptive bands derived from smoothed residual spread.
  • A filled region that changes color based on where price sits relative to the fit.
  • Optional extrapolation of the fit and envelope into the future using last slope, with widening uncertainty.
  • An info label showing fit quality (R²), position inside the envelope, and direction.


Where LOWESS comes from (and why it is different from moving averages)
LOWESS (also written LOESS) is a classic statistical smoothing technique used in exploratory data analysis and robust curve fitting. It became popular because it can approximate complex shapes without assuming a single global model. Instead of forcing the entire window to follow one equation (like a single linear regression or a single moving average kernel), LOWESS fits many small local regressions, each one tailored to its neighborhood.

Key distinction:
  • A moving average is a fixed smoother, it applies the same weighting rule everywhere, regardless of whether the market is trending, chopping, or accelerating.
  • LOWESS is a locally re-fitted model, it re-estimates slope and intercept at each point based on nearby data.


In price terms:
  • LOWESS is better at “hugging structure” when the market curves or transitions.
  • It can follow gradual regime shifts without the same lag profile as long-window MAs.
  • It does not assume the trend is constant across the whole lookback, it assumes trend can vary locally.


What the indicator is modeling
Think of the lookback window as a dataset of points:
  • x = bar index (0..length-1 inside the window)
  • y = price


For every point i inside that window, the indicator estimates the best local line:
  • y ≈ a + b * x

But it does this using only nearby points, and it weights them by distance from i. So the fitted value at i is a locally weighted regression prediction.

The final fitted curve is the collection of those predictions across i = 0..length-1.

Core mechanics: local weighted linear regression

1) Neighborhood size (bandwidth)
The “locality” is controlled by a bandwidth parameter. In this script:
  • h = max(bandwidth * length / 2, 2)


Interpretation:
  • h acts like a radius measured in bars inside the fitting window.
  • Lower bandwidth → smaller h → more local fit (more responsive, can track curvature, more sensitive to noise).
  • Higher bandwidth → larger h → more global fit (smoother, more stable, more lag in transitions).


So bandwidth controls the bias-variance tradeoff:
  • Small bandwidth: low bias, high variance.
  • Large bandwidth: higher bias, lower variance.


2) Tricube kernel weighting
LOWESS requires a weight function that decays smoothly with distance. This script uses the classic tricube kernel:

For each candidate point j around target i:
  • u = |i - j| / h
  • If u < 1:
    - w = (1 - u³)³
  • If u ≥ 1:
    - w = 0


Why tricube:
  • Weights go to zero smoothly at the boundary (no sharp cutoff artifacts).
  • Nearby points dominate the fit, distant points contribute little or nothing.
  • It is a standard LOWESS choice because it produces stable smooth curves.


3) Weighted least squares fit
For each i, the script accumulates weighted sums over j in the neighborhood:
  • sumW, sumWX, sumWY, sumWXX, sumWXY


These correspond to the normal equations for weighted linear regression. From those, it computes:
  • denom = sumW * sumWXX - sumWX²
  • a and b derived from sums (intercept and slope)
  • fitted = a + b * i


If denom is too small (numerical instability, insufficient variation), it falls back to the raw price at that i.

This entire process is repeated for every i in the window, which is why it is done only on the last bar (performance).

Why it fits inside the window rather than a single line
A single regression across 200 bars assumes one slope b explains the whole move. Markets rarely do that. LOWESS allows the slope to drift through time, which is exactly what “trend structure” actually does in real price.

Residuals: turning model error into volatility structure
Once the LOWESS fitted curve is computed, the script measures the residual at each point:
  • res = price - fitted


Residuals are the model’s error. In trading terms, residual magnitude is a proxy for:
  • Local noise level.
  • Deviations from trend structure (overextension/underextension).
  • Regime instability (trend is less “explanatory”).


The script takes absolute residuals:
  • absRes = |res|


This is important because envelope width should reflect spread size regardless of direction.

R²: fit quality and regime information
The indicator also computes R² over the window:
  • ssRes = Σ(res²)
  • ssTot = Σ((price - meanPrice)²)
  • R² = 1 - ssRes/ssTot


Interpretation:
  • Higher R² means the LOWESS fit explains more of the variation inside the window.
  • Lower R² means price is behaving in a way the smooth trend model cannot explain well (chop, shocks, irregular volatility).


In markets, R² can be read as “how trend-like vs how noisy” the recent environment is, but remember it depends on your chosen length and bandwidth.

Adaptive envelope construction (what makes it “adaptive”)
A normal envelope uses a constant width (like ±k*ATR or ±k*stdev). This script does something different: it estimates a local envelope width based on smoothed residual magnitude.

1) Smooth residual magnitude locally
It computes a residual averaging window:
  • rWin = max(3, int(h * 0.8))


So the residual smoothing window is linked to the LOWESS locality. If the fit is local, the envelope adapts locally. If the fit is global, the envelope adapts more slowly.

Then for each i:
  • envW = mean(absRes over [i-rWin .. i+rWin]) * envMult


Interpretation:
  • The envelope width is proportional to how much price typically deviates from the fit around that region.
  • envMult is your “how many spreads” multiplier.


This creates an envelope that expands and contracts along the curve, not a single constant band.

2) Upper and lower envelopes
For each i:
  • upper = fitted + envW
    *lower = fitted - envW


    This is a model-driven channel. It is not ATR-based directly, it is “error-based.” That makes it very effective at responding to the actual behavior of the market relative to the fitted structure.

    How to interpret the envelope
    The centerline is the best local structural estimate. The envelope is the expected deviation range around that structure.

    Typical readings:
    • Price near centerline: balanced relative to structure.
    • Price riding upper band: strong bullish pressure, trend continuation or overextension depending on context.
    • Price riding lower band: strong bearish pressure, continuation or overextension.
    • Repeated band rejections: mean-reversion regime around the structural fit.
    • Envelope widening: instability rising, volatility expanding, structure less reliable.
    • Envelope tightening: compression, cleaner trend or coiling behavior.


    Because the band width is based on residuals, widening often coincides with “trend breaks” and regime transitions, not just higher ATR.

    Color logic and visual encoding
    The envelope fill color is based on price relative to the most recent fitted value:
    • If close > fitted[last], bullish color.
    • Else bearish color.


    So color is a regime/bias cue, not a volatility cue. The bands themselves are drawn with translucent versions of the same regime color, while the fit line is a subtle white.

    The fill polygon is constructed by:
    • Walking forward through upper points.
    • Then walking backward through lower points.

    So the shape is closed and can be filled cleanly using polyline fills.

    Extrapolation: forward projection with widening uncertainty
    This script can project the fitted line into future bars. This is not forecasting in a statistical sense, it is a deterministic extension based on the current slope.

    How it extrapolates
    It takes:
    • slope = fitted[last] - fitted[prev]
    • lastFit = fitted[last]


    Then for i = 1..extrapBars:
    • futureFit = lastFit + slope * i


    This is a linear continuation of the most recent fit direction. It is meant as a visual guide for “if the current local trend continues.”

    Why the forward envelope widens
    The script also grows the envelope slightly with each projected bar:
    • envGrow = lastEnv * 0.01
    • futureEnv = lastEnv + envGrow * i


    This is a simple uncertainty widening mechanism. As you move further into the future, you should assume less confidence. The envelope expansion encodes that visually without claiming statistical rigor.

    Info label: what it reports and how to read it
    When enabled, the label shows:

    1) Direction arrow
    It computes a slope over the last few fitted points:
    • recentSlope = fitted[last] - fitted[last-5] (or closest valid index)
    • ▲ if slope >= 0
    • ▼ if slope < 0


    This gives a slightly more stable direction read than one-bar slope.

    2) R²
    Displayed as R²: 0.xxx, representing how well the LOWESS curve explains window variation.

    3) Envelope Position (Env Pos)
    It measures where the current close sits inside the latest envelope:
    • 0% = at lower band
    • 50% = at centerline
    • 100% = at upper band


    This is extremely useful as a normalized “over/under extension” metric because it is scaled by the adaptive band width, not raw price units.

    How to use it properly

    Trend structure and regime filtering
    • Use the fit line as structural trend direction.
    • Use the fill color as quick bias context.
    • Use R² as a “trend quality” read: high R² tends to mean cleaner structure, low R² tends to mean chop or instability.


    Mean reversion vs continuation
    This tool can support both styles, but interpretation differs:

    Mean reversion framing
    • If market repeatedly returns to the fit line, the fit is acting like value.
    • Upper band touches can be “overbought relative to structure.”
    • Lower band touches can be “oversold relative to structure.”
    • Envelope position becomes your normalized stretch gauge.


    Trend continuation framing
    • In strong trends, price can ride a band rather than revert to centerline.
    • Band riding plus rising fit slope suggests persistence.
    • A sudden failure to hold the band plus falling R² can flag transition risk.


    Breakdown/transition identification
    Because the envelope width is residual-driven:
    • If price starts producing large residuals, the envelope expands.
    • That expansion is often a signature of regime change, not just volatility.
    • Combine expansion with slope flattening to identify trend exhaustion.


    Parameter tuning (what each input really does)

    Length
    Defines how much historical data is used for the full fit. Larger length:
    • More stable curve.
    • More computational load.
    • Tends to represent macro structure.


    Bandwidth
    Controls locality:
    • Low bandwidth (0.10–0.25): more reactive, tracks curvature and micro-structure, more sensitive to noise.
    • Higher bandwidth (0.30–0.50+): smoother, more stable, more lag in fast turns.


    Envelope Width (envMult)
    Scales how wide the adaptive band is relative to the local residual spread:
    • Lower values create a tighter channel, more band interactions.
    • Higher values create a wider channel, fewer touches, better for regime filtering.


    Extrapolation Bars
    Purely visual. More bars gives a longer projected structure line and uncertainty region.

    Limitations and correct expectations
    LOWESS is powerful, but it is not a magic predictor.
    • LOWESS is descriptive, it fits what happened, then projects linearly if extrapolation is enabled.
    • In sudden shocks or gaps, the fit will update only after the new data is inside the window.
    • Very small bandwidth can overfit local noise, producing misleading curvature.
    • Very large bandwidth can underfit, behaving like a slow regression and missing turning points.
    • R² is window-dependent, a low value does not mean “bad indicator,” it often means “market is not smooth right now.”


    Summary
    LOWESS Adaptive Envelope applies locally weighted linear regression (LOWESS) with a tricube kernel to build a smooth, structure-following fitted price curve that adapts to regime changes without relying on a fixed moving-average form. It then converts the model’s local residual spread into a dynamic envelope that expands and contracts with real deviation behavior, provides fit quality via R², normalizes price position inside the band, and optionally extrapolates the latest structural slope forward with widening uncertainty. The result is a robust trend-structure and deviation framework that is equally useful for regime filtering, mean-reversion context, and trend persistence assessment.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.