Autocorrelation State Stability [AlgoAlpha]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlgoAlpha X © Sushiboi77

//@version=5
indicator("⩰ Autocorrelation State Stability [AlgoAlpha]")
len = input.int(14, "correlation Period")
plotcol = input.color(#000000, "Color") //#00ffbb
r = close

corr1 = ta.correlation(r, r[1], len)
corr2 = ta.correlation(r, r[2], len)
corr3 = ta.correlation(r, r[3], len)
corr4 = ta.correlation(r, r[4], len)
corr5 = ta.correlation(r, r[5], len)
corr6 = ta.correlation(r, r[6], len)
corr7 = ta.correlation(r, r[7], len)
corr8 = ta.correlation(r, r[8], len)
corr9 = ta.correlation(r, r[9], len)
corr10 = ta.correlation(r, r[10], len)

dist1 = 1 - corr1
dist2 = 1 - corr2
dist3 = 1 - corr3
dist4 = 1 - corr4
dist5 = 1 - corr5
dist6 = 1 - corr6
dist7 = 1 - corr7
dist8 = 1 - corr8
dist9 = 1 - corr9
dist10 = 1 - corr10


var dist = array.new_float(size = 10)

array.insert(dist, 0, dist1)
array.insert(dist, 0, dist2)
array.insert(dist, 0, dist3)
array.insert(dist, 0, dist4)
array.insert(dist, 0, dist5)
array.insert(dist, 0, dist6)
array.insert(dist, 0, dist7)
array.insert(dist, 0, dist8)
array.insert(dist, 0, dist9)
array.insert(dist, 0, dist10)

// Compute the standard deviation of distances over length
stdDist = array.stdev(dist)

for i = 1 to 10
    array.remove(dist, 10)


plot(1, color = color.gray)
plot(0, color = color.gray)
plot(-1, color = color.gray)

plot(corr1, color = color.new(plotcol, 0))
plot(corr2, color = color.new(plotcol, 10))
plot(corr3, color = color.new(plotcol, 20))
plot(corr4, color = color.new(plotcol, 30))
plot(corr5, color = color.new(plotcol, 40))
plot(corr6, color = color.new(plotcol, 50))
plot(corr7, color = color.new(plotcol, 60))
plot(corr8, color = color.new(plotcol, 70))
plot(corr9, color = color.new(plotcol, 80))
plot(corr10, color = color.new(plotcol, 90))
bg = color.from_gradient(-stdDist, -1, 0, color.new(color.yellow, 50), color.new(color.red, 50))
bgcolor(bg)