Kendall Rank Correlation NET on SMA [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Kendall Rank Correlation NET on SMA [Loxx]",
     shorttitle="KRCNETSMA [Loxx]", 
     overlay=true, 
     max_bars_back = 3000)

greencolor = #2DD204
redcolor = #D2042D 

src  = input.source(close, "Source", group = "Basic Settings")
smaper = input.int(14, "SMA Period", group = "Basic Settings")
netper = input.int(5, "NET Period", group = "Basic Settings", minval = 1)
colorbars = input.bool(false, "Color bars?", group = "UI Options")

smaperout = math.max(smaper, 1)
netperout = math.max(netper, 2)
netd = 0.5 * netperout * (netperout - 1)

val = ta.sma(src, smaper)

netNum = 0.
for k = 0 to netperout - 1
    for j = 0 to k 
        diff = math.sign(nz(val[k]) - nz(val[j]))
        netNum -= (diff > 0) ? 1 : (diff < 0) ? -1 : 0
        
net = netNum / netd

valc = 0.
valc := (net > 0) ? 0 : (net < 0) ? 1 : nz(valc[1])
colorout = valc == 1 ? redcolor : valc == 0 ? greencolor : color.gray

plot(val, color = colorout, linewidth = 3)

barcolor(colorbars ? colorout : na)