Skip to content

Correlation matrix ​

How do you see which coins move together, pair by pair, as it was on each date? Inside request.pairs, left and right are the two coins' own closes, so a pair can correlate their returns rather than look at their ratio.

ameno
indicator("Correlation matrix")
array<string> m = request.universe(15, exclude_tags = "stablecoin")
int len = input.int(90, "Window, days", minval = 10)

// left and right: the row coin's and the column coin's own closes
matrix<float> rho = request.pairs(m, ta.correlation(
  ta.change(math.log(left)), ta.change(math.log(right)), len))
report.matrix("correlation " + str.tostring(len), m, rho)
// How crowded each coin is: its correlations summed
report.column("summed correlation", m, cs.row_sum(rho))
plot(array.size(m), "Members")

Run it from the Screener: choose it in the script picker, press Run, and open the Matrix section. request.pairs and report.* are AmenoScript additions, so the script is AmenoScript and runs leak-safe. Stablecoins are left out because their returns are close to zero every day, so their correlations would say nothing.

How it works ​

  • ta.change(math.log(left)) is the row coin's daily log return, and the same with right for the column coin.
  • ta.correlation(a, b, len) is their correlation over the last 90 days of the pair.
  • Every pair keeps its own window. With warm at its default, true, a pair starts at the two coins' first shared price, so a coin that just joined the list arrives with its past. ta.correlation reads na until the pair has 90 returns.
  • The report's name carries the window, so runs with two windows don't overwrite each other.

Traps ​

  • A pair steps on days either coin printed. A coin with no print that day holds its last close, so its return that day is 0. That pulls a thinly traded coin's correlations toward 0.
  • Correlation is not a trade. It says two coins moved together over the window, not that they will.

See also ​

AmenoScript is compatible with Pine Script v6. Pine Script is a trademark of TradingView, Inc., which has no part in AmenoScript.