PINE LIBRARY
LinearRegressionLibrary

Library "LinearRegressionLibrary" contains functions for fitting a regression line to the time series by means of different models, as well as functions for estimating the accuracy of the fit.
Linear regression algorithms:
RepeatedMedian(y, n, lastBar) applies repeated median regression (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
Output:
TheilSen(y, n, lastBar) applies the Theil-Sen estimator (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
Output:
OrdinaryLeastSquares(y, n, lastBar) applies the ordinary least squares regression (non-robust) to the input time series within the selected interval.
Parameters:
Output:
Model performance metrics:
metricRMSE(y, n, lastBar, slope, intercept) returns the Root-Mean-Square Error (RMSE) of the regression. The better the model, the lower the RMSE.
Parameters:
Output:
metricMAE(y, n, lastBar, slope, intercept) returns the Mean Absolute Error (MAE) of the regression. MAE is is similar to RMSE but is less sensitive to outliers. The better the model, the lower the MAE.
Parameters:
Output:
metricR2(y, n, lastBar, slope, intercept) returns the coefficient of determination (R squared) of the regression. The better the linear regression fits the data (compared to the sample mean), the closer the value of the R squared is to 1.
Parameters:
Output:
Usage example:
//version=5
indicator('ExampleLinReg', overlay=true)
// import the library
import tbiktag/LinearRegressionLibrary/1 as linreg
// define the studied interval: last 100 bars
int Npoints = 100
int lastBar = bar_index
int firstBar = bar_index - Npoints
// apply repeated median regression to the closing price time series within the specified interval
{square bracket}slope, intercept{square bracket} = linreg.RepeatedMedian(close, Npoints, lastBar)
// calculate the root-mean-square error of the obtained linear fit
rmse = linreg.metricRMSE(close, Npoints, lastBar, slope, intercept)
// plot the line and print the RMSE value
float y1 = intercept
float y2 = intercept + slope * (Npoints - 1)
if barstate.islast
{indent} line.new(firstBar,y1, lastBar,y2)
{indent} label.new(lastBar,y2,text='RMSE = '+str.format("{0,number,#.#}", rmse))
Linear regression algorithms:
RepeatedMedian(y, n, lastBar) applies repeated median regression (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
- y :: float series, source time series (e.g. close)
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
- mSlope :: float, slope of the regression line
- mInter :: float, intercept of the regression line
TheilSen(y, n, lastBar) applies the Theil-Sen estimator (robust linear regression algorithm) to the input time series within the selected interval.
Parameters:
- y :: float series, source time series
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
- tsSlope :: float, slope of the regression line
- tsInter :: float, intercept of the regression line
OrdinaryLeastSquares(y, n, lastBar) applies the ordinary least squares regression (non-robust) to the input time series within the selected interval.
Parameters:
- y :: float series, source time series
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
Output:
- olsSlope :: float, slope of the regression line
- olsInter :: float, intercept of the regression line
Model performance metrics:
metricRMSE(y, n, lastBar, slope, intercept) returns the Root-Mean-Square Error (RMSE) of the regression. The better the model, the lower the RMSE.
Parameters:
- y :: float series, source time series (e.g. close)
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
- slope :: float, slope of the evaluated linear regression line
- intercept :: float, intercept of the evaluated linear regression line
Output:
- rmse :: float, RMSE value
metricMAE(y, n, lastBar, slope, intercept) returns the Mean Absolute Error (MAE) of the regression. MAE is is similar to RMSE but is less sensitive to outliers. The better the model, the lower the MAE.
Parameters:
- y :: float series, source time series
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
- slope :: float, slope of the evaluated linear regression line
- intercept :: float, intercept of the evaluated linear regression line
Output:
- mae :: float, MAE value
metricR2(y, n, lastBar, slope, intercept) returns the coefficient of determination (R squared) of the regression. The better the linear regression fits the data (compared to the sample mean), the closer the value of the R squared is to 1.
Parameters:
- y :: float series, source time series
- n :: integer, the length of the selected time interval
- lastBar :: integer, index of the last bar of the selected time interval (defines the position of the interval)
- slope :: float, slope of the evaluated linear regression line
- intercept :: float, intercept of the evaluated linear regression line
Output:
- Rsq :: float, R-sqared score
Usage example:
//version=5
indicator('ExampleLinReg', overlay=true)
// import the library
import tbiktag/LinearRegressionLibrary/1 as linreg
// define the studied interval: last 100 bars
int Npoints = 100
int lastBar = bar_index
int firstBar = bar_index - Npoints
// apply repeated median regression to the closing price time series within the specified interval
{square bracket}slope, intercept{square bracket} = linreg.RepeatedMedian(close, Npoints, lastBar)
// calculate the root-mean-square error of the obtained linear fit
rmse = linreg.metricRMSE(close, Npoints, lastBar, slope, intercept)
// plot the line and print the RMSE value
float y1 = intercept
float y2 = intercept + slope * (Npoints - 1)
if barstate.islast
{indent} line.new(firstBar,y1, lastBar,y2)
{indent} label.new(lastBar,y2,text='RMSE = '+str.format("{0,number,#.#}", rmse))
Biblioteca do Pine
No verdadeiro espirito do TradingView, o autor desse código Pine o publicou como uma biblioteca de código aberto, para que outros programadores Pine da nossa comunidade possam reusa-los. Parabéns ao autor! Você pode usar essa biblioteca privadamente ou em outras publicações de código aberto, mas a reutilização desse código em publicações é regida pelas Regras da Casa.
DISCLAIMER: I am not a financial advisor, and my scripts are for educational purposes only. Any trades you make are at your own risk.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.
Biblioteca do Pine
No verdadeiro espirito do TradingView, o autor desse código Pine o publicou como uma biblioteca de código aberto, para que outros programadores Pine da nossa comunidade possam reusa-los. Parabéns ao autor! Você pode usar essa biblioteca privadamente ou em outras publicações de código aberto, mas a reutilização desse código em publicações é regida pelas Regras da Casa.
DISCLAIMER: I am not a financial advisor, and my scripts are for educational purposes only. Any trades you make are at your own risk.
Aviso legal
As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.