Indicator · Pine Script v4 · On the chart

Test 025 K-Means

by ricardosantos79· code credited to RicardoSantos

This script demonstrates an experimental implementation of the K-means clustering algorithm in Pine Script using array structures and a custom pseudo-random number generator.

View on GitHub

GitHub stars261on the repository
Pine versionv4older, still runs
Lines of code175
Settings2inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

175 lines of Pine Script v4 from beta/arrays/test-025-kmeans.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

test-025-kmeans.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=4
study("test-025-kmeans", overlay=true)

//| -------------------------------------------------------------------------------|
var float[] seed = array.new_float(size=1, initial_value=42.0)                  //-|
f_prng(_range)=>                                                              //---|
//| pseudo random function:                                                 // O O |
    var float _return = 1.0                                                 //- V -|
    float _seed = array.get(id=seed, index=0)                                //NNNN|
    float _reseed =  271.828                                                  // A |
    _return := ((3.1416 * _return % _seed) * _reseed) % _range                // V |
    array.set(id=seed, index=0, value=(1 + (_seed * 1.618) % _range) + _return) //||
    _return                                                                    // ||
//| -------------------------------------------------------------------------------|

f_kmeans_cluster(_X, _Y, _number_of_clusters)=>
//| Returns the cluster centers for the given data.
//| -----------------------------------------------
//| Inputs:
//|     _X: array x data points
//|     _Y: array y data points
//|
//|     _number_of_clusters: number of clusters to find center.
//|
//| Reference:
//| http://rosettacode.org/wiki/K-means%2B%2B_clustering
//| -----------------------------------------------------------
//| 1:  setup and errors
    int _X_size = array.size(id=_X)
    int _Y_size = array.size(id=_X)
    bool _size_match = _X_size == _Y_size
    bool _has_nclusters = _number_of_clusters > 0
    bool _data_over_clusters = _X_size > _number_of_clusters

    float[] _centers_x = array.new_float(size=0, initial_value=0.)
    float[] _centers_y = array.new_float(size=0, initial_value=0.)
    int[] _centers_count = array.new_int(size=_number_of_clusters, initial_value=1)
    
    float[] _distances = array.new_float(size=0, initial_value=0.)
    int[] _group = array.new_int(size=0, initial_value=0)
    
    if _has_nclusters and _data_over_clusters and _size_match
//| 2:  initial cluster centers
//|     can use alternative method of initialization (kmeans++, random) for now will only use random
        for _i = 0 to _number_of_clusters - 1
            int _value = int(f_prng(_X_size))
            array.push(id=_centers_x, value=array.get(id=_X, index=_value))
            array.push(id=_centers_y, value=array.get(id=_Y, index=_value))
//|     2.b: calculate distances to centers:
        for _i = 0 to _number_of_clusters - 1
            float _total_sum_of_distance = 0.0
            for _j = 0 to _X_size - 1
                float _x = array.get(id=_X, index=_j)
                float _y = array.get(id=_Y, index=_j)
                //  calculate distance to cluster and populate the _group
                int _min_group = 0
                float _min_distance = sqrt(pow(_x - array.get(id=_centers_x, index=0), 2) + pow(_y - array.get(id=_centers_x, index=0), 2))
                for _k = 1 to _number_of_clusters - 1
                    float _c_x = array.get(id=_centers_x, index=_k)
                    float _c_y = array.get(id=_centers_y, index=_k)
                    float _distance = sqrt(pow(_x - _c_x, 2) + pow(_y - _c_y, 2))//some examples did not sqrt
                    if _distance < _min_distance
                        _min_distance := _distance
                        _min_group := _k
                array.push(id=_group, value=_min_group)
                array.push(id=_distances, value=_min_distance)
                _total_sum_of_distance := _total_sum_of_distance + _min_distance
            
            _total_sum_of_distance := _total_sum_of_distance * f_prng(1.0)
            
            for _j = 0 to _X_size - 1
                _total_sum_of_distance := _total_sum_of_distance - array.get(id=_group, index=_j)
                if _total_sum_of_distance > 0
                    continue
                else
                    array.set(id=_centers_x, index=_i, value=array.get(id=_X, index=_j))
                    array.set(id=_centers_y, index=_i, value=array.get(id=_Y, index=_j))
                    break
//| 3:  Choose center with probability proportional to its squared distance from existing centers.
            for _j = 0 to _X_size - 1
                float _x = array.get(id=_X, index=_j)
                float _y = array.get(id=_Y, index=_j)
                //  calculate distance to cluster and populate the _group
                int _min_group = 0
                float _min_distance = sqrt(pow(_x - array.get(id=_centers_x, index=0), 2) + pow(_y - array.get(id=_centers_x, index=0), 2))
                for _k = 1 to _number_of_clusters - 1
                    float _c_x = array.get(id=_centers_x, index=_k)
                    float _c_y = array.get(id=_centers_y, index=_k)
                    float _distance = sqrt(pow(_x - _c_x, 2) + pow(_y - _c_y, 2))//some examples did not sqrt
                    if _distance < _min_distance
                        _min_distance := _distance
                        _min_group := _k
                array.set(id=_group, index=_j, value=_min_group)
                array.set(id=_distances, index=_j, value=_min_distance)                
//| 4:  find cluster centers.
        for _i = 0 to _X_size - 1
            float _x = array.get(id=_X, index=_i)
            float _y = array.get(id=_Y, index=_i)
            int _group_i = array.get(id=_group, index=_i)
            
            int _center_count = array.get(id=_centers_count, index=_group_i)
            float _center_x = array.get(id=_centers_x, index=_group_i)
            float _center_y = array.get(id=_centers_y, index=_group_i)
            array.set(id=_centers_count, index=_group_i, value=_center_count + 1)
            array.set(id=_centers_x, index=_group_i, value=_center_x + _x)
            array.set(id=_centers_y, index=_group_i, value=_center_y + _y)
        
        for _i = 0 to _number_of_clusters - 1
            int _center_count = array.get(id=_centers_count, index=_i)
            float _center_x = array.get(id=_centers_x, index=_i)
            float _center_y = array.get(id=_centers_y, index=_i)
            
            array.set(id=_centers_x, index=_i, value=_center_x / _center_count)
            array.set(id=_centers_y, index=_i, value=_center_y / _center_count)
//| 6:  Output.
    [_centers_x, _centers_y]


if barstate.isfirst
    array.set(id=seed, index=0, value=1337)

int[] X = array.new_int(size=0, initial_value=0)
float[] Y = array.new_float(size=0, initial_value=0)

ndata = input(20)
nclusters = input(3)
for _i = 0 to ndata
    array.push(id=X, value=bar_index[_i])
    array.push(id=Y, value=close[_i])

[CX, CY] = f_kmeans_cluster(X, Y, nclusters)

// sort centers by ascending index:
CX_size = array.size(id=CX) - 1

float[] tX = array.new_float(size=0, initial_value=0)
float[] tY = array.new_float(size=0, initial_value=0)

for _i = 0 to CX_size
    int _index = array.indexof(id=CX, value=array.min(id=CX))
    array.push(id=tX, value=array.remove(id=CX, index=_index))
    array.push(id=tY, value=array.remove(id=CY, index=_index))


color _cdiv_col = color.red
string _xtend = extend.both
var line _cdiv00 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv01 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv02 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv03 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv04 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv05 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv06 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv07 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv08 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
var line _cdiv09 = line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, extend=_xtend, color=_cdiv_col, style=line.style_solid, width=2)
f_cdiv_line_selector(_i)=>(_i==0?_cdiv00:(_i==1?_cdiv01:(_i==2?_cdiv02:(_i==3?_cdiv03:(_i==4?_cdiv04:(_i==5?_cdiv05:(_i==6?_cdiv06:(_i==7?_cdiv07:(_i==8?_cdiv08:(_i==9?_cdiv09:_cdiv00))))))))))

// plot the lines
for _i = 0 to min(8, max(0, nclusters - 2))
    int _cx1 = round(array.get(id=tX, index=_i))
    int _cx2 = round(array.get(id=tX, index=_i+1))
    float _cy1 = array.get(id=tY, index=_i)
    float _cy2 = array.get(id=tY, index=_i+1)
    line.set_xy1(id=f_cdiv_line_selector(_i), x=_cx2, y=_cy1)
    line.set_xy2(id=f_cdiv_line_selector(_i), x=_cx1, y=_cy2)

t = 'Coordinates of cluster centers:\nindex:' + tostring(tX, '#') + '\nprice:' + tostring(tY)

var label debug = label.new(bar_index, 0.0, '')
label.set_xy(id=debug, x=bar_index, y=0.0)
label.set_text(id=debug, text=t)

Overview

Test 025 K-Means partitions a dataset into a specified number of clusters based on Euclidean distance calculations from initialized center points. Users can adjust the amount of historical data evaluated and the total cluster count. It serves as an overlay proof-of-concept for unsupervised machine learning techniques within Pine Script.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

AI / machine learning

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
ndataint20ndata
nclustersint3nclusters
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This indicator uses a Lorentzian distance k-nearest neighbors classification algorithm to predict market direction based on up to five technical features, such as RSI, WaveTrend, CCI, and ADX. It compares current feature values against historical bar patterns

Indicator v5 AI / machine learningOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of Donald - Machine Learning Options

AI Trend Navigator

by hasnocool
106 stars

This indicator calculates a trend direction and smoothed moving average using a k-nearest neighbours (k-NN) classification algorithm directly on the main price chart. Users can select input price types, target values, neighborhood size, and smoothing periods.

Indicator v5 AI / machine learningTrend
Updated 2 years ago · GPL-3.0 GitHub repository of AI Trend Navigator

Machine Learning: Lorentzian Classification

by artificial-intelligence-edge
75 stars

This indicator classifies the current bar by comparing its feature vector with historical bars using Lorentzian distance and a k-nearest-neighbors vote. Configurable features include RSI, WaveTrend, CCI, and ADX. Optional volatility, regime, ADX, and EMA filte

Indicator v5 AI / machine learningOscillators & momentum
Updated 2 days ago · MIT GitHub repository of Machine Learning: Lorentzian Classification
47 stars

Calculates and plots a forward price prediction directly on the main chart using an on-chart multilayer perceptron neural network. The model processes technical input features including moving average ratios, RSI, normalized ATR, and Bollinger bandwidth throug

Indicator v6 AI / machine learning
Updated 8 months ago · MIT GitHub repository of Multilayer Perceptron Predictor
46 stars

This indicator uses a Hidden Markov Model (HMM) framework combined with an adaptive dual moving average engine and Directional Movement Index (DMI) features to identify market regimes (bullish, bearish, or ranging/chop). It calculates regime probabilities on e

Indicator v5 AI / machine learningTrend
Updated 7 weeks ago · None stated GitHub repository of HMM Enhanced: Regime Probability

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers