Implementing K-Nearest Neighbors for Classification in MQL5
Summary
This article introduces K-nearest neighbors as a non-parametric method for classification and regression, then walks through a classifier implemented in MQL5. For a new observation, the method calculates its Euclidean distance from labeled examples, selects the nearest k observations, and assigns the class with the most votes. The tutorial discusses choosing k, including an automatic default based on the square root of the sample count and making an even value odd, and demonstrates classification on a small weight-and-height dataset.
The author also describes applying the method to trading data in an Expert Advisor. KNN is presented as easiest to use with labeled, relatively small datasets, but prediction requires retaining and comparing against the training data. The article reports that its implementation caused long pauses in strategy testing, even when invoked once per new bar. It suggests that the approach may be explored for stocks and indices, but supplies no evidence of predictive trading performance. Feature scaling, data quality, and distance choice also affect whether nearest examples are meaningfully similar.
Key ideas
- KNN classifies a new point by voting among the closest labeled observations.
- The tutorial uses Euclidean distance and discusses selecting an odd neighbor count.
- The worked example classifies a point using weight and height features.
- KNN stores the training set and repeats distance calculations for each prediction.
- The reported MQL5 implementation was slow in the strategy tester and has no demonstrated trading edge.
Tags
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.