OPEN-SOURCE SCRIPT
Aktualisiert

Machine Learning Price Bands Kernel Regression Signals

327
OVERVIEW

Every "AI band" on this platform draws two lines and asserts them. None of them can tell you how often price actually stays inside.

This one can — because it is built on a method that comes with a MATHEMATICAL COVERAGE GUARANTEE, and then it CHECKS WHETHER IT KEPT THE PROMISE, live, on your chart:

Coverage (empirical vs nominal) 89.1% vs 90% n = 20,266
Is the miss REAL? -0.9 pp z = -4.3 (real)
Verdict undercovering — real, but small

That is not a band. That is a prediction interval that has been audited, and it is the whole reason this tool exists.

It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.


THE MACHINE LEARNING, SPELLED OUT — no buzzwords, here is the actual model

1. NADARAYA-WATSON KERNEL REGRESSION. Non-parametric: no functional form is assumed, the data chooses the shape. Each past bar votes on the current estimate with a Gaussian weight that decays with distance. This is the same estimator Lo, Mamaysky and Wang used in the Journal of Finance to make chart-pattern recognition objective. It is real machine learning, and it is sixty years old.

The kernel here is CAUSAL. It only ever looks backwards. A centred kernel — the kind most "Nadaraya-Watson envelope" scripts use — peeks at bars that have not happened yet, and that is why their historical fit looks so much better than their live one.

2. BANDWIDTH BY PREDICTIVE MODEL SELECTION. The bandwidth h is the only real parameter, and it is not a magic number: several candidates are run in parallel and scored on their ROLLING ONE-STEP-AHEAD SQUARED ERROR. The winner is used. That is honest model selection — the criterion you would use to choose any forecaster — rather than a knob you turn until the chart looks nice.

3. CONFORMAL PREDICTION INTERVALS. The half-width is the (1-alpha) empirical quantile of the recent ABSOLUTE one-step-ahead errors. Under exchangeability this carries a FINITE-SAMPLE coverage guarantee, with NO distributional assumption at all: no normality, no GARCH, no volatility model. The model's own recent mistakes size the band — which is why it widens when the model starts being WRONG, not merely when price starts moving.

4. ADAPTIVE CONFORMAL INFERENCE — Gibbs and Candes, NeurIPS 2021.

Here is the problem with plain conformal prediction on markets, stated plainly: its guarantee holds under EXCHANGEABILITY, and financial returns are the textbook counterexample. Volatility CLUSTERS. So a residual quantile computed over a trailing window is always a step behind, the band is too narrow exactly when it matters, and the misses bunch together. Coverage lands quietly under nominal. Measured live on NIFTY futures before this was added: 89.1% against a nominal 90%, on the 1m, the 3m and the 1h, every one of them roughly four standard errors below target. Not a bug. The assumption breaking.

ACI makes the miscoverage level a LEARNED parameter:

alpha(t+1) = alpha(t) + gamma * (alpha - err(t))

Miss the interval and alpha falls, so the quantile rises and the band WIDENS. Cover it and alpha creeps back, so the band TIGHTENS. Long-run coverage provably converges to the target IRRESPECTIVE OF THE DATA GENERATING PROCESS — no exchangeability assumption anywhere.

A band that notices it is undercovering and fixes itself. Watch the alpha row: where it settles BELOW nominal is a direct measurement of how badly exchangeability fails on your instrument.

MEASURED, ON THE SAME INSTRUMENT, BEFORE AND AFTER:

timeframe plain conformal with ACI
1m 89.1% 90.1%
3m 89.1% 90.1%
5m 89.1% 90.1%
15m 90.1% 90.1%
1h 89.1% 90.1%
(nominal 90%)

Five timeframes, a four-standard-error undercoverage on four of them, closed. The binomial test now returns "calibrated — within sampling noise" and means it. That is not a backtest of a trading rule. That is a mathematical promise being kept, and being checked.

5. NORMALISED NONCONFORMITY — Papadopoulos et al. (2008), Lei et al. (2018).

The plain score |price - fit| is a SCALAR, which means the band is THE SAME WIDTH in a dead tape and in a crash. It therefore OVERCOVERS in calm and UNDERCOVERS in chaos — and the single marginal coverage figure is the average of those two errors, looking correct while being wrong in both directions.

Normalising divides each residual by a local scale estimate before taking the quantile, and multiplies it back when drawing:

score = |price - fit| / sigma band = fit +/- q * sigma

The band now scales with LOCAL DIFFICULTY — and note it is the MODEL'S difficulty, not the market's volatility. Related, but not the same thing, and the first one is what a prediction interval is actually about.

6. THE COVERAGE AUDIT. A guarantee you do not verify is just a claim.


TWO QUESTIONS ABOUT THE COVERAGE, AND THE PANEL ANSWERS BOTH

IS THE MISS REAL? That is a binomial z-test and it needs no tolerance at all. Each bar is a Bernoulli trial with p = nominal, so the standard error of the observed coverage is sqrt(p(1-p)/n).

IS THE MISS BIG ENOUGH TO CARE ABOUT? That is a judgement, and you set it.

These are NOT the same question, and conflating them is how a band gets waved through as "calibrated". Measured live on NIFTY futures: at n = 20,266 the standard error is 0.21 pp, so an empirical coverage of 89.1% against a nominal 90% is a 0.9 pp miss — FOUR STANDARD ERRORS. Unmistakably real. Arguably too small to trade differently. A 5 pp tolerance called that "calibrated", which was the headline row of the script asserting the one thing the script exists to verify, and asserting it wrongly.

The panel now reports the size of the miss, its significance, and a verdict that distinguishes "within sampling noise" from "real, but small" from "MISCALIBRATED — do not trust the band". You get to decide which of those matters to you, and you get the numbers to decide with.


AND THEN THE ROW NOBODY HAS: CONDITIONAL COVERAGE

Coverage 90.0% vs 90% n = 20,178
calm / normal / turbulent 96.4% · 90.1% · 83.2%

A single marginal number can read a perfect 90% while the interval covers 96% of quiet bars and 83% of violent ones. Ninety per cent is then the AVERAGE OF TWO ERRORS — it looks right while being wrong in both directions, and it is wrong in the direction that costs you money exactly when it costs you money.

Exact conditional coverage is provably impossible without strong assumptions. But you can always MEASURE it, and almost nobody does. Bars are split into calm, normal and turbulent thirds by the percentile rank of ATR, and coverage is scored inside each. If the three numbers fan apart, the band is not breathing — and the normalised score is what closes the gap.

Turn the normalised score off and watch those three fan out. That is the demonstration.


FADE OR FOLLOW? THE TOOL DOES NOT PRETEND TO KNOW

Price leaving a 90% interval is statistically unusual. Whether to FADE it (an outlier, so bet on reversion) or FOLLOW it (the model has broken, so bet on the new regime) is an EMPIRICAL question, and the honest answer is often neither.

So both are logged, both are graded, and BOTH ARE TESTED AGAINST EACH OTHER.

That last part matters more than it sounds. Knowing that fading beats an unconditional control, and that following also beats an unconditional control, does not answer the question a trader is actually asking at a band break — which of the two should I do? They are mutually exclusive responses to the SAME event. So they are run head to head with a Welch t-test, and the answer is allowed to be:

FADE or FOLLOW? NEITHER — the break does not tell you which

If the difference does not clear the noise, then on this instrument the break carries no directional information, and saying so IS the finding. A tool that cannot report its own failure is an advertisement, not a measurement.

And the chart agrees with the panel. An unproven direction is still drawn — it is arithmetic, and you may want it — but it is drawn MUTED and labelled "(not proven)". It used to print "Follow the break" in full colour while the panel directly beneath it said "neither proven". The paint has to agree with the code.


THE ANTI-BIAS GUARDS

ENTRY IS THE CLOSE, for the event and for the control alike. A band break is a SIGNAL, not a fill. Entering at the band — a better price — while the control enters at the close hands every signal a free head start and manufactures an edge out of nothing.

THE CONTROL IS DIRECTION-MATCHED. In a downtrend there are more break-downs than break-ups, so FOLLOW skews short and FADE skews long. A direction-skewed event set measured against a 50/50 control inherits the index drift for free and calls it an edge. Longs are compared only with control longs, shorts only with control shorts, and the control is blended back using the events' OWN direction mix.

IDENTICAL GEOMETRY. Every event and every control trade uses the same stop and the same R multiple, so the comparison is apples to apples.

Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are marked to market, not booked as losses. Nothing is marked proven below t = 1.96.


NON-REPAINT

The kernel is causal, the bandwidth is chosen on past error only, the interval is built from past residuals, and coverage is scored by asking whether the actual close landed inside the interval that was published BEFORE it. Everything is computed on confirmed bars. Nothing is drawn and then moved.


WHY THESE PARTS ARE ONE TOOL

The regression gives the trend. Without the interval, a band is a guess. Without model selection, the bandwidth is a knob you turn until you like the picture. Without the coverage audit, a conformal interval is an unverified promise. And without the signal calibration, "price left the band" is folklore. Each piece is worthless alone — which is exactly why they ship together.


DATA AND SCOPE

Any symbol, any timeframe. ATR-normalised throughout. No volume required.


EXPORTS (Data Window — consume from other scripts via input.source())

EXP_Fit, EXP_Upper, EXP_Lower, EXP_Bandwidth, EXP_Coverage, EXP_Miscal, EXP_Signal, EXP_Entry, EXP_Stop, EXP_Target


CONCEPT CREDIT

Nadaraya-Watson kernel regression — E. A. Nadaraya and G. S. Watson (1964). Its use for technical pattern recognition in finance — Andrew W. Lo, Harry Mamaysky and Jiang Wang, "Foundations of Technical Analysis", Journal of Finance 55(4), 2000. Conformal prediction — Vladimir Vovk, Alexander Gammerman and Glenn Shafer; the split/inductive form used here follows Papadopoulos et al. and Lei et al. Triple-barrier forward labelling — Marcos Lopez de Prado. Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.

The causal-kernel implementation, the parallel bandwidth selection, the live coverage audit, the binomial calibration test and the fade-versus-follow head-to-head are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.


HONESTY AND LIMITATIONS

Conformal coverage is guaranteed under EXCHANGEABILITY. Financial returns are NOT exchangeable — volatility clusters, regimes shift — so the guarantee is approximate in practice. THAT IS PRECISELY WHY THE COVERAGE IS AUDITED LIVE INSTEAD OF ASSUMED. When empirical coverage drifts from nominal you are watching the assumption break, in real time, and you should believe what you see rather than the label.

A prediction interval says where price is LIKELY TO BE. It says nothing about DIRECTION, and it is not a forecast. Coverage being correct does not make band breaks tradeable — those are two different claims, and the tool tests them separately for exactly that reason.

Calibration figures are IN-SAMPLE, with no costs or slippage, and use overlapping windows. A proven in-sample edge is NOT a guarantee out-of-sample. Nothing here predicts price.


DISCLAIMER

Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use.
Versionshinweise
v1.1 — Cost model (no engine change)

- Added a cost model to the band-break self-test: a new "Round-trip cost (R)" input and a
"Net of cost (R)" row. The fade/follow expectancy is already measured in R, so NetR = ExpR − cost
subtracts directly. The ✓ "proven" mark still means the response beats its control statistically;
NetR is shown right beside it so you can also see whether that edge survives trading costs.
- Exported the cost-aware expectancy (EXP_FadeNetR / EXP_FollowNetR) so other scripts can read it via
input.source().
- No change to the kernel-regression bands, the conformal coverage calibration, the signals or the
fade-vs-follow test — everyday behaviour is identical.

Descriptive research tooling, in-sample expectancy, not investment advice.

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.