OPEN-SOURCE SCRIPT

Variance-Weighted Regression Trend [BackQuant]

5 397
Variance-Weighted Regression Trend [BackQuant]

Overview
Variance-Weighted Regression Trend is a rolling linear-regression trend indicator that adjusts the influence of observations according to the estimated variance of their regression residuals.

The script first calculates a standard ordinary least-squares regression across the selected window. It then measures the squared residuals around that fit and uses those residuals to estimate how variable the regression error has been through the sample.

Those variance estimates are converted into relative weights. Lower estimated residual variance can receive more influence, while higher estimated residual variance can receive less. A second weighted regression is then calculated using those weights.

The indicator also includes:
  • EMA, RMA or rolling-average residual variance.
  • Configurable inverse-variance weighting strength.
  • Weight regularization and upper/lower weight limits.
  • Weighted R² and slope-quality diagnostics.
  • Two regression-channel methods.
  • Optional trend-flip quality confirmation.
  • OLS comparison.
  • Linear regression projection.
  • Trend colouring and alerts.


Calculation
The basic process is:

  1. Fit an ordinary least-squares regression over the Regression Length.
  2. Calculate the squared residual of every observation around that fit.
  3. Smooth those squared residuals to estimate local residual variance.
  4. Add a regularization floor to reduce unstable extreme weights.
  5. Convert variance into relative observation weights.
  6. Clamp weights between the selected minimum and maximum.
  7. Calculate a second weighted regression.


The weighted line is therefore influenced more by observations receiving larger relative weights and less by those receiving smaller ones.

Variance Weighting
The weighting is based on regression residual variance, not ATR, trading volume or raw price volatility.

For each point:

  • Residual = Source - OLS fitted value
  • Squared Residual = Residual²


The squared residuals are then processed using the selected Variance Model.

EMA
Uses exponential smoothing and responds more quickly to recent residual changes.

RMA
Uses a slower recursive smoothing process.

Rolling Mean
Uses a finite moving average of squared residuals.

Weight Power
Weight Power controls how strongly estimated variance affects the regression.

The raw weighting relationship is:

  • Weight ∝ 1 / Variance^Weight Power


0 gives equal weighting, making the final fit behave like the OLS regression.

1 applies standard inverse-variance-style weighting.

Values above 1 increase the difference between low- and high-variance observations.

Higher settings can make the regression more selective, but can also concentrate too much influence in a small part of the sample.

Variance Regularization
Very small variance estimates can otherwise create extremely large inverse weights.

The script therefore adds a fraction of the window's mean squared residual to each local variance estimate.

Higher regularization makes the weights more uniform.

Lower regularization allows stronger differences between observations.

Minimum and Maximum Relative Weight
Raw weights are normalized relative to their average before being clamped.

A relative weight above 1 means the observation has greater-than-average influence.

A value below 1 means it has less.

The Minimum Relative Weight prevents high-variance observations from effectively disappearing from the regression.

The Maximum Relative Weight prevents very low-variance observations from dominating the entire fit.

Weighted Regression
Once the final weights are calculated, the script solves a weighted linear regression:

  • Y = Intercept + Slope × X


The displayed line is the current endpoint of that rolling weighted regression.

Each new bar shifts the regression window and recalculates:
  • OLS.
  • Residuals.
  • Variance estimates.
  • Weights.
  • Weighted slope and intercept.


OLS Comparison
The optional OLS line shows the endpoint of the initial equal-weight regression.

This makes it easy to see how much the variance weighting is actually changing the result.

If Weight Power is set to 0, the weighted regression and OLS should be effectively aligned.

As the weighting becomes more aggressive, the lines may separate depending on the residual structure inside the window.

Trend State
Trend direction comes from the sign of the weighted regression slope.

  • Positive slope = bullish.
  • Negative slope = bearish.


A bullish flip occurs when the stored trend changes from bearish to bullish.

A bearish flip occurs when it changes from bullish to bearish.

Quality Confirmation
Quality Confirmation can be enabled to prevent weak slope changes from immediately flipping the trend state.

When enabled, an opposite slope must also satisfy:
  • Minimum Weighted R².
  • Minimum Slope / Standard Error.


If those conditions are not met, the existing trend state remains active even if the current slope temporarily changes sign.

Weighted R²
Weighted R² measures how well the weighted straight-line regression describes the current sample.

Higher values indicate that the weighted observations are more closely aligned with a linear fit.

Lower values indicate a less orderly linear relationship.

R² does not determine trend direction and should not be interpreted as a forecast of future performance.

Slope / Standard Error
The script calculates the absolute weighted slope relative to its estimated standard error:

  • |Slope| / Slope Standard Error


This is used as a practical slope-quality measure.

Higher values indicate that the fitted slope is larger relative to the estimated regression error.

It is used by the optional Quality Confirmation setting and is not presented as a formal significance test.

Regression Channels
Two channel-width methods are available.

Weighted Residual RMS
Uses the weighted root-mean-square distance of observations from the fitted regression.

This reflects the general amount of scatter around the line.

Regression Standard Error
Uses the calculated standard error of the fitted current regression value.

This normally represents a different and often narrower measure than residual RMS.

The Channel Multiplier scales whichever method is selected.

Expand During Poor Fit
When enabled, the channel becomes wider as Weighted R² decreases.

This is intended to visually reflect greater uncertainty when the current window is poorly described by a straight line.

The expansion affects only the channel width.

It does not alter the regression or trend calculation.

Projection
The Projection extends the current regression slope forward by the selected number of bars.

It is simply:

  • Current fitted line extended using the current slope.


It is not a separate forecasting model.

As the regression changes on new bars, the projection also changes.

Current Relative Weight
The Data Window shows the final relative weight assigned to the newest observation.

A value:
  • Above 1 = greater-than-average influence.
  • Below 1 = less-than-average influence.


This can help show how the current observation is being treated by the variance-weighting model.

Effective Sample Size
The indicator also reports:

  • Effective N = (Sum of Weights)² / Sum of Squared Weights


This provides a simple measure of weight concentration.

If weights are similar, Effective N remains close to the full Regression Length.

If a smaller group of observations receives most of the weight, Effective N falls.

This is useful when experimenting with aggressive Weight Power or wide weight limits.

Trend Strength
Trend Strength is used only for the regression glow.

It combines:
  • 60% Weighted R².
  • 40% normalized Slope / Standard Error.


It does not affect the regression or signals.

ATR(14) is used only to scale the visual width of the glow and flip bloom to the instrument.

Input Guide
Regression Length
Controls the size of the rolling regression sample.

Projection Bars
Controls how far the current fitted slope is extended visually.

Variance Length
Controls how quickly the residual-variance estimate changes.

Variance Model
Selects EMA, RMA or Rolling Mean smoothing of squared residuals.

Weight Power
Controls the strength of inverse-variance weighting.

Variance Regularization
Reduces extreme differences between weights.

Minimum / Maximum Relative Weight
Limits how little or how much influence any one observation can receive.

Channel Width
Selects Weighted Residual RMS or Regression Standard Error.

Channel Multiplier
Scales the regression channel.

Poor Fit Expansion
Optionally widens the channel as R² deteriorates.

Quality Confirmation
Requires minimum regression fit and slope quality before allowing trend flips.

How to use it
The indicator can be used as:
  • A regression-based trend filter.
  • A comparison between ordinary and variance-weighted regression.
  • A way to study how residual-based weighting changes a rolling trend estimate.
  • A trend-quality filter using R² and slope strength.
  • A regression channel for visualizing fit dispersion.


The OLS Comparison and Data Window values are particularly useful when testing the weighting settings, because they show whether the extra weighting is materially changing the regression or simply producing a result close to ordinary least squares.

Limitations
  • The variance estimates are derived from OLS residuals inside the same rolling window.
  • The model is a custom two-stage weighted regression rather than a full generalized least-squares procedure.
  • Higher Weight Power can concentrate the fit in a relatively small part of the sample.
  • Linear regression cannot represent every type of market structure.
  • High R² does not imply future trend continuation.
  • The forward projection is only a linear extrapolation of the current fit.
  • Quality Confirmation can reduce weak flips but can also delay genuine changes in direction.


Data Window
The script exposes:
  • Weighted Slope.
  • Weighted R².
  • Slope / Standard Error.
  • Weighted Residual RMS.
  • Regression Standard Error.
  • Current Relative Weight.
  • Effective Sample Size.
  • Trend Strength.


Alerts
The indicator includes:
  • Variance-Weighted Regression Bullish: trend changes from bearish to bullish.
  • Variance-Weighted Regression Bearish: trend changes from bullish to bearish.
  • Variance-Weighted Regression Flip: either transition occurs.


Summary
Variance-Weighted Regression Trend starts with a normal rolling OLS regression, measures the residual variance around that fit, and uses those estimates to assign relative weights to the observations in a second regression.

The weighting strength, variance smoothing, regularization and weight limits are all configurable, making it possible to move from essentially equal-weight OLS to a much more selective fit.

The final weighted slope controls the trend state, while Weighted R² and the Slope / Standard Error score can optionally be used to filter weak reversals.

Regression channels, OLS comparison, forward projection and the visual strength system provide additional context around the core weighted regression without changing the underlying trend logic.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.