Machine Learning: kNN-based Strategy
Dec 30, 2020

The Machine Learning: kNN-based Strategy indicator utilizes a classic k-Nearest Neighbors classification algorithm to predict future market moves based on historical price patterns and technical indicators.
Usage
The Usage section describes how the script can be used to identify potential market reversals or trend continuations. By analyzing historical data points (features) that most closely resemble current market conditions, the script classifies the current state as a potential buy or sell signal.
- Signal Interpretation: Labels appearing below the bar indicate a bullish prediction, while labels above the bar indicate a bearish prediction. The intensity of the label color corresponds to the strength of the prediction based on the consensus of the k-nearest neighbors.
- Indicator Modes: Users can choose which technical indicators serve as the "features" for the kNN algorithm. For example, selecting "RSI" will cause the algorithm to look for historical instances where RSI levels were similar to current levels to predict the next move.
- Volatility Filtering: When enabled, the strategy only generates signals during periods of higher relative volatility (ATR 10 > ATR 40), helping to avoid "choppy" or sideways markets where kNN might provide false signals.
Details
The script implements a two-dimensional k-Nearest Neighbors (kNN) algorithm. It collects historical data into three primary arrays: feature 1, feature 2, and directions (the resulting market move).
- Feature Selection: The script calculates "Short" and "Long" versions of a chosen indicator (RSI, ROC, CCI, or Volume). These two values represent the coordinates of the current market state in a 2D space.
- Distance Calculation: The algorithm calculates the Euclidean distance between the current state and all historical states stored in the arrays.
- Classification: It identifies the 'k' closest historical points (neighbors). If the majority of these neighbors resulted in a price increase, the script predicts a bullish move; if the majority resulted in a decrease, it predicts a bearish move.
- Repainting Note: Users should be aware that signals may repaint as the algorithm processes new data points and updates its internal arrays.
Settings
General Settings
- Start Date: Sets the beginning of the backtesting and data collection period.
- Stop Date: Sets the end of the data collection period.
- Indicator: Determines which technical indicator (RSI, ROC, CCI, Volume, or an Average of all) is used to generate the features for the kNN algorithm.
- Short Period [1..n]: The lookback period for the "fast" feature calculation.
- Long Period [2..n]: The lookback period for the "slow" feature calculation.
- Base No. of Neighbours (K) [5..n]: The base number of historical data points the algorithm considers. The actual K value used is the square root of this input.
- Volatility Filter: A toggle to restrict signals to periods where short-term volatility exceeds long-term volatility.
- Bar Threshold [2..5000]: Limits the duration a signal remains active before being cleared.
FAQ
How does the kNN algorithm make predictions? The kNN algorithm looks at historical instances where technical indicators were at similar levels to current values and checks whether the price moved up or down following those instances to provide a classification.
What does the color intensity of the labels mean? The transparency of the buy and sell labels is scaled based on the prediction's strength. A more solid color indicates a higher degree of consensus among the k-nearest neighbors.
How can I access the Machine Learning: kNN-based Strategy? 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.

