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

//@version=5
indicator(title='test - pattern similarity')

import RicardoSantos/FunctionPatternDecomposition/1 as decompose
import RicardoSantos/FunctionCosineSimilarity/1 as similarity

im(float source, int length, float smooth=0.7, float thin=0.7, int msize=5)=>
    var _data = array.new_float(length, source), array.push(_data, source), array.shift(_data)
    [_x, _y] = decompose.smooth_data_2d(_data, smooth)
    [_tx, _ty] = decompose.thin_points(_x, _y, thin)
    float[] _m = decompose.grid_coordinates(_tx, _ty, msize)

float src = input.source(close)
int length = input.int(12)
float smooth = input.float(0.7)
float thin = input.float(0.7)
int msize = input.int(5)

string ticker1 = input.symbol('AAPL')
string ticker2 = input.symbol('MSFT')
float s1 = request.security(ticker1, timeframe.period, src)
float s2 = request.security(ticker2, timeframe.period, src)

float[] m1 = im(s1, length, smooth, thin, msize)
float[] m2 = im(s2, length, smooth, thin, msize)

cs = similarity.function(m1, m2)
avg = ta.cum(cs) / (bar_index + 1)

plot(series=cs, title='similarity', color=color.blue)
plot(series=avg, title='average', color=color.yellow)

m_tostring(sample, int cols)=>
    int _size = array.size(sample)
    string _str = ''
    for _i = 0 to (_size - 1)
        _str += str.tostring(array.get(sample, _i), '0')
        if _i != (_size - 1)
            _str += ' '
        if (_i % cols) == (cols - 1)
            _str += '\n'
    _str
    
var t_ = table.new(position.bottom_left, 1, 2)
table.cell(t_, 0, 0, m_tostring(m1, msize), text_color=color.silver, bgcolor=#000000)
table.cell(t_, 0, 1, m_tostring(m2, msize), text_color=color.silver, bgcolor=#000000)
