PINE LIBRARY
kNNLorentzianMachineLearning

A high-performance, quant-grade machine learning library written in Pine Script v6, implementing a k-Nearest Neighbors (kNN) classification engine optimized for algorithmic trading. This library features a zero-data-leakage architecture, dynamic memory pre-allocation, and a specialized distance metric designed to evaluate historical market state similarities efficiently.
🔷 Introduction
For quantitative and algorithmic traders using TradingView and Pine Script v6, this library provides an institutional-grade machine learning architecture that moves far beyond basic, traditional technical indicators.
When it comes to feature scalability, the engine is designed to handle a dynamic and unrestricted number of features. You simply pass an array of your chosen technical features, and the library automatically adapts its internal matrix structure to accommodate them. The matrix allocates columns for your features while reserving the final column specifically for the historical target direction. For optimal performance and to avoid the curse of dimensionality—where distance metrics lose precision in overly complex spaces—it is best to use a compact, orthogonal set of three to eight features, such as balanced combinations of momentum, volatility, and volume indicators.
A critical advantage for backtesting integrity is the zero-data-leakage design. In quantitative finance, accidentally including contemporaneous or future information in historical calculations invalidates your results. This library forces the historical scanning loop to start at index one instead of zero, completely excluding the active current bar from the distance calculation pool. This eliminates lookahead bias entirely and ensures your backtest results reflect true historical precedents.
To handle market noise, the library uses a Lorentzian distance metric with a logarithmic transformation. Standard Euclidean distance metrics often break down during flash crashes or extreme macroeconomic volatility spikes because outliers heavily distort the results. The logarithmic transformation dampens the impact of extreme values, stabilizing the kNN classification engine during turbulent market regimes.
From a performance and runtime perspective, the library implements advanced memory management. By using pre-allocated temporary matrices, it avoids the heavy heap thrashing caused by constant dynamic resizing. Furthermore, the step-size parameter allows the engine to sample historical bars by skipping intervals, meaning you can run deep historical lookbacks across thousands of bars without hitting Pine Script execution timeouts.
Finally, the engine delivers probabilistic confidence scoring rather than rigid binary signals. It evaluates the top-k nearest neighbors and computes a directional confidence ratio. Signals are only triggered when this confidence score breaches your configured threshold, giving algorithmic traders a reliable filter for risk management. Combined with recursive safety checks that catch missing values before they can crash your script, this library offers a robust foundation for live quantitative execution.
🔷 Key Technical Features
🔹 Robust Min-Max Feature Normalization [f_minmax]
🔹 Historical Matrix State Management [f_update_history_matrix]
🔹 Optimized kNN Classification Engine [f_calc_knn_matrix]
🔷 Function Signatures & API Reference
🔹 f_minmax(src, len)
Normalizes a data series between 0 and 100 using a rolling lookback window.
Return Type: float
🔹 f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Appends validated feature vectors and target directions to the historical memory matrix.
Return Type: void
🔹 f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Executes the kNN distance scan, sorting, and institutional confidence calculation.
Return Type: [int, float]
Below find a script example to quickly test the library.
Pine Script®
-----------------------------------------------------------------------------
f_minmax(src, len)
Parameters:
src (float): (float) The raw data series to normalize (e.g., RSI, CCI, Momentum).
len (int): (int) Lookback period for determining the rolling minimum and maximum.
Returns: (float) The normalized value scaled from 0 to 100, or a default midpoint (50.0) on structural failure.
-----------------------------------------------------------------------------
f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Parameters:
hist_matrix (matrix<float>): (matrix<float>) The reference matrix storing historical feature rows and targets.
current_features (array<float>): (array<float>) The current bar's feature vector array to evaluate and ingest.
target_direction (float): (float) The label/target outcome for the current state (e.g., 1.0 for up, 0.0 for down).
max_lookback (int): (int) Maximum allowed row capacity for the history buffer to control memory footprint.
Returns: (void) Mutates the history matrix in place.
-----------------------------------------------------------------------------
f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Parameters:
k_neighbors (int): (int) Number of nearest neighbors to query for classification.
threshold (float): (float) Confidence probability boundary required to trigger a directional signal (e.g., 0.6).
current_features (array<float>): (array<float>) The live feature vector evaluated against historical instances.
hist_matrix (matrix<float>): (matrix<float>) The historical memory matrix containing past states and targets.
step_size (int): (int) Sampling step size interval to optimize heavy runtime loops.
Returns: (tuple) Returns [raw_signal, confidence] where signal is 1, -1, or 0, and confidence is a float ratio.
-----------------------------------------------------------------------------
🔷 Introduction
For quantitative and algorithmic traders using TradingView and Pine Script v6, this library provides an institutional-grade machine learning architecture that moves far beyond basic, traditional technical indicators.
When it comes to feature scalability, the engine is designed to handle a dynamic and unrestricted number of features. You simply pass an array of your chosen technical features, and the library automatically adapts its internal matrix structure to accommodate them. The matrix allocates columns for your features while reserving the final column specifically for the historical target direction. For optimal performance and to avoid the curse of dimensionality—where distance metrics lose precision in overly complex spaces—it is best to use a compact, orthogonal set of three to eight features, such as balanced combinations of momentum, volatility, and volume indicators.
A critical advantage for backtesting integrity is the zero-data-leakage design. In quantitative finance, accidentally including contemporaneous or future information in historical calculations invalidates your results. This library forces the historical scanning loop to start at index one instead of zero, completely excluding the active current bar from the distance calculation pool. This eliminates lookahead bias entirely and ensures your backtest results reflect true historical precedents.
To handle market noise, the library uses a Lorentzian distance metric with a logarithmic transformation. Standard Euclidean distance metrics often break down during flash crashes or extreme macroeconomic volatility spikes because outliers heavily distort the results. The logarithmic transformation dampens the impact of extreme values, stabilizing the kNN classification engine during turbulent market regimes.
From a performance and runtime perspective, the library implements advanced memory management. By using pre-allocated temporary matrices, it avoids the heavy heap thrashing caused by constant dynamic resizing. Furthermore, the step-size parameter allows the engine to sample historical bars by skipping intervals, meaning you can run deep historical lookbacks across thousands of bars without hitting Pine Script execution timeouts.
Finally, the engine delivers probabilistic confidence scoring rather than rigid binary signals. It evaluates the top-k nearest neighbors and computes a directional confidence ratio. Signals are only triggered when this confidence score breaches your configured threshold, giving algorithmic traders a reliable filter for risk management. Combined with recursive safety checks that catch missing values before they can crash your script, this library offers a robust foundation for live quantitative execution.
🔷 Key Technical Features
🔹 Robust Min-Max Feature Normalization [f_minmax]
- Dynamic Bounding: Computes local maximums and minimums over a configurable lookback window to normalize raw source values.
- Edge-Case Safety: Implements strict safeguards against division by zero and na propagation, defaulting to a median scale baseline [50.0] when ranges collapse or data is unavailable.
🔹 Historical Matrix State Management [f_update_history_matrix]
- Integrity Validation: Performs deep array inspection to ensure all feature vectors are free of na values before ingestion.
- Bounded Rolling Buffer: Automatically maintains a sliding window of historical states, capping memory growth by removing oldest records once the [max_lookback] threshold is exceeded.
🔹 Optimized kNN Classification Engine [f_calc_knn_matrix]
- Zero Data Leakage: Explicitly offsets historical iteration starting points (beginning at index 1) to prevent current-bar lookahead bias.
- Memory Optimization & Pre-allocation: Reduces runtime overhead through dynamic step-size sampling [step_size] and pre-allocated temporary matrix architecture.
- Lorentzian Distance Adaptation: Utilizes a logarithmic transformation metric to compute feature distance matrices, mitigating the distorting effects of market outliers.
- Confidence Scoring: Aggregates directional outcomes from the top-k nearest neighbors to output a bounded probability metric and a threshold-filtered trading score [+1, -1, 0].
🔷 Function Signatures & API Reference
🔹 f_minmax(src, len)
Normalizes a data series between 0 and 100 using a rolling lookback window.
Return Type: float
🔹 f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Appends validated feature vectors and target directions to the historical memory matrix.
Return Type: void
🔹 f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Executes the kNN distance scan, sorting, and institutional confidence calculation.
Return Type: [int, float]
Below find a script example to quickly test the library.
-----------------------------------------------------------------------------
f_minmax(src, len)
Parameters:
src (float): (float) The raw data series to normalize (e.g., RSI, CCI, Momentum).
len (int): (int) Lookback period for determining the rolling minimum and maximum.
Returns: (float) The normalized value scaled from 0 to 100, or a default midpoint (50.0) on structural failure.
-----------------------------------------------------------------------------
f_update_history_matrix(hist_matrix, current_features, target_direction, max_lookback)
Parameters:
hist_matrix (matrix<float>): (matrix<float>) The reference matrix storing historical feature rows and targets.
current_features (array<float>): (array<float>) The current bar's feature vector array to evaluate and ingest.
target_direction (float): (float) The label/target outcome for the current state (e.g., 1.0 for up, 0.0 for down).
max_lookback (int): (int) Maximum allowed row capacity for the history buffer to control memory footprint.
Returns: (void) Mutates the history matrix in place.
-----------------------------------------------------------------------------
f_calc_knn_matrix(k_neighbors, threshold, current_features, hist_matrix, step_size)
Parameters:
k_neighbors (int): (int) Number of nearest neighbors to query for classification.
threshold (float): (float) Confidence probability boundary required to trigger a directional signal (e.g., 0.6).
current_features (array<float>): (array<float>) The live feature vector evaluated against historical instances.
hist_matrix (matrix<float>): (matrix<float>) The historical memory matrix containing past states and targets.
step_size (int): (int) Sampling step size interval to optimize heavy runtime loops.
Returns: (tuple) Returns [raw_signal, confidence] where signal is 1, -1, or 0, and confidence is a float ratio.
-----------------------------------------------------------------------------
Libreria Pine
Nello spirito di TradingView, l'autore ha pubblicato questo codice Pine come libreria open source affinché altri programmatori della nostra community possano riutilizzarlo. Complimenti all'autore! È possibile utilizzare questa libreria privatamente o in altre pubblicazioni open source, ma il riutilizzo di questo codice nelle pubblicazioni è soggetto al Regolamento.
🔥 Unlock the power of Symbiosis, the first Python XGBoost model natively built for Pine Script. Grab the last available spots on Patreon: patreon.com/c/xgboost_symbiosis
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Libreria Pine
Nello spirito di TradingView, l'autore ha pubblicato questo codice Pine come libreria open source affinché altri programmatori della nostra community possano riutilizzarlo. Complimenti all'autore! È possibile utilizzare questa libreria privatamente o in altre pubblicazioni open source, ma il riutilizzo di questo codice nelle pubblicazioni è soggetto al Regolamento.
🔥 Unlock the power of Symbiosis, the first Python XGBoost model natively built for Pine Script. Grab the last available spots on Patreon: patreon.com/c/xgboost_symbiosis
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.