mirror of
https://github.com/mihakralj/QuanTAlib.git
synced 2026-08-23 13:08:04 +00:00
pine files
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
// 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
|
||||
//@doc https://github.com/mihakralj/pinescript/blob/main/indicators/statistics/linreg.md
|
||||
//@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)
|
||||
Reference in New Issue
Block a user