R2-Adaptive Regression
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © bjr117, alexgrover

//@version=5
indicator(title = "R2-Adaptive Regression", shorttitle = "R2AR", overlay = true)

//==============================================================================
// Inputs
//==============================================================================
r2ar_length = input.int(title = "R2AR Length", defval = 100, minval = 1)
r2ar_src    = input.source(title = "R2AR Source", defval = close)
//==============================================================================


//==============================================================================
// Mathematical Functions
//==============================================================================
a(x) => ta.stdev(r2ar_src, r2ar_length) * ta.correlation(r2ar_src, x, r2ar_length) / ta.stdev(x, r2ar_length)
b(x) => ta.sma(r2ar_src, r2ar_length) - a(x)*ta.sma(x, r2ar_length)
r(x) => math.pow(ta.correlation(r2ar_src, x, r2ar_length), 2)
//==============================================================================


//==============================================================================
// Calculating the R2-Adaptive Regression line
//==============================================================================
out  = float(0.0)
x2   = nz(out[1], r2ar_src)
y1   = ta.linreg(r2ar_src, r2ar_length, 0)
y2   = a(x2)*x2 + b(x2)
out := r(y1)*y1 + r(y2)*y2 + (1 - (r(y1) + r(y2)))*x2
//==============================================================================


//==============================================================================
// Plotting the R2-Adaptive Regression line
//==============================================================================
plot(out, title = "R2AR", color = color.new(#000000, 0))
//==============================================================================