Skip to content

Technical indicators

Linear Regression

Where the best-fit trend line through the window says the price should be now.

For each bar, Linear Regression fits a straight line through the last periods closes by least squares and takes its value at the newest bar. It is also called the least squares moving average. Because it projects the fitted slope forward, it sits on the price when the price rises or falls by the same amount every bar, where a moving average would trail behind. It overshoots at turns.

Like a moving average: a close above it points up and below it down, and its slope is the trend’s direction and pace. Traders also draw bands a number of standard errors either side of it.

fit CLOSE = a + b × x by least squares over the window, with x = 0 for the oldest close
value = a + b × (periods − 1)

This is TA-Lib’s LINEARREG and TradingView’s ta.linreg with no offset.

Call: linearRegression(periods)

Setting Chart default
periods: Periods 14

What you get: a number.

Warm-up: with linearRegression(14), it asks for 14 bars of history and a run-up of 1, and its first value came on bar 15 of the example data.

Linear Regression drawn by its own code on example prices

The prices are made up, hourly, and the same on every page, so the chart shows how the indicator behaves, not how a market behaved.

function onIntervalClose() {
const fit = linearRegression(14);
if (fit !== null && CLOSE > fit && OPEN_POSITIONS_COUNT === 0) {
openPosition("BUY", { quantity: 10000, stopLossPips: 30 });
}
}