You are on page 1of 2

Pine Script - Sample Regression Indicator

Sample Regression indicator:

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

//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © x11joe
// Credit given to @midtownsk8rguy for original source code. I simply modified
to add Pearson's R

//@version=5
indicator("Linear Regression Trend Channel With Pearson's R", "LRTCWPR",
true, format.inherit)
period = input.int( 20, "Period" , minval=3)
deviations = input.float( 2.0, "Deviation(s)" , minval=0.1, step=0.1)
extendType = input.string("Right", "Extend Method" ,
options=["Right","None"])=="Right" ? extend.right : extend.none
periodMinusOne = period-1
Ex = 0.0, Ey = 0.0, Ex2 = 0.0,Ey2 =0.0, Exy = 0.0, for i=0 to periodMinusOne
closeI = nz(close[i]), Ex := Ex + i, Ey := Ey + closeI, Ex2 := Ex2 + (i * i),Ey2 :=
Ey2 + (closeI * closeI), Exy := Exy + (closeI * i)
ExT2 = math.pow(Ex,2.0) //Sum of X THEN Squared
EyT2 = math.pow(Ey,2.0) //Sym of Y THEN Squared
PearsonsR = (Exy - ((Ex*Ey)/period))/(math.sqrt(Ex2-(ExT2/
period))*math.sqrt(Ey2-(EyT2/period)))
ExEx = Ex * Ex, slope = Ex2==ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period *
Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0, for i=0 to periodMinusOne
deviation := deviation + math.pow(nz(close[i]) - (intercept - slope *
(bar_index[i])), 2.0)
deviation := deviations * math.sqrt(deviation / periodMinusOne)
startingPointY = linearRegression + slope * periodMinusOne
var label pearsonsRLabel = na
label.delete(pearsonsRLabel[1])
pearsonsRLabel := label.new(bar_index,startingPointY -
deviation*2,text=str.tostring(PearsonsR),
color=color.black,style=label.style_label_down,textcolor=color.white,size=size.
large)
var line upperChannelLine = na , var line medianChannelLine = na , var line
lowerChannelLine = na
line.delete(upperChannelLine[1]), line.delete(medianChannelLine[1]),
line.delete(lowerChannelLine[1])
upperChannelLine := line.new(bar_index - period + 1, startingPointY +
deviation, bar_index, linearRegression + deviation, xloc.bar_index, extendType,
color.new(#FF0000, 0), line.style_solid , 2)
medianChannelLine := line.new(bar_index - period + 1, startingPointY ,
bar_index, linearRegression , xloc.bar_index, extendType,
color.new(#C0C000, 0), line.style_solid , 1)
lowerChannelLine := line.new(bar_index - period + 1, startingPointY -
deviation, bar_index, linearRegression - deviation, xloc.bar_index, extendType,
color.new(#00FF00, 0), line.style_solid , 2)

You might also like