# kNN Analog Forecasting

Also known as: nearest-neighbor pattern matching.
A Machine Learning concept (Similarity & memory) in the LuxAlgo Library, with 7 indicator implementations.

## What is kNN Analog Forecasting?

kNN analog forecasting applies the k-nearest-neighbors method to price history. The current market state is encoded as a vector, typically a window of recent normalized returns, prices, or indicator readings assembled through [feature engineering](https://www.luxalgo.com/library/concept/feature-engineering/). The algorithm searches the historical record for the k windows most similar to the present one, usually by Euclidean distance, and treats what followed those analogs as the forecast: averaging the subsequent paths gives a projection, letting the neighbors vote gives a directional call. It is memory-based learning. There is no training step and no fitted equation, only the stored history plus a handful of design choices: the features, the window length, the distance measure, and k.

The appeal is transparency: you can inspect exactly which past episodes drive today's forecast, making it the quantitative version of the analog charts traders have long drawn. The weaknesses are equally concrete. Markets are non-stationary, so states that look alike in feature space are not guaranteed to resolve alike; adjacent historical windows overlap, so neighbors are rarely independent; and everything hinges on normalization ([z-scores](https://www.luxalgo.com/library/concept/z-score/) or [min-max scaling](https://www.luxalgo.com/library/concept/min-max-scaling/) are typical), because raw price levels from different years are not comparable. Treat the output as a set of historical scenarios, not a prediction.

## How to build a kNN analog forecast

Every implementation follows the same four moves; the choices inside each one are where results diverge.

1. Encode the present: choose features and a window length, normalize them, and stack the recent values into a single vector.
2. Measure similarity: compute the distance, usually Euclidean, between that vector and every comparable window in the historical record.
3. Select neighbors: keep the k smallest distances, ideally skipping windows that overlap one another so the analogs are closer to independent.
4. Aggregate outcomes: average the k subsequent paths for a projection, or tally each neighbor's resolution for a directional vote, optionally weighting nearer neighbors more.

## How traders use it

- As projection overlays: the paths that followed the nearest historical analogs are averaged and drawn forward from the current bar, a data-driven forecast curve rather than a model-based extrapolation.
- As a direction classifier: each neighbor votes up or down over the chosen horizon and the majority becomes the bullish or bearish reading; inputs are often oscillator values such as [RSI](https://www.luxalgo.com/library/concept/rsi/) rather than raw price.
- As a filter on a base system: before a rule-based signal fires, the kNN layer checks whether similar past states resolved favorably and suppresses entries whose analogs performed poorly.
- With honest validation: neighbors come from the same history the signal is judged on, so look-ahead leaks in easily; an [in-sample / out-of-sample split](https://www.luxalgo.com/library/concept/in-sample-out-of-sample-split/) or walk-forward test is the minimum before trusting reported accuracy.

## kNN Analog Forecasting vs related methods

- **Monte Carlo Price Paths** (https://www.luxalgo.com/library/concept/monte-carlo-price-paths/): Monte Carlo also projects forward paths, but it samples randomly from a return distribution; kNN replays specific historical episodes selected for their similarity to the present state.
- **Exponential Smoothing Forecasts** (https://www.luxalgo.com/library/concept/exponential-smoothing-forecasts/): Exponential smoothing extrapolates a fitted level, plus a trend term in trended variants, from recent data; kNN assumes no functional form and forecasts from whatever the closest historical matches actually did next.
- **Kernel Regression** (https://www.luxalgo.com/library/concept/kernel-regression/): Kernel regression weights every observation continuously by distance; kNN makes a hard cut, using only the k closest matches and ignoring the rest of the record entirely.

## FAQ

### How many neighbors should k be in kNN forecasting?

There is no universally correct k. A very small k leaves the forecast hostage to a few possibly unrepresentative episodes, while a very large k averages toward the unconditional mean and says little. Practitioners test a range and often prefer distance-weighted votes, which soften the choice. Whatever the value, verify it out of sample, because k is an easy parameter to overfit.

### Does kNN analog forecasting actually predict price?

It replays what followed the most similar past states, which is a scenario, not a certainty. Markets are non-stationary, so lookalike states can resolve very differently, and overlapping windows exaggerate the apparent agreement among neighbors. The honest use is as a conditional base rate, a summary of what usually happened here, combined with independent confirmation rather than traded on alone.

### What inputs does nearest-neighbor pattern matching compare?

Anything that fits in a vector: windows of normalized returns or prices, oscillator readings, volatility measures, or several of these stacked together. Normalization is the critical step, since Euclidean distance on raw prices makes past regimes incomparable to today. Feature choice matters more than the algorithm itself; irrelevant inputs dilute the distance measure and degrade neighbor quality.

## Implementations in the Library

- The Echo Forecast (LuxAlgo): https://www.luxalgo.com/library/indicator/the-echo-forecast/
- Historical Price Projection (LuxAlgo): https://www.luxalgo.com/library/indicator/historical-price-projection/
- kNN Market Architecture (LuxAlgo): https://www.luxalgo.com/library/indicator/knn-market-architecture/
- Indicator Configuration Forecasting (LuxAlgo): https://www.luxalgo.com/library/indicator/indicator-configuration-forecasting/
- KNN Supertrend Horizon (LuxAlgo): https://www.luxalgo.com/library/indicator/knn-supertrend-horizon/
- Neighboring Trailing Stop (LuxAlgo): https://www.luxalgo.com/library/indicator/neighboring-trailing-stop/
- MACD Based Price Forecasting (LuxAlgo): https://www.luxalgo.com/library/indicator/macd-based-price-forecasting/

## Related concepts

- Dynamic Time Warping Similarity: https://www.luxalgo.com/library/concept/dynamic-time-warping-similarity/
- Matrix Profile: https://www.luxalgo.com/library/concept/matrix-profile/

---

Source: https://www.luxalgo.com/library/concept/knn-analog-forecasting/ (LuxAlgo Library, the encyclopedia of trading & technical analysis). Free to use with attribution: https://www.luxalgo.com/library/license/