Sidechair

ta.linreg()

Browse the reference

Returns the value of the least-squares regression line fitted to the last length values of source, read offset bars back from the newest bar.

Try it in the editor

ta.linreg fits a straight line through the last length values of source by least squares and returns the line's value at the newest bar. Fitting the same window again on the next bar moves the whole line, so past values can differ from what the line showed then.

A positive offset reads the line that many bars before the newest bar instead. The first value appears on bar number length, and any na in the window makes the result na.

Syntax

Pine Script
ta.linreg(source: series int/float, length: series int, offset: simple int) -> series float

Arguments

NameTypeDefaultDescription
sourceseries int/floatrequiredThe series the straight line is fitted to over the last length bars.
lengthseries intrequiredNumber of bars in the fitted window. A whole number of 1 or more.
offsetsimple int0Bars back from the newest bar at which to read the fitted line. 0 reads the end of the line; the value is truncated to a whole number.

Returns

series float: the regression line's value at the chosen position, or na while the window is not full.

Remarks

  • The regression endpoint reacts faster than a moving average of the same length because it extrapolates the trend to the newest bar.
  • Compute the slope yourself as ta.linreg(source, length, 0) - ta.linreg(source, length, 1).

Example

Pine ScriptRegression slopeOpen in editor
//@version=6
indicator("Linreg slope")
len = input.int(30, "Length", minval = 2)
slope = ta.linreg(close, len, 0) - ta.linreg(close, len, 1)
plot(slope, "Slope", color = slope >= 0 ? color.green : color.red, style = plot.style_columns)
hline(0)

See also

Runs on Sidechair