Files
QuanTAlib/lib/statistics/linreg/linreg.pine
T
Miha Kralj 24e86d762a Add documentation links for various volatility indicators and channels
- Updated BBWN, BBWP, CCV, CV, CVI, EWMA, GKV, HLV, HV, Jvolty, JVOLTYN, MASSI, NATR, RSV, RV, RVI, TR, UI, VOV, VR, YZV indicators with documentation links.
- Added documentation links for Aberration, Acceleration Bands, Andrews' Pitchfork, Adaptive Price Zone, ATR Bands, Bollinger Bands, Center of Gravity, Donchian Channels, Decay Min-Max Channel, Detrended Synthetic Price, EACP, EBSW, HOMOD, Jurik Volatility Bands, Keltner Channel, MA Envelope, Min-Max Channel, Price Channel, Regression Channels, Standard Deviation Channel, Stoller Average Range Channel, Super Trend Bands, Ultimate Bands, Ultimate Channel, VWAP Bands, and VWAP with Standard Deviation Bands.
2026-02-18 11:55:48 -08:00

59 lines
1.9 KiB
Plaintext

// The MIT License (MIT)
// © mihakralj
//@version=6
indicator("Linear Regression (LINREG)", "LINREG", overlay=false, precision=8)
//@function Calculates linear regression and slope over the specified period
//@param src Source series to calculate linear regression from
//@param len Lookback period for the calculation
//@returns Tuple containing [intercept, slope]
linreg(series float src, simple int len) =>
if len < 2
[na, na]
else
var float lastValid = na
var array<float> buf = array.new_float(len, 0.0)
var int count = 0
var int head = 0
float curr = src
if na(curr) and not na(lastValid)
curr := lastValid
if not na(curr)
lastValid := curr
if not na(curr)
array.set(buf, head, curr)
if count < len
count := count + 1
head := (head + 1) % len
float n = count
if n < 2
[na, na]
else
int start = count < len ? 0 : head
float sumY = 0.0, sumXY = 0.0
for i = 0 to int(n) - 1
int idx = (start + i) % len
float y_val = array.get(buf, idx)
sumY += y_val
sumXY += i * y_val
float sumX = 0.5 * (n - 1) * n
float sumX2 = (n - 1) * n * (2 * n - 1) / 6.0
float D = n * sumX2 - sumX * sumX
float s = D != 0 ? (n * sumXY - sumX * sumY) / D : na
float intercept = (sumY / n) - s * ((n - 1) / 2)
float lr = intercept + s * (n - 1)
[lr, s]
// ---------- Main loop ----------
// Inputs
i_period = input.int(14, "Period", minval=2)
i_source = input.source(close, "Source")
// Calculation: Assign tuple elements.
[lr, slope] = linreg(i_source, i_period)
// Plot
plot(lr, "LinReg", color=color.yellow, linewidth=2)
// plot(slope, "Slope", color=color.orange, linewidth=2, plot.style_histogram)