OPEN-SOURCE SCRIPT

Machine Learning Point Forecast with SR [SS]

1 222
Hello,
Releasing the Machine Learning Point Forecast indicator, let's get into it!

What It Is

This indicator is a price forecasting indicator built on a simple but powerful idea borrowed from machine learning: markets tend to behave similarly when they're in similar states.

Instead of relying on a fixed formula (like a moving average crossover or a fixed RSI threshold), this indicator constantly asks a different question every bar:

"Out of the last 200 bars, which ones looked most like right now and what happened next, those times?"


It answers that question using K-Nearest Neighbors (KNN), a classic non-parametric machine learning technique, applied to four hand engineered features that describe the shape and momentum of price action. The result is plotted directly on the chart as a series of horizontal price targets, each one a literal price level the model thinks is worth watching, based on what similar historical setups did.

The Theory

Feature Engineering: Describing "What a Bar Looks Like"

Raw OHLC data isn't directly comparable across time (a $2 move means something different at $50 than at $500), so the model first converts each bar into four normalized descriptors:

  • Composite candle shape: the combined magnitude of the high, low, and close moves relative to the open, expressed as a single Euclidean value. This captures how "stretched" or volatile a candle was.
  • Close slope: the rate of change of a 14-period linear regression of price, normalized by price. This captures short-term trend acceleration/deceleration.
  • RSI slope: the rate of change of a 14-period linear regression of RSI. This captures whether momentum itself is accelerating or stalling, independent of price.
  • Return slope: the rate of change of a 14-period linear regression of bar-to-bar percentage returns. This captures whether volatility/returns are trending up or down.


Together, these four numbers form a fingerprint for every bar, not just where price is, but how it's moving and accelerating.

Standardization: Putting Everything on the Same Scale

Each of the four features is converted into a z-score over a rolling window (default 100 bars):

z = (value − rolling mean) / rolling standard deviation


This step matters because the four raw features live on completely different scales. Z-scoring puts them all in "standard deviations from normal" terms, so no single feature can dominate the similarity comparison just because its raw numbers happen to be bigger.

The K-Nearest Neighbors Search

With four standardized features per bar, every bar in history is now a point in 4-dimensional space. The model searches the last N bars (default 200, the "Historical Search Window") and calculates the Euclidean distance between the current bar's 4D fingerprint and every historical bar's fingerprint:

distance = √[(Δfeature1)² + (Δfeature2)² + (Δfeature3)² + (Δfeature4)²]


The K historical bars (default 5) with the smallest distance are kept, these are the "nearest neighbors," i.e., the historical moments that most closely resembled the current setup across all four dimensions simultaneously.

Inverse Distance Weighted Forecasting (IDWF)

This is the forecasting step. For each of the K neighbors, the model already knows what actually happened: the real forward return that occurred over the next N bars (the "Forecast Bars Forward" setting) after that historical analog appeared.

Those K historical outcomes are blended into a single forecast using inverse distance weighting closer matches (smaller distance) get more influence over the final number than weaker matches:

forecast return = Σ(return × weight) / Σ(weight), where weight = 1 / distance


That weighted return is applied to the current close to produce the point target — the model's price forecast.

This entire approach:
  1. feature engineering
  2. standardization
  3. KNN
  4. Distance weighted aggregation


is a form of case-based / analog forecasting. It's the same family of technique used in some quantitative pattern-matching strategies and academic time series KNN research: rather than fitting one global formula to all market conditions, it lets the data itself decide what "similar" means, bar by bar.

How It Works on the Chart

Point-Forecast Lines

Once per closed bar, the model draws a flat, dashed, horizontal line at the calculated target price, extending forward indefinitely. Green lines mean the model's weighted forecast is bullish (target above current price); red means bearish.

Each line behaves like a real price target:

  • It disappears the instant price actually reaches it (high touches an upside target, or low touches a downside target).
  • It ages out automatically — only a capped number of lines (default 20, adjustable) are kept on screen. Once that cap is hit, the oldest surviving forecast is dropped to make room for the newest one.


Grouping Nearby Targets

Because a new forecast is generated every bar, it's common for the model to repeatedly point at roughly the same price over several bars in a row. Rather than stacking near duplicate lines, any new target that lands within a configurable percentage of an existing active target gets merged, the two are averaged into one line, and that line's label updates accordingly.

This has a useful side effect: the more a price level keeps attracting merges, the more "agreed upon" that level has been across many bars' worth of model runs informally, a cluster of merged calls is a stronger zone of interest than an isolated, never-revisited line.

Reading the Signals in Practice

This indicator is best treated as a contextual map of historically-analogous price targets, not a standalone buy/sell signal generator. A few practical ways to use it:

  1. Confluence, not isolation. Treat each TP line as one vote. A target line that lines up with an existing structural level (a prior swing high/low, VWAP, a round number) is more interesting than one floating in open air.
  2. Watch for clustering. Because nearby targets merge, a chart where forecasts keep collapsing into the same line over time is the model expressing genuine conviction about that price. A chart full of scattered, never-merged lines suggests the model is seeing a noisier, less consistent setup right now.
  3. Use Avg Fit Distance as a confidence dial. A low distance means "this is a well-worn pattern"; a high or rising distance means "this is a less familiar regime, be more skeptical of the target." % Bullish/Bearish tells you how unanimous the analogs are. 100%/0% is a much stronger statement than 60%/40%, even if the point target is identical.
  4. New forecasts only print once per closed bar (not on every tick), so the model won't spam new lines intrabar, but a line can still vanish intrabar the instant its target is actually touched.


Honest Limitations

This is a similarity heuristic, not a trained, validated, or backtested predictive model. "What happened after similar setups in the past" is not a guarantee of what happens next.

Small windows (low K, short lookback) make the model fast and reactive but noisier; large windows make it smoother but slower to adapt to genuine regime change.

Like any pattern-matching tool, it can be confidently wrong, a low Avg Fit Distance means the pattern matched well, not that the outcome is certain.

It's intended as one input among several in a broader trading process — not a substitute for risk management, market structure analysis, or your own judgment.


I hope you all enjoy and find it helpful!
As always, safe trades to all!

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.