本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AlgoAlpha
//@version=6
indicator("Regression Trend Reversal Signals & Forecasts [AlgoAlpha]", "AlgoAlpha - Regression Trend Reversal", overlay = true, behind_chart = false, max_labels_count = 500, max_lines_count = 100)
// inputs
gMain = "Method & Window"
gSmth = "Smoothing (LOESS / Nadaraya-Watson)"
gPoly = "Polynomial"
gKlm = "Kalman Filter"
src = input.source(close, "Source", group = gMain, tooltip = "The price the line is fitted to. 'close' is normal; try hl2 or ohlc4 for a slightly smoother starting point.")
methodSel = input.string("Linear", "Method", group = gMain, options = ["Linear", "Theil-Sen", "Local Linear (LOESS)", "Kalman", "Polynomial", "Nadaraya-Watson"], tooltip = "Which engine draws the line. Linear / Theil-Sen = straight trend (Theil-Sen shrugs off spikes). LOESS / Nadaraya-Watson = smooth curve that hugs price. Kalman = adaptive real-time line. Polynomial = curved trend.")
length = input.int(50, "Window Length", minval = 3, group = gMain, active = methodSel != "Kalman", tooltip = "How many bars the line looks back over. Higher = smoother and slower to turn; lower = tighter to price and more reactive. Kalman is recursive and ignores this.")
smoothness = input.float(30.0, "Smoothness", minval = 1.0, maxval = 100.0, step = 1.0, group = gSmth, active = methodSel == "Local Linear (LOESS)" or methodSel == "Nadaraya-Watson", tooltip = "Width of the averaging window around the current bar. Higher = smoother, rounder line that ignores small wiggles; lower = line follows price more closely and reacts faster.")
degree = input.int(2, "Degree", minval = 1, maxval = 3, group = gPoly, active = methodSel == "Polynomial", tooltip = "Curve complexity. 1 = straight line, 2 = one bend (U / ∩ shape), 3 = S-curve. Higher captures more shape but can swing wildly at the right-hand edge.")
kProcess = input.float(0.01, "Process Noise", minval = 0.0, step = 0.001, group = gKlm, active = methodSel == "Kalman", tooltip = "How freely the line may change direction. Higher = snappier, follows price faster; lower = smoother with more lag.")
kMeasure = input.float(1.0, "Measurement Noise", minval = 0.0001, step = 0.1, group = gKlm, active = methodSel == "Kalman", tooltip = "How much each new price is distrusted. Higher = ignores noise, very smooth; lower = reacts to almost every move.")
gFc = "Forecast"
showFc = input.bool(true, "Show Forecast", group = gFc, tooltip = "Extend the selected regression into the future using its current direction (slope).")
forecastBars = input.int(40, "Forecast Bars", minval = 1, maxval = 500, group = gFc, active = showFc, tooltip = "How many bars to project forward. Longer = further but less reliable.")
fcStyleSel = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], group = gFc, active = showFc, tooltip = "Line style of the forecast projection (the line and its bands).")
fcWidth = input.int(2, "Width", minval = 1, group = gFc, active = showFc, tooltip = "Thickness of the forecast projection line.")
showFcLbl = input.bool(true, "Label projected value", group = gFc, active = showFc, tooltip = "Print the projected price in a label at the end of the forecast line.")
group_appearance = "Appearance"
showReg = input.bool(true, "Show Regression Line", group = group_appearance, tooltip = "Show or hide the main regression line.")
showBands = input.bool(true, "Show Bands", group = group_appearance, tooltip = "Channel built from how far price strays from the regression line. Width = standard deviation of (price − regression), so it adapts to whichever method is selected: a tight-tracking fit gives narrow bands, a smooth/laggy fit gives wide ones.")
green = input.color(#00ffbb, "Bullish Colour", group = group_appearance, tooltip = "Color used when the regression is rising — the line, its forward projection, and the band fill.")
red = input.color(#ff1100, "Bearish Colour", group = group_appearance, tooltip = "Color used when the regression is falling — the line, its forward projection, and the band fill.")
// regression methods
f_linreg(s, len) =>
sumX = 0.0
sumY = 0.0
sumXY = 0.0
sumX2 = 0.0
for i = 0 to len - 1
x = len - 1 - i
y = s[i]
sumX += x
sumY += y
sumXY += x * y
sumX2 += x * x
denom = len * sumX2 - sumX * sumX
slope = denom != 0.0 ? (len * sumXY - sumX * sumY) / denom : 0.0
intercept = (sumY - slope * sumX) / len
[slope * (len - 1) + intercept, slope]
f_theilsen(s, len) =>
slopes = array.new_float()
for i = 0 to len - 2
for j = i + 1 to len - 1
dx = j - i
dy = s[i] - s[j]
if dx != 0
array.push(slopes, dy / dx)
slope = array.size(slopes) > 0 ? array.median(slopes) : 0.0
inter = array.new_float()
for i = 0 to len - 1
x = len - 1 - i
array.push(inter, s[i] - slope * x)
intercept = array.median(inter)
[slope * (len - 1) + intercept, slope]
f_locallinear(s, len, bw) =>
Sw = 0.0
Swx = 0.0
Swy = 0.0
Swxx = 0.0
Swxy = 0.0
for i = 0 to len - 1
x = len - 1 - i
y = s[i]
w = math.exp(-0.5 * (i / bw) * (i / bw))
Sw += w
Swx += w * x
Swy += w * y
Swxx += w * x * x
Swxy += w * x * y
denom = Sw * Swxx - Swx * Swx
slope = denom != 0.0 ? (Sw * Swxy - Swx * Swy) / denom : 0.0
intercept = (Swy - slope * Swx) / Sw
[slope * (len - 1) + intercept, slope]
f_kalman(s, q, r) =>
var float l = na
var float b = 0.0
var float P00 = 1.0
var float P01 = 0.0
var float P11 = 1.0
if na(l)
l := s
else
lPred = l + b
bPred = b
p00 = P00 + 2.0 * P01 + P11 + q
p01 = P01 + P11
p11 = P11 + q
yk = s - lPred
S = p00 + r
K0 = p00 / S
K1 = p01 / S
l := lPred + K0 * yk
b := bPred + K1 * yk
P00 := (1.0 - K0) * p00
P01 := (1.0 - K0) * p01
P11 := p11 - K1 * p01
[l, b]
f_poly(s, len, deg) =>
float reg = na
float slp = na
if len > deg
A = matrix.new<float>(deg + 1, deg + 1, 0.0)
Bv = matrix.new<float>(deg + 1, 1, 0.0)
for i = 0 to len - 1
t = (2.0 * (len - 1 - i)) / (len - 1) - 1.0
y = s[i]
for rr = 0 to deg
for cc = 0 to deg
e = rr + cc
p = e == 0 ? 1.0 : math.pow(t, e)
matrix.set(A, rr, cc, matrix.get(A, rr, cc) + p)
pr = rr == 0 ? 1.0 : math.pow(t, rr)
matrix.set(Bv, rr, 0, matrix.get(Bv, rr, 0) + pr * y)
Ainv = matrix.inv(A)
coeffs = matrix.mult(Ainv, Bv)
v = 0.0
dv = 0.0
for rr = 0 to deg
c = matrix.get(coeffs, rr, 0)
v += c
dv += rr * c
reg := v
slp := dv * 2.0 / (len - 1)
[reg, slp]
f_nadaraya(s, len, bw) =>
num = 0.0
den = 0.0
for i = 0 to len - 1
w = math.exp(-0.5 * (i / bw) * (i / bw))
num += w * s[i]
den += w
[den != 0.0 ? num / den : s, 0.0]
// dispatch
sm = smoothness / 100.0
bw = math.max(0.5, sm * length)
[reg, slp] = switch methodSel
"Linear" => f_linreg(src, length)
"Theil-Sen" => f_theilsen(src, length)
"Local Linear (LOESS)" => f_locallinear(src, length, bw)
"Kalman" => f_kalman(src, kProcess, kMeasure)
"Polynomial" => f_poly(src, length, degree)
"Nadaraya-Watson" => f_nadaraya(src, length, bw)
=> [float(na), float(na)]
// plots
bandLen = 50
bandMult = 2.0
dirCol = reg > reg[3] ? green : red
bandDev = ta.stdev(src - reg, bandLen)
upper = ta.wma(reg + bandMult * bandDev,7)
lower = ta.wma(reg - bandMult * bandDev,7)
upperMid = reg + 0.5 * bandMult * bandDev
lowerMid = reg - 0.5 * bandMult * bandDev
m = plot(showReg ? reg : na, "Regression", dirCol, 3)
u = plot(showBands ? upper : na, "Upper Band", color.new(red, 40))
um = plot(showBands ? upperMid : na, "Upper Mid", color.new(red, 60), display = display.none)
lm = plot(showBands ? lowerMid : na, "Lower Mid", color.new(green, 60), display = display.none)
l = plot(showBands ? lower : na, "Lower Band", color.new(green, 40))
fill(um, u, upper, upperMid, color.new(red, 70), color.new(red, 90))
fill(um, m, upperMid, reg, color.new(red, 90), color.new(red, 100))
fill(lm, l, lowerMid, lower, color.new(green, 90), color.new(green, 70))
fill(lm, m, reg, lowerMid, color.new(green, 100), color.new(green, 90))
candleBase = close >= reg ? color.from_gradient(close, reg, upper, chart.fg_color, green) : color.from_gradient(close, lower, reg, red, chart.fg_color)
candleCol = color.new(candleBase, color.t(candleBase) + (close < open ? 20 : 0))
plotcandle(open, high, low, close, "Candles", candleCol, wickcolor = candleCol, bordercolor = candleCol)
topSig = close > upper and close < open and close[1] > open[1] and close[1] > upper[1]
botSig = close < lower and close > open and close[1] < open[1] and close[1] < lower[1]
plotchar(topSig, "Bearish Reversal", "◆", location.abovebar, red, size = size.tiny)
plotchar(botSig, "Bullish Reversal", "◆", location.belowbar, green, size = size.tiny)
regUp = reg > reg[3]
flipUp = regUp and not regUp[1]
flipDn = not regUp and regUp[1]
plotshape(flipUp ? lower : na, "Bullish Signal", shape.labelup, location.absolute, green, size = size.small, text = "▲", textcolor = chart.fg_color)
plotshape(flipDn ? upper : na, "Bearish Signal", shape.labeldown, location.absolute, red, size = size.small, text = "▼", textcolor = chart.fg_color)
// forecast
fcStyle = fcStyleSel == "Solid" ? line.style_solid : fcStyleSel == "Dashed" ? line.style_dashed : line.style_dotted
fcDir = slp >= 0 ? green : red
var line fcLine = na
var line fcU = na
var line fcL = na
var linefill fcFU = na
var linefill fcFL = na
var label fcLbl = na
if barstate.islast
line.delete(fcLine)
line.delete(fcU)
line.delete(fcL)
label.delete(fcLbl)
if showFc and not na(reg) and not na(slp)
x2 = bar_index + forecastBars
yEnd = reg + slp * forecastBars
fcLine := line.new(bar_index, reg, x2, yEnd, color = fcDir, width = fcWidth, style = fcStyle)
if showBands and not na(bandDev)
dev = bandMult * bandDev
fcU := line.new(bar_index, upper, x2, yEnd + dev, color = color.new(red, 40), style = fcStyle)
fcL := line.new(bar_index, lower, x2, yEnd - dev, color = color.new(green, 40), style = fcStyle)
fcFU := linefill.new(fcU, fcLine, color.new(red, 90))
fcFL := linefill.new(fcLine, fcL, color.new(green, 90))
if showFcLbl
fcLbl := label.new(x2, yEnd, str.tostring(yEnd, format.mintick),
style = label.style_label_left, color = color.new(fcDir, 80),
textcolor = chart.fg_color, size = size.small)
// alerts
alertcondition(flipUp, "Regression Turned Up")
alertcondition(flipDn, "Regression Turned Down")
alertcondition(botSig, "Bullish Reversal")
alertcondition(topSig, "Bearish Reversal")