OPEN-SOURCE SCRIPT

Linear Regression Channel Fit Audit

800
Linear Regression Channel Fit Audit

Overview

Linear Regression Channel Fit Audit is a price-chart overlay for studying statistical slope and the behavior of a rolling regression channel. It separates three questions: how well a line fits its own historical window, how the next observation compares with the model available before it arrived, and what happens when an earlier model is kept unchanged through several later observations.

The practical question is simple: did price fit the channel that was available beforehand, or did updating the channel make it appear to fit?

The script combines a current ordinary least-squares channel, a previous-model reference, refit attribution, historical as-of inspection, and scheduled frozen-channel studies. It is a descriptive model-diagnostics indicator, not a trading strategy, probability forecast, or source of entry and exit instructions.

What distinguishes the approach

Regression lines, residual bands, R-squared and historical channels are established tools. The contribution here is their use in a connected comparison of model updates and subsequent observations.

The same observation is evaluated before and after refitting. Movement of the fitted center is separated into removal of the oldest observation and addition of the newest. Changes in containment are examined separately through center movement and width changes. Earlier models are also retained on a predetermined schedule, allowing endpoint containment to be distinguished from containment throughout the observed path. Matched comparisons then show how a fixed model differs from an updating model and how shifting the starting level affects extrapolation errors.

These components address one problem: a rolling channel can change its apparent relationship with price because the model itself has moved or widened. They do not vote on a combined trade score or choose a supposedly best model.

Getting started

Use standard time-based candles and a price-valued Source. The default Source is close, the regression length is 120 bars, and the width is twice the residual standard error. Snapshot updates default to Confirmed close.

Start with the Model panel. Read the slope and in-window fit, then compare Prior/Now. Use Refit research to examine the effect of updating the model, Horizon research for one-step and H-step endpoint checks, and Frozen paths for complete fixed-model observation sequences.

Historical frozen paths are enabled by default. Four recent paths are retained for display. Each evaluates 24 later Source values, followed by a 24-bar gap, so scheduled origins are 48 bars apart. Drawing retention and numerical sample retention are separate controls.

Chart guide

The solid upper and lower boundaries are cyan and pink by default. The solid center is colored according to rising, falling or approximately flat normalized slope. Optional dotted inner guides and transparent shading help locate price within the selected width. These colors describe geometry, not trade direction.

OLS identifies the fitted center. +1w and -1w identify the selected upper and lower boundaries, where w means one channel half-width, not necessarily one standard deviation. The dashed EXT segment continues the current slope and width geometrically. It is not an uncertainty interval and is not used in any audit statistic.

The short amber reference uses the preceding model and its preceding width. Its endpoint at the displayed observation is the one-step reference. Optional historical reference traces connect those successive one-step centers and boundaries; they are not one permanently fixed channel.

Thin dashed channels identified by F1, F2 and similar labels are scheduled frozen paths. They retain their origin model rather than being refitted with later prices. A dotted vertical line marks the origin. Optional amber connectors show the first observed exit and the distance from the fixed center at the latest evaluated observation.

The Forward only setting shows the observed forward portion. Fit + forward additionally restores the original fitted training segment as faint dotted lines. That training segment became available at its origin, not at each older bar through which it is drawn.

Small event symbols have no filled background:
! means a transition outside the respective previous-model envelope, including a direct switch from one outside side to the other.
↺ means refit inclusion has appeared: outside the previous envelope but inside after refitting.
= means a transition inside the respective previous-model envelope again.

An optional letter mode uses O, R and I. These are state transitions, not buy/sell signals. Each observation uses its own preceding model; an inside-again event does not prove that price crossed back through one unchanged boundary.

Symbols are offset outside nearby candle wicks for readability. Their vertical placement is not an event or execution price. When conditions coincide, refit inclusion takes drawing priority. Marker spacing, count and display-window filters can hide glyphs without removing observations or suppressing the corresponding alert conditions.

Regression and residual width

The script fits a straight line to N consecutive Source observations using equally spaced bar positions. It works in source-price units, not log price or elapsed calendar time. For each observation, its residual is its Source value minus the fitted value at the same position in that window.

Three half-width methods are available:
Residual standard error: multiplier * sqrt(SSE / (N - 2)).
Mean absolute residual: multiplier * mean(abs(residual)).
Residual percentile: the nearest-rank percentile of absolute residuals from the fitted window.

SSE is the sum of squared fitted residuals. The percentile method does not use the multiplier. Mean absolute residual is not median absolute deviation. A configurable minimum width in symbol ticks, together with a small numerical floor, prevents a zero denominator on flat or nearly exact-line data. The floor can dominate such samples.

These are descriptive residual envelopes. A selected percentile measures the fitting sample; it does not specify a future coverage probability. None of the methods constructs a confidence interval or prediction interval.

Model panel

Slope is the fitted price change over the selected measurement span divided by the current half-width. The default span is 20 bars. Arrows and the flat threshold use this normalized value. Changing the width method or multiplier can therefore change the normalized slope and its flat classification. It is not an on-screen angle or annualized return.

R-squared measures in-window fit relative to variation around the sample mean. The five-segment meter is a coarse visual representation of that number. Constant data display n/a. High R-squared does not establish useful future prediction.

In/Next compares current fitted-window containment with realized one-step containment over the audit sample. These are different samples. Amber highlights the configured coverage gap after enough valid observations are available; it is not a significance test.

Prior/Now shows the signed Source distance before and after refitting. Prior uses the old half-width; Now uses the new half-width. Values beyond +1 or -1 are outside the respective envelope. Do not subtract these readings as raw price distances because their denominators differ.

Add/Drop reports the center-update components explained below. State refers to the previous envelope, except REFIT IN, which explicitly identifies inclusion after updating. Audit shows the valid observation count. A check mark means the sample is full, not that the model passed a performance test.

Detailed mode also shows one-step error skill, residual persistence, older/recent half-window slopes, width change and the number of refit-included observations. Residual persistence is the sum of adjacent residual products divided by SSE, not a significance test. The two half-window slopes use a common full-channel width; with odd lengths the older half contains one extra observation.

Add/Drop: why the center changed

The previous and current N-observation windows share N - 1 observations. All three models below are evaluated at the current observation's time coordinate:
Previous center: the preceding N-observation model extended by one bar.
Common center: the model fitted to the N - 1 shared observations.
Current center: the newly fitted N-observation model.

Drop = Common center - Previous center.
Add = Current center - Common center.
Add + Drop = Current center - Previous center.

The defined update order removes the oldest observation first and then adds the newest. The calculation uses the least-squares endpoint leverage identity to obtain the addition term without fitting another model on every bar.

Both displayed components are signed shifts in prior half-widths, not percentages. Opposite signs indicate offsetting effects. This is an attribution of a model update, not an explanation of the economic cause of a price movement.

Refit research: center versus width

Before/After compares exactly the same confirmed observations against their respective prior and refitted envelopes. In/Out n counts outside-to-inside and inside-to-outside observations. Their difference accounts for the change in matched containment:

After coverage - Before coverage = (Included observations - Excluded observations) / Paired observations.

The After result includes each observation in its own fit and is not an out-of-sample forecast.

Containment margin is half-width minus the absolute distance from the center. Its change is split into:
Center contribution = abs(old residual) - abs(new residual).
Width contribution = new half-width - old half-width.

Both displayed contributions are divided by the prior half-width, and their sum equals the normalized margin change.

For outside-to-inside observations, the Cause field tests two alternative geometries: new center with old width, and old center with new width.
CENTER: only the center change alone is sufficient.
WIDTH: only the width change alone is sufficient.
JOINT: neither change alone is sufficient; both are needed.
EITHER: either change alone is sufficient.

The four classification counts sum to the included count. These are geometric comparisons, not evidence of price reversal or economic causality. For example, WIDTH can identify a point accommodated by a wider envelope without needing the center to move.

One-step and H-step endpoint research

At observation t, the one-step reference is the center fitted at t-1 plus that model's slope. Its width is the width fitted at t-1. The observation at t is not included in that reference.

The second reference uses the model fitted H bars earlier, extended by H bars while keeping its origin width. H defaults to 5 and is selectable from 2 to 50. Results enter the statistics only when their endpoint has been reached and confirmed. This endpoint test does not require all intermediate observations to remain inside; the Frozen paths study addresses that separate question.

Each horizon reports realized containment and an error-skill comparison with holding its origin Source value unchanged:

Skill (%) = 100 * (1 - Model squared-error sum / Unchanged-source squared-error sum).

Model and baseline use identical eligible observations at that horizon. Positive values mean lower squared error than that baseline; negative values mean higher squared error. A zero baseline error produces n/a. Scores are not returns, win rates or significance levels. The two horizons can have different valid counts and are not necessarily identical samples across horizons.

The page also reports H-step mean absolute error in source-price units, the matching baseline error, mean absolute error normalized by origin width, and upper/lower endpoint misses. Successive horizon tests can overlap and are dependent.

Scheduled frozen paths

A path saves the fitted center, slope, width and Source value at its origin. It then evaluates the next L confirmed Source values without changing those saved parameters:

Fixed center at age k = Origin fitted center + Origin slope * k.
Fixed boundaries = Fixed center at age k +/- Origin half-width.

The origin observation itself is not one of the L tested outcomes. A path is extended only through observations already reached. It is not reset or discarded when price exits. Historical line colors do not change retrospectively to label the whole path as successful or unsuccessful.

Origins follow a bar-count schedule beginning at the first loaded confirmed close at or after Path schedule anchor. They recur every L plus Gap bars. Price behavior does not choose the scheduled times. An invalid origin fit is skipped, not moved to a more favorable observation. Skipped origins are reported in the sample tooltip.

With a zero gap, a path finishes before the next starts on the same close. Tested outcome segments do not overlap, although training windows can overlap and market observations remain dependent.

At maturity, the result label is:
ALL: all L sampled Source values were inside.
BACK: the final Source value was inside after at least one earlier sampled exit.
OUT: the final Source value was outside.
DATA: the path contained missing Source observations and is excluded from valid-result denominators.

A fraction such as 8/24 indicates an unfinished path. It is not counted as success or failure. ALL is about sampled Source values at confirmed bars, not an intrabar high/low test. With close as Source, a wick can exceed a boundary while the sampled close remains inside.

The first-exit connector marks the first observed outside Source value, not an intrabar crossing or order fill. Maximum distance is the largest sampled absolute distance from the fixed center divided by origin width.

For a simple example, a path that exits at age 6 and finishes inside at age 24 is BACK, not ALL. Looking only at the final observation would miss that distinction.

Frozen paths panel and matched comparisons

End/All reports final-observation containment and every-observation containment over the same valid completed paths. Back/Exit reports paths ending inside after an exit and paths with any sampled exit. End count equals All count plus Back count.

First exit is the average first-exit age among exited, valid, completed paths only. Paths without an exit and unfinished paths are not assigned zero-time exits. This conditional average is not a survival estimate.

F/A skill compares two centers against one common unchanged-origin-Source baseline over the same complete paths:
F: origin fitted center + origin slope * k.
A: origin Source + the same origin slope * k.

A changes the starting level, not the slope. The comparison helps inspect the effect of initial fitted-center displacement. It does not prove that the slope is useful or select a winning model. Scores use pooled squared errors across all included observations, not an average of individual path percentages.

Roll/Fix compares updating one-step envelopes with the saved fixed envelope on the same eligible observations within valid completed paths. It reports the percentage inside only the updating envelope and the percentage inside only the fixed envelope. Both-inside and both-outside counts are also available in the tooltip, along with matched error comparisons.

Both references exclude the observation being tested, but the updating model has intermediate information that the fixed model does not. Their widths may also differ. This comparison measures the effect of updating; it is not a contest between models with equal information.

Paired gives the number of matched observations. Done/Open gives the valid completed-path count and current unfinished age. Missing-data slots are separately disclosed and remain part of slot retention. The drawing cap never changes the numerical sample.

As-of research and sample scope

Set View to As-of research, choose Research start and As-of cutoff, and select the relevant panel page. The main channel and snapshot represent the last available confirmed bar whose close time is inside that interval. The header or its tooltip identifies the actual selected close in the exchange timezone.

Training can use earlier observations, but test origins must be calculated inside the admitted interval. One-step and H-step results therefore need their respective earlier origin models. The script does not invent those initial tests. A frozen path still unfinished at the cutoff remains unfinished.

Rolling audit uses the last K chart bars for the ordinary audit metrics. Selected interval aggregates valid tests admitted throughout the interval. Frozen-path statistics have a separate completed-slot sample: Latest and Rolling research retain up to the configured number of completed slots; Selected interval uses all completed slots. Actual counts, not requested maxima, determine the denominators.

As-of mode does not scroll the chart or hide later candles. It reconstructs the model at the selected time, but it is not a blind replay environment. Alerts are disabled in this mode. Later loaded timestamps can place optional annotations; later Source prices do not enter the selected model or its statistics. Without those timestamps, annotation spacing beyond loaded data uses a nominal bar duration and can differ around session gaps or irregular periods.

Schedule reproducibility and workload

If the path anchor is at or before the beginning of loaded history, the Frozen paths header displays PHASE*. The schedule may then change when additional earlier bars load. For reproducible comparisons, place the anchor within loaded history with earlier bars available, and retain the same symbol, timeframe, settings and research interval.

The default calculation budget is 600 bars, configurable from 100 to 4,000. Latest view adds audit/horizon warm-up to the recent fitted range. Frozen-path origins and retained results are bounded by the recent path range; chronological path IDs are local identifiers, not permanent IDs across recalculations.

In research, the budget is a hard limit on admitted interval bars. RANGE > CAP blocks the main research display rather than silently presenting an earlier endpoint as the selected result. Earlier traces or numeric records can remain partial and must not be read as complete interval results. Narrow the dates or raise the budget. START > END, NO ELIGIBLE BAR and WARM-UP / DATA identify other unavailable states.

Larger windows and percentile sorting increase processing cost. Drawing caps are independent of statistical caps. Up to 12 paths can be retained visually. Defaults are starting points, not optimized parameters.

Numeric history and alerts

Numeric history page selects Model, Refit research, Horizon research or Frozen paths independently of the visible panel; Match panel follows that panel. Outputs are paged rather than exposing every metric simultaneously. Titles use M, R, H and F to identify page-specific meanings, and a numeric page ID accompanies the values. Record that page and the settings when comparing exports. The settings tooltip lists the field mapping.

Common fields include Source, the inclusion-cause code and additive event flags. Cause codes are 0 for none, 1 CENTER, 2 WIDTH, 3 JOINT and 4 EITHER. Event bits are 1 outside, 2 inside again, 4 refit inclusion, 8 refit exclusion, 16 coverage gap, 32 half-window disagreement, 64 path start, 128 path completion and 256 first path exit. Coexisting bits are added. Numeric events are not thinned by marker spacing.

Historical records describe the observation where they were calculated; they do not repeat the frozen as-of panel into later bars. On a zero-gap finish/start close, path step fields describe the finishing path while event flags can identify both events.

Six confirmed-close alert conditions are available in Latest view: Outside prior channel; Inside prior channel again; Refit inclusion appeared; Refit exclusion appeared; Coverage gap appeared; and Half-window slopes disagree. Path start/completion/exit flags are research records, not additional standalone alert conditions. Configure alerts through the chart interface; the indicator does not create them automatically.

Updates and limitations

Confirmed close holds the main snapshot on the last confirmed bar during an open bar. Live preview permits that snapshot to change intrabar. Audit totals, path evaluation, event records and alerts still use confirmed closes.

The current fitted historical segment redraws as its window changes. Restored training segments also use information available at their origin, not at every earlier point. Do not treat those lines as contemporaneous historical signals or describe the entire indicator as non-repainting. Frozen parameters remain fixed within a path for unchanged inputs and data, but changing settings, loaded history, the schedule phase or the data feed can change the reconstructed study. An external Source can introduce its own repainting or revisions.

No volume data, imported libraries, external requests or higher-timeframe series are required. ATR is used only to separate labels from candle wicks. Bar counts are not elapsed calendar time. Non-standard or synthetic charts can change the meaning of prices and time; use standard time-based charts for the described interpretation.

Wide envelopes can achieve high containment without useful directional information. High in-window fit can coexist with weak future error scores. Retained samples can be small, and missing-data exclusions can affect representativeness. No confidence level, calibrated future probability, statistical significance, economic causality or trading profitability is established by these readings.

The script is free and open-source under the Mozilla Public License 2.0. Users can inspect the calculations and modify the research settings. It does not place orders, simulate a trading strategy or guarantee outcomes.

Penafian

Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.