Indicator · Pine Script v5 · On the chart

Function - Linear Regression

by ricardosantos79· code credited to RicardoSantos

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code108
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

108 lines of Pine Script v5 from beta/libs/v4_to_v5_conversions/Function - Linear Regression.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Function - Linear Regression.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=5
indicator(title='Function - Linear Regression', overlay=true)

f_array_linreg(_X, _Y) =>
//{
//| Returns a linear regression channel using (X,Y) vector points.
//| Resources:
//|     https://www.statisticshowto.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/#FindaLinear
    int _sizeY = array.size(id=_Y)
    int _sizeX = array.size(id=_X)
    float _sumX = array.sum(id=_X)
    float _sumY = array.sum(id=_Y)
    float _sumXY = 0.0
    float _sumX2 = 0.0
    float _sumY2 = 0.0
    if _sizeY == _sizeX
        for _i = 0 to _sizeY - 1 by 1
            float _Xi = nz(array.get(id=_X, index=_i))
            float _Yi = nz(array.get(id=_Y, index=_i))
            _sumXY := _sumXY + _Xi * _Yi
            _sumX2 := _sumX2 + math.pow(_Xi, 2)
            _sumY2 := _sumY2 + math.pow(_Yi, 2)
            _sumY2
    float _a = (_sumY * _sumX2 - _sumX * _sumXY) / (_sizeX * _sumX2 - math.pow(_sumX, 2))
    float _b = (_sizeX * _sumXY - _sumX * _sumY) / (_sizeX * _sumX2 - math.pow(_sumX, 2))
    float[] _predictions = array.new_float(size=0, initial_value=0.0)
    float _max_dev = 0.0
    float _min_dev = 0.0
    float _stdev = 0.0
    for _i = 0 to _sizeX - 1 by 1
        float _vector = _a + _b * array.get(id=_X, index=_i)
        array.push(id=_predictions, value=_vector)
        //
        float _Yi = array.get(id=_Y, index=_i)
        float _diff = _Yi - _vector
        if _diff > _max_dev
            _max_dev := _diff
            _max_dev
        if _diff < _min_dev
            _min_dev := _diff
            _min_dev
        _stdev := _stdev + math.abs(_diff)
        _stdev
//| Output:
//|     _predictions:   Array with adjusted _Y values.
//|     _max_dev:       Max deviation from the mean.
//|     _min_dev:       Min deviation from the mean.
//|     _stdev/_sizeX:  Average deviation from the mean.
//}
    [_predictions, _max_dev, _min_dev, _stdev / _sizeX]



int length = input(10)
var float[] prices = array.new_float(size=length, initial_value=open)
var int[] indices = array.new_int(size=length, initial_value=0)
if ta.pivothigh(2, 2)
    e = array.pop(id=prices)
    i = array.pop(id=indices)
    array.unshift(id=prices, value=high[2])
    array.unshift(id=indices, value=bar_index[2])
if ta.pivotlow(2, 2)
    e = array.pop(id=prices)
    i = array.pop(id=indices)
    array.unshift(id=prices, value=low[2])
    array.unshift(id=indices, value=bar_index[2])



[D, Dmax, Dmin, Dstdev] = f_array_linreg(indices, prices)

string _ln_extend = input.string(defval=extend.none, title='Extend lines', options=[extend.both, extend.left, extend.none, extend.right])
color _ln_mid_col = input(defval=color.blue)
color _ln_std_col = input(defval=color.aqua)
color _ln_max_col = input(defval=color.purple)
var line ln_mid = line.new(x1=bar_index, y1=open, x2=bar_index, y2=open, extend=_ln_extend, color=_ln_mid_col, style=line.style_solid, width=2)
var line ln_max = line.new(x1=bar_index, y1=open, x2=bar_index, y2=open, extend=_ln_extend, color=_ln_max_col, style=line.style_dotted, width=1)
var line ln_min = line.new(x1=bar_index, y1=open, x2=bar_index, y2=open, extend=_ln_extend, color=_ln_max_col, style=line.style_dotted, width=1)
var line ln_upper = line.new(x1=bar_index, y1=open, x2=bar_index, y2=open, extend=_ln_extend, color=_ln_std_col, style=line.style_dashed, width=1)
var line ln_lower = line.new(x1=bar_index, y1=open, x2=bar_index, y2=open, extend=_ln_extend, color=_ln_std_col, style=line.style_dashed, width=1)

int first = 0
int last = array.size(id=indices) - 1
ln_y1 = array.get(id=D, index=first)
ln_y2 = array.get(id=D, index=last)

line.set_xy1(id=ln_mid, x=array.get(id=indices, index=first), y=ln_y1)
line.set_xy2(id=ln_mid, x=array.get(id=indices, index=last), y=ln_y2)
line.set_xy1(id=ln_max, x=array.get(id=indices, index=first), y=ln_y1 + Dmax)
line.set_xy2(id=ln_max, x=array.get(id=indices, index=last), y=ln_y2 + Dmax)
line.set_xy1(id=ln_min, x=array.get(id=indices, index=first), y=ln_y1 + Dmin)
line.set_xy2(id=ln_min, x=array.get(id=indices, index=last), y=ln_y2 + Dmin)
line.set_xy1(id=ln_upper, x=array.get(id=indices, index=first), y=ln_y1 + Dstdev)
line.set_xy2(id=ln_upper, x=array.get(id=indices, index=last), y=ln_y2 + Dstdev)
line.set_xy1(id=ln_lower, x=array.get(id=indices, index=first), y=ln_y1 - Dstdev)
line.set_xy2(id=ln_lower, x=array.get(id=indices, index=last), y=ln_y2 - Dstdev)


// bool show_debug = input(false)
// var label debug = label.new(bar_index, open, '')
// if show_debug
//     label.set_xy(id=debug, x=bar_index, y=close)
//     label.set_text(id=debug, text=tostring(indices) + '\n' + tostring(D))
// else
//     label.delete(id=debug)

Overview

A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots update rolling arrays of a chosen length. Settings change that length, whether the lines extend, and the colors of the midline, deviation, and extreme lines. The script shows the channel only; it does not generate trade entries or exits.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
lengthint10length
Extend linesstringextend.none_ln_extend
_ln_mid_colcolorcolor.blue_ln_mid_col
_ln_std_colcolorcolor.aqua_ln_std_col
_ln_max_colcolorcolor.purple_ln_max_col
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

Open Source Fractal

by cantolab
183 stars

This indicator implements the Fractal Model concept to plot market structure shifts, liquidity sweeps, and Change in State of Delivery (CISD) levels. It overlays custom higher-timeframe candle previews, open prices, and time markers directly on the price chart

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · MIT GitHub repository of Open Source Fractal

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers