Indicator · Pine Script v6 · Own pane

Multi Asset Similarity Matrix

by regalouisei· code credited to RicardoSantos

This indicator builds a pairwise similarity matrix for a user-supplied list of assets, defaulting to major stock indices.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code142
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago25 Feb 2026

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

142 lines of Pine Script v6 from pinescript/editors_picks/multi-asset-similarity-matrix.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

multi-asset-similarity-matrix.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=6
string LTITLE = 'Multi Asset Similarity Matrix'
string STITLE = 'MASM'
indicator(LTITLE, STITLE, false)


// Provides a unique and visually stunning way to analyze the similarity between various stock market indices. This script uses a range of mathematical measures to calculate the correlation between different assets, such as indices, forex, crypto, etc..
// Key Features:
// Similarity Measures: The script offers a range of similarity measures to choose from, including SSD (Sum of Squared Differences), Euclidean Distance, Manhattan Distance, Minkowski Distance, Chebyshev Distance, Correlation Coefficient, Cosine Similarity, Camberra Index, Mean Absolute Error (MAE), Mean Squared Error (MSE), Lorentzian Function, Intersection, and Penrose Shape.
// Asset Selection: Users can select the assets they want to analyze by entering a comma-separated list of tickers in the "Asset List" input field.
// Color Gradient: The script uses a color gradient to represent the similarity values between each pair of indices, with red indicating low similarity and blue indicating high similarity.
// How it Works:
// The script calculates the source method (Returns or Volume Modified Returns) for each index using the sec function.
// It then creates a matrix to hold the current values of each index over a specified window size (default is 10).
// For each pair of indices, it applies the selected similarity measure using the select function and stores the result in a separate matrix.
// The script calculates the maximum and minimum values of the similarity matrix to normalize the color gradient.
// Finally, it creates a table with the index names as rows and columns, displaying the similarity values for each pair of indices using the calculated colors.
// Visual Insights:
// The indicator provides an intuitive way to visualize the relationships between different assets. By analyzing the color-coded tables, traders can gain insights into:
// Which assets are highly correlated (blue) or uncorrelated (red)
// The strength and direction of these correlations
// Potential trading opportunities based on similarities and differences between assets
// Overall, MASM is a powerful tool for market analysis and visualization, offering a unique perspective on the relationships between various assets.
// ~llama3

//#region    Similarity functions
import RicardoSantos/SimilarityMeasures/2 as sm

enum M
    SSD
    Euclidean
    Manhattan
    Minkowski
    Chebyshev
    Correlation
    Cosine
    Camberra
    MAE
    MSE
    Lorentzian
    Intersection
    PenroseShape
    Meehl

// @function Select the method of measure.
select (M m, float[] a, float[] b) =>
    switch m
        M.SSD            => sm.ssd(a, b)
        M.Euclidean        => sm.euclidean(a, b)
        M.Manhattan        => sm.manhattan(a, b)
        M.Minkowski        => sm.minkowski(a, b)
        M.Chebyshev        => sm.chebyshev(a, b)
        M.Correlation    => sm.correlation(a, b)
        M.Cosine        => sm.cosine(a, b)
        M.Camberra        => sm.camberra(a, b)
        M.MAE            => sm.mae(a, b)
        M.MSE            => sm.mse(a, b)
        M.Lorentzian    => sm.lorentzian(a, b)
        M.Intersection    => sm.intersection(a, b)
        M.PenroseShape    => sm.penrose(a, b)
        M.Meehl            => sm.meehl(a, b)

//#endregion
//#region    Inputs:

enum MSRC
    R  = 'Returns'
    RV = 'Volume Modified Returns'

int window = input.int(10, 'Window:')
MSRC srcmethod = input.enum(MSRC.R, 'Source Method:')
M mmethod = input.enum(M.Cosine, 'Similarity Measure Method:')
string tickers = input.text_area('NAS100,SPX500,DJI, IBXX, N100, EU500, UKX, JP225USD, NIFTY, CN50USD, HSI, NZ50G, MOEX', 'Asset List:')
color grad1 = input.color(color.maroon, 'Gradient Colors:', inline='1')
color grad2 = input.color(color.blue, '', inline='1')
int ndigits = input.int(5, 'Number of Digits:')

var string fdigits = '0.'
if barstate.isfirst
    for _i = 1 to ndigits
        fdigits += '0'

sec (string t) => 
    float _src = na
    switch srcmethod
        MSRC.R => _src := close / close[1]
        MSRC.RV => float _v = nz(volume, 1.0) , _src := (close * _v) / (close[1] * _v[1])
    request.security(t, timeframe.period, _src, barmerge.gaps_off, barmerge.lookahead_on)


//#endregion
//#region    Import indices data:

var string[] tlist = str.split(str.replace_all(tickers, ' ', ''), ',')
int tsize = tlist.size()
// @variable Matrix to hold the indice values for the length of the window.
var matrix<float> tvalues = matrix.new<float>(window, tsize, float(na))
// @variable Temporary array to hold current indice values.
float[] lastvalues = array.new<float>(tsize, float(na))
for [_i, _t] in tlist
    lastvalues.set(_i, sec(_t))
tvalues.add_row(window, lastvalues)
if tvalues.rows() > window
    tvalues.remove_row(0)

//#endregion
//#region    Calculate the measure of the indices:

// @variable similarity measure values
matrix<float> cs = matrix.new<float>(tsize, tsize, float(na))
for _i = 0 to tsize - 1
    _ri = tvalues.col(_i)
    for _j = 0 to tsize - 1
        if _i == _j
            continue
        _rj = tvalues.col(_j)
        cs.set(_i, _j, select(mmethod, _ri, _rj))
// @variable matrice highest value.
float smax = cs.max()
// @variable matrice lowest value.
float smin = cs.min()

// @function Color the table values.
col (v) => 
    float _v = (v - smin) / (smax - smin)
    color.from_gradient(_v, 0, 1, grad1, grad2)

//#endregion
//#region
var table TB = table.new(position.bottom_right, tsize+1, tsize+1, #000000, #ffffff, 1)
for [_i, _t] in tlist
    TB.cell(0, 1+_i, _t, 0, 0, #ffffff, text.align_center, text.align_center, 14, #000000)
    TB.cell(1+_i, 0, _t, 0, 0, #ffffff, text.align_center, text.align_center, 14, #000000)
    for _j = 0 to tsize-1
        float _sv = cs.get(_i, _j)
        if _i == _j
            TB.cell(1+_i, 1+_j, str.format('{0}', _t), 0, 0, #ffffff, text.align_center, text.align_center, 14, #000000)
        else
            TB.cell(1+_i, 1+_j, str.format('{0}', str.tostring(_sv, fdigits)), 0, 0, #ffffff, text.align_center, text.align_center, 14, col(_sv))

Overview

Multi Asset Similarity Matrix collects a rolling window of returns or volume-modified returns for each ticker, then applies a selected distance or similarity function from an imported library. Results appear in a separate-pane table, with a maroon-to-blue gradient and a chosen number of digits. The window length, source method, and measure change the comparison. It does not generate trade signals.

Details

Published by

regalouisei on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Screeners & dashboards

Markets

Indices

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
Window:int10window
Source Method:enumMSRC.Rsrcmethod
Similarity Measure Method:enumM.Cosinemmethod
Asset List:textNAS100,SPX500,DJI, IBXX, N100, EU500, UKX, JP225USD, NIFTY, tickers
Gradient Colors:colorcolor.maroongrad1
grad2colorcolor.bluegrad2
Number of Digits:int5ndigits
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

948 stars

This indicator measures the chart symbol’s percentage change from the opening price at the start of each US presidential term and plots those values as histogram columns in a separate pane. Columns are offset so each administration appears separately, with a s

Indicator v6 Screeners & dashboards
Updated 10 days ago · GPL-3.0 GitHub repository of Presidents Performance

This indicator scans a pasted list of symbols for RSI directional momentum and shows matching long and short signals in a table in a separate pane. The user chooses continuous break, continuous retracement, flip break, flip retracement, divergence, or hidden d

Indicator v6 Oscillators & momentumDivergence
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Scanner

Tables-001

by ricardosantos79
261 stars

This indicator builds a TradingView table in a separate pane and fills its cells with fixed placeholder text according to whether each row and column index is even or odd. Users set the table position, the number of rows and columns, and the background, frame,

Indicator v4 Screeners & dashboards
Updated 4 years ago · None stated GitHub repository of Tables-001
257 stars

Donald SPX - Options Trading is an indicator designed to assist SPX index option traders by tracking session benchmarks and multi-timeframe moving average data. It calculates a 200-period weighted moving average (WMA) and requests multi-timeframe bar data from

Indicator v5 Moving averagesScreeners & dashboards Repaints
Updated 6 weeks ago · None stated GitHub repository of Donald SPX - Options Trading

Index Member Distribution

by TradersPost
218 stars

Calculates and plots a weighted histogram of constituent returns for major market indices (NDX, SPX, DJIA, and RUT) in a separate pane. Each histogram bin reflects the summed weights of members within that percentage return bracket. The script renders vertical

Indicator v6 Screeners & dashboards
Updated 3 months ago · None stated GitHub repository of Index Member Distribution

KamaFama

by Mastaaa1987
141 stars

KamaFama is an indicator that translates a Freqtrade trading strategy into Pine Script for visualization. It combines Kaufman Adaptive Moving Average (KAMA), MAMA/FAMA calculations derived via Hilbert Transform, Williams %R, and correlation trend filters to ev

Indicator v6 Moving averagesOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of KamaFama

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