Machine Learning: kNN (New Approach)
Sep 16, 2022

The Machine Learning: kNN (New Approach) indicator utilizes a modified K-Nearest Neighbors algorithm to classify price data and predict future price movements based on historical proximity. This tool provides a smoothed trend-following curve and directional forecasts, offering a robust alternative to traditional moving averages and statistical models like SVM or Random Forest.
Usage
The Usage section describes how the script can be used to identify market trends and potential reversals. The indicator processes a series of price points to determine the "nearest neighbors" in a one-dimensional data space, which are then averaged to produce a prediction.
- Trend Identification: The primary output is a smooth curve that approximates the behavior of a Simple Moving Average (SMA). Users can observe the color and slope of this curve to determine the current market regime.
- Price Projection: The script provides a forward-looking "Predict" point (displayed as a circle) that suggests where the price might move in the next bar relative to the current projection base.
- Directional Hints: By analyzing the relationship between the prediction and the input data, the indicator highlights bullish or bearish shifts through color transitions.
Details
The K-Nearest Neighbors (kNN) algorithm is a non-parametric method used for classification and regression. In this implementation, the logic is adapted for time-series data:
- Feature Construction: The script creates training records by taking consecutive price points. By default, it uses a window of 10 data points to establish the predictor values.
- Distance Calculation: It calculates the one-dimensional Euclidean distance (absolute difference) between the current instance and historical samples.
- Neighbor Selection: It ranks these distances to identify the "K" number of nearest neighbors based on the minimum distance.
- Averaging: The final prediction is the average of these identified nearest neighbors.
A unique modification in this "New Approach" allows the kNN curve to behave similarly to an SMA (specifically an SMA(20) when settings are tuned to approximately N=17), but with the added benefit of machine learning-based responsiveness to local price clusters.
Settings
- Resolution: Sets the timeframe from which the data is pulled for the kNN calculation.
- # of Data Points [2:n]: Determines the window size of consecutive prices used to create training records.
- # of Nearest Neighbors (K) [1:252]: Defines the number of historical neighbors to consider when calculating the average prediction.
- Adjust Prediction: A toggle to adjust the directional logic based on the current bar versus the previous bar.
- Non-Repainting: When enabled, the indicator uses closed bar data to ensure signals do not change after the bar closes.
- Add-On: Allows the user to filter directional signals using secondary logic:
- None: Standard kNN directional logic.
- Pivot Point: Filters signals based on high/low pivot detection.
- Z-Score: Filters signals based on statistical deviation from the mean.
- Pivot Point Lag / Z-Score Lag: Adjusts the lookback period for the respective Add-On filters.
- Show Outcomes: Controls the visual output (Curve only, Prediction point only, or Both).
- Projection Base: The price source (e.g., hlcc4) used as the basis for the projection.
FAQ
How does this differ from a standard Moving Average? While it looks like a moving average, the kNN approach selects data points based on their similarity (distance) in value rather than just their chronological order, allowing it to adapt more dynamically to price clusters.
What is the purpose of the "Add-On" setting? The Add-On setting provides a statistical filter (like Z-Score) or a structural filter (like Pivot Points) to confirm the kNN prediction, helping to reduce noise in sideways markets.
How can I access this tool? You can get access on the LuxAlgo Library for charting platforms like TradingView, MetaTrader (MT4/MT5), and NinjaTrader for free.
Trading & investing are risky and many will lose money in connection with trading and investing activities. All content on this site is not intended to, and should not be, construed as financial advice. Decisions to buy, sell, hold or trade in securities, commodities and other investments involve risk and are best made based on the advice of qualified financial professionals. Past performance does not guarantee future results.
Hypothetical or Simulated performance results have certain limitations. Unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not been executed, the results may have under-or-over compensated for the impact, if any, of certain market factors, including, but not limited to, lack of liquidity. Simulated trading programs in general are designed with the benefit of hindsight, and are based on historical information. No representation is being made that any account will or is likely to achieve profit or losses similar to those shown.
Testimonials appearing on this website may not be representative of other clients or customers and is not a guarantee of future performance or success.
As a provider of technical analysis tools and strategies, we do not have access to the personal trading accounts or brokerage statements of our customers. As a result, we have no reason to believe our customers perform better or worse than traders as a whole based on any content, tool, or platform feature we provide.
Charts used on this site are by TradingView in which the majority of our technical indicators are built on. TradingView® is a registered trademark of TradingView, Inc. www.TradingView.com TradingView® has no affiliation with the owner, developer, or provider of the Services described herein.
Market data is provided by CBOE, CME Group, BarChart, Massive, CoinAPI. Select U.S. equities data is provided through Massive. CBOE BZX real-time U.S. equities data is licensed from CBOE and provided through BarChart. Real-time futures data is licensed from CME Group and provided through BarChart. Select cryptocurrency data, including major coins, is provided through CoinAPI. All data is provided “as is” and should be verified independently for trading purposes.
This does not represent our full Disclaimer. Please read our full disclaimer.
© 2026 LuxAlgo Global, LLC.

