R Squared - Momentum
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Crak_Trading

//@version=5
indicator("R Squared - Momentum")

len = input.int(21, title = "Length")
src = input(hlc3, title = "Source")



f_rsq(_src, _period) =>
    x = _period
    y = _src
    avg = 0.0

    
    for i = 0 to x
        avg := avg + y[i] / x
    avg

    diff = y - avg
    diffsqr = math.pow(diff, 2)
    diffsum = math.sum(diffsqr, x)
    linereg = ta.linreg(y, x, 0)
    est = linereg - avg
    estsqr = math.pow(est, 2)
    estsum = math.sum(estsqr, x)
    r2 = 1 - diffsum / estsum

r2line = f_rsq(src, len)
sm = ta.sma(r2line, 5)


up = r2line > r2line[1] ? color.green : color.red


plot(r2line, color = up, style = plot.style_line)
plot(sm, color = color.gray, style=plot.style_line)







