Appearance
Linear Regression Channel
Regression line through the last N bars with deviation bands.
Kind indicator · Drawn on the price pane
Try it
On the chart, press / and choose Linear Regression Channel under Support & resistance. To change it, copy the source below into the AlphaScript editor.
Inputs
| Input | Type | Default |
|---|---|---|
| Length | int | 100 |
| Deviation | float | 2 |
| Extend right | bool | true |
| Source | source | "close" |
| Base color | color | "#F23645" |
| Channel color | color | "#2962FF" |
Source
From packages/alphascript/indicators/linregchannel.as.js.
js
indicator({ name: "Linear Regression Channel", shortTitle: "LinReg", overlay: true });
const length = input.int("Length", 100, { min: 2, max: 2000 });
const devs = input.float("Deviation", 2, { min: 0, step: 0.1 });
const extend = input.bool("Extend right", true);
const src = input.source("Source", "close");
const midColor = input.color("Base color", "#F23645", { group: "Style" }), bandColor = input.color("Channel color", "#2962FF", { group: "Style" });
let mid = 0, up = 0, dn = 0;
event.onCandle(() => {
if (src.length < length) return;
let sx = 0, sy = 0, sxx = 0, sxy = 0;
for (let k = 0; k < length; k++) { const x = length - 1 - k, y = src.at(k); sx += x; sy += y; sxx += x * x; sxy += x * y; }
const slope = (length * sxy - sx * sy) / (length * sxx - sx * sx), icpt = (sy - slope * sx) / length;
let ss = 0;
for (let k = 0; k < length; k++) { const r = src.at(k) - (icpt + slope * (length - 1 - k)); ss += r * r; }
const dev = devs * math.sqrt(ss / length), x1 = candle.time.at(length - 1), x2 = candle.time.value, y1 = icpt, y2 = icpt + slope * (length - 1);
const ext = extend ? "right" : "none";
if (!mid) {
mid = draw.line({ x1, y1, x2, y2, color: midColor, width: 1, style: "dashed", extend: ext });
up = draw.line({ x1, y1: y1 + dev, x2, y2: y2 + dev, color: bandColor, width: 1, extend: ext });
dn = draw.line({ x1, y1: y1 - dev, x2, y2: y2 - dev, color: bandColor, width: 1, extend: ext });
} else {
draw.set(mid, { x1, y1, x2, y2 });
draw.set(up, { x1, y1: y1 + dev, x2, y2: y2 + dev });
draw.set(dn, { x1, y1: y1 - dev, x2, y2: y2 - dev });
}
});