Library · Pine Script v5 · Library

FunctionLinearRegression

by ricardosantos79· code credited to RicardoSantos

This library exports a linreg method that fits a straight line through paired sample arrays.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code111
Settings1inputs
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 library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

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

withglobalpass.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

// @description Method for Linear Regression using array sample points.
library(title='FunctionLinearRegression', overlay=true)

// @function Performs Linear Regression over the provided sample points.
// @param sample_x float array, sample points X value.
// @param sample_y float array, sample points Y value.
// @returns tuple with:
//      _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.
export linreg (float[] sample_x, float[] sample_y) => //{
//| Returns a linear regression channel using (X,Y) vector points.
    int _sizeX = array.size(id=sample_x)
    int _sizeY = array.size(id=sample_y)
    //
    switch
        (_sizeX < 1) => runtime.error('FunctionLinearRegression -> linreg(): "sample_x" has the wrong size.')
        (_sizeX != _sizeY) => runtime.error('FunctionLinearRegression -> linreg(): "sample_x" and "sample_y" size must match.')
    //
    float _sumX = array.sum(id=sample_x)
    float _sumY = array.sum(id=sample_y)
    float _sumXY = 0.0
    float _sumX2 = 0.0
    float _sumY2 = 0.0
    //
    for _i = 0 to _sizeY - 1 by 1
        float _Xi = nz(array.get(id=sample_x, index=_i))
        float _Yi = nz(array.get(id=sample_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=sample_x, index=_i)
        array.push(id=_predictions, value=_vector)
        //
        float _Yi = array.get(id=sample_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
    //
    [_predictions, _max_dev, _min_dev, _stdev / _sizeX]
//{ usage:
//{ remarks:
//      https://www.statisticshowto.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/#FindaLinear
//}}}



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])

float[] sample_y=prices, string extend=extend.none, 
color mid_color=color.blue, string mid_style=line.style_solid, int mid_width=2,
color std_color=color.aqua, string std_style=line.style_dashed, int std_width=1,
color max_color=color.purple, string max_style=line.style_dotted, int max_width=1

[D, Dmax, Dmin, Dstdev] = linreg(indices, sample_y)
string _xloc = xloc.bar_index
var line ln_mid     = line.new(bar_index, open, bar_index, open, _xloc, extend, mid_color, mid_style, mid_width)
var line ln_max     = line.new(bar_index, open, bar_index, open, _xloc, extend, max_color, max_style, max_width)
var line ln_min     = line.new(bar_index, open, bar_index, open, _xloc, extend, max_color, max_style, max_width)
var line ln_upper   = line.new(bar_index, open, bar_index, open, _xloc, extend, std_color, std_style, std_width)
var line ln_lower   = line.new(bar_index, open, bar_index, open, _xloc, extend, std_color, std_style, std_width)

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)

Overview

FunctionLinearRegression returns fitted Y values plus the largest positive deviation, the largest negative deviation, and the average absolute deviation. Callers pass matching X and Y arrays; mismatched or empty samples raise a runtime error. A length setting sizes the stored pivot samples, and the script is marked to overlay the price chart. The included usage fragment collects recent pivot highs and lows but does not show finished drawing or exit rules.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

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
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

PositionSizing

by iamrichardD
57 stars

This Pine Script v6 library calculates trade position sizes and provides risk management functions for external scripts. It computes position sizes from account equity, percentage risk, and stop-loss distance, and offers dynamic sizing adjustments based on vol

Library v6
Updated 1 year ago · Apache-2.0 GitHub repository of PositionSizing

Chart Patterns

by deepentropy
13 stars

Chart Patterns is a Pine Script v6 library designed to scan for and render technical chart patterns directly on the price chart. It defines custom user-defined types to configure scanning parameters, such as Zigzag pivot offsets, error ratios, flat ratios, and

Library v6 Repaints
Updated 6 months ago · MIT GitHub repository of Chart Patterns

WebhookMessageLibrary

by TradersPost
6 stars

WebhookMessageLibrary is a helper library designed to construct structured JSON payload messages for automated trading integrations like TradersPost. It defines custom exported types and constants for trade actions, market sentiments, quantities, limit prices,

Library v5
Updated 1 year ago · None stated GitHub repository of WebhookMessageLibrary

Standard Lib

by vitahoang
5 stars

Standard Lib is a utility Pine Script library designed to assist developers with chart debugging and dynamic text display. It exports a print function that creates and updates a single text label on the price chart. The label automatically positions itself at

Library v5
Updated 3 years ago · None stated GitHub repository of Standard Lib

TheStratGrammar

by 345-strategies
5 stars

This library calculates TheStrat price action states, classifying candles by directional break structure, close relative to open, and rejected break conditions. It draws demo bar labels directly on the price chart using standard or glyph notation. User inputs

Library v6 Repaints
Updated 2 days ago · MPL-2.0 GitHub repository of TheStratGrammar

More libraries

Trade Your Charts With a Regulated Broker

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

Compare brokers