Colorful Regression
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © faytterro

//@version=5
indicator("Colorful Regression", overlay=true, max_lines_count=500)

src=input(hlc3,title="source")
len=input.int(40,title="lenght", maxval=500)
cr(x, y) =>
    z = 0.0
    weight = 0.0
    for i = 0 to y-1
        z:=z + x[i]*((y-1)/2+1-math.abs(i-(y-1)/2))
    z/(((y+1)/2)*(y+1)/2)
cr= cr(src,2*len-1) 
width=input.int(2, title="linewidth", minval=1)
crm=ta.change(cr)
//plot(cr, color=(cr>=cr[1])? #35cf02 : #cf0202 , linewidth=width,offset=-len+1)
///////////
dx(x) =>
    x-x[1]
pm = dx(cr)
/////////////////////////
y = math.abs(pm)
n = bar_index
m = math.min(math.max(n-2*len+2,1),500)
t = ta.wma(y,m)//ta.cum(y)/n 
fd(x) =>
    100-100/(math.pow(1+2/t,x)+1)
f = fd(pm)
f:= f*2.5
plot(cr, color= color.rgb(math.min(510-2*f,255),math.min(2*f,255),0), linewidth=width,offset=-len+1, display = display.pane)
/////////////////////////
// extrapolation
diz = array.new_float(501)
var lin=array.new_line()
if barstate.islast
    for k=0 to len-1
        sum=0.0
        for i=0 to 2*len-2-k
            sum +=(len-math.abs(len-1-k-i))*src[i]/(len*len-k*(k+1)/2)
        array.set(diz,k, sum )
    for i=0 to (len-1)
        array.push(lin, line.new(na, na, na, na))
        fp= 2.5*fd(array.get(diz,i+1)-array.get(diz,i))
        line.set_color(array.get(lin,i),color.blue)//array.get(diz,i+1)>=array.get(diz,i)?  #35cf02 : #cf0202)
        line.set_xy1(array.get(lin,i), bar_index[len]+i+1, array.get(diz,i))
        line.set_xy2(array.get(lin,i),  bar_index[len]+i+2,array.get(diz,i+1))
        line.set_color(array.get(lin,i), color.rgb(math.min(510-2*fp,255),math.min(2*fp,255),0))
        line.set_width(array.get(lin,i),width)

bool buy=ta.change(ta.change(cr))>0 and ta.change(cr)<0
bool sell=ta.change(ta.change(cr))<0 and ta.change(cr)>0
//buy:= buy and buy[1]==false
for i=1 to len
    buy:= buy and buy[i]==false
    sell:= sell and sell[i]==false
alert=buy or sell
alertcondition(alert, title="Alarm", message="buy or sell signal!")
plotshape(buy, style = shape.triangleup, location = location.belowbar, color = color.rgb(0, 255, 0, 0), textcolor = color.white, size = size.tiny)
plotshape(sell, style = shape.triangledown, location = location.abovebar, color = color.rgb(255, 0, 0), textcolor = color.white, size = size.tiny)
fp= 2.5*fd(array.get(diz,1)-array.get(diz,0))
plot(ta.wma(src,len), color = color.rgb(math.min(510-2*fp,255),math.min(2*fp,255),0,100))

