Log Regression Channel v2

blastoplast · study · 319 行 · 点赞 38 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("Log Regression Channel v2", shorttitle = "LogReg v2", overlay = true, max_lines_count = 500, max_labels_count = 10)
 
// Adapted from "Log-Regression Channels RV" by manuschm1988.
// Original publication: https://www.tradingview.com/script/AWBVmz7a/
// This adaptation adds calendar-time models, optional power-law regression,
// as-known-then history, anchor sensitivity and prior-fit forecast diagnostics.
// Regression bands describe dispersion,
// not fair value, reversal odds, or calibrated prediction intervals.
// Suggested BTC setup: standard 1W candles, 2015 start, Latest available end.
// Latest-fit view redraws history. As-known-then view uses each bar's own fit;
// confirmed readings do not incorporate later bars with unchanged settings/data.
// The current unfinished bar is excluded from fitting by default, but its live
// selected-source value is still evaluated against the last confirmed fit.
// Dates select bars by OPEN time, as in v1. A selected weekly/monthly bar may
// close after the end date. For a strict cutoff, choose a bar that closes by it.
// Power law: ln(price) = a + b*ln(days since origin). Exponential: ln(price)
// = a + b*elapsed years. Real elapsed time handles missing bars consistently.
// Walk-forward RMSE uses confirmed, strictly prior-fit forecasts after the
// minimum sample. Inside the fitting range it is one bar ahead; after a fixed
// end it evaluates the frozen model at increasing horizons. It is not a
// trading backtest, and a smaller value does not guarantee future performance.
 
string gCalc = "1. Calculation"
string sourceMode = input.string("Close", "Price source", options = ["Close", "HLC3", "OHLC4"], group = gCalc)
string model = input.string("Exponential", "Model", options = ["Exponential", "Power law"], group = gCalc, tooltip = "Exponential assumes constant percentage growth. Power law allows growth to decelerate when its fitted exponent is positive. Neither is automatically superior.")
int startTime = input.time(timestamp("01 Jan 2015 00:00 +0000"), "Regression start", group = gCalc)
string endMode = input.string("Latest available", "Regression end mode", options = ["Latest available", "Fixed date"], group = gCalc)
int endTime = input.time(timestamp("31 Dec 2025 00:00 +0000"), "Fixed end date", group = gCalc)
bool includeLive = input.bool(false, "Include unfinished bar in fit", group = gCalc, tooltip = "Off: fit only confirmed bars; the live label still evaluates the current price source. On: the fit and live label can both change during the open bar.")
int minimumBars = input.int(52, "Minimum sample bars", minval = 10, maxval = 1000, group = gCalc)
int originTime = input.time(timestamp("03 Jan 2009 00:00 +0000"), "Power-law origin", group = gCalc, tooltip = "BTC genesis is the default. The origin must precede the selected sample; change it for other assets. Results depend on this choice.")
 
string gView = "2. Display"
string viewMode = input.string("Latest fit (redraws history)", "Channel view", options = ["Latest fit (redraws history)", "As known then (confirmed bars)"], group = gView)
bool showTrend = input.bool(true, "Show trend", group = gView)
bool show1 = input.bool(true, "Show +/-1 sigma", group = gView)
bool show2 = input.bool(true, "Show +/-2 sigma", group = gView)
bool show3 = input.bool(true, "Show +/-3 sigma", group = gView)
bool showLabel = input.bool(true, "Show current deviation", group = gView)
bool showTable = input.bool(false, "Show diagnostics", group = gView)
bool showComparisons = input.bool(true, "Compare 2015 / 2017 / 2021 starts", group = gView, tooltip = "Fixed sensitivity checks, using the selected model, source and end settings. They do not automatically choose or optimize a start date. Actual first observations are shown.")
int projectionBars = input.int(100, "Projection beyond current bar", minval = 0, maxval = 500, group = gView, tooltip = "Latest-fit view only. Uses nominal chart-bar duration in calendar time; future exchange sessions and month boundaries are approximate.")
int segments = input.int(60, "Curve segments", minval = 10, maxval = 60, group = gView)
 
string gStyle = "3. Style"
color trendColor = input.color(color.rgb(173, 157, 255), "Trend accent", group = gStyle)
color upperColor = input.color(color.rgb(248, 120, 145), "Above-trend bands", group = gStyle)
color lowerColor = input.color(color.rgb(47, 205, 181), "Below-trend bands", group = gStyle)
bool showShading = input.bool(true, "Shade channel zones", group = gStyle)
int shadeTransparency = input.int(90, "Zone transparency", minval = 70, maxval = 100, group = gStyle, tooltip = "Higher values are more subtle. Colors indicate position relative to the fitted trend, not buy/sell signals.")
int trendWidth = input.int(3, "Trend width", minval = 1, maxval = 5, group = gStyle)
int bandWidth = input.int(1, "Band width", minval = 1, maxval = 5, group = gStyle)
 
float dayMs = 86400000.0
float yearMs = 365.25 * dayMs
float src = sourceMode == "HLC3" ? hlc3 : sourceMode == "OHLC4" ? ohlc4 : close
bool power = model == "Power law"
bool fixedEnd = endMode == "Fixed date"
bool historyView = viewMode == "As known then (confirmed bars)"
bool sourceOK = not na(src) and src > 0.0
bool endOK = not fixedEnd or time <= endTime
bool commitOK = barstate.isconfirmed or includeLive
float xExp = (time - startTime) / yearMs
float ageDays = (time - originTime) / dayMs
float xPower = ageDays > 0.0 ? math.log(ageDays) : na
float x = power ? xPower : xExp
float logSource = sourceOK ? math.log(src) : na
 
// Centered online moments avoid cancellation in large raw sums. Ordinary var
// fields roll back on realtime ticks; do not change them to varip.
type Fit
    int n = 0
    float mx = 0.0
    float my = 0.0
    float xx = 0.0
    float xy = 0.0
    float yy = 0.0
    int firstTime = na
    int lastTime = na
 
method add(Fit f, float xv, float yv, int tv) =>
    f.n += 1
    float dx = xv - f.mx
    float dy = yv - f.my
    f.mx += dx / f.n
    f.my += dy / f.n
    f.xx += dx * (xv - f.mx)
    f.xy += dx * (yv - f.my)
    f.yy += dy * (yv - f.my)
    if na(f.firstTime)
        f.firstTime := tv
    f.lastTime := tv
 
method ready(Fit f) =>
    f.n >= minimumBars and f.xx > 0.0
 
method slope(Fit f) =>
    f.ready() ? f.xy / f.xx : na
 
method sigma(Fit f) =>
    float rss = f.ready() ? math.max(f.yy - f.xy * f.xy / f.xx, 0.0) : na
    float cleanedRSS = not na(rss) and rss <= math.max(f.yy, 1.0) * 1e-12 ? 0.0 : rss
    f.ready() ? math.sqrt(cleanedRSS / (f.n - 2)) : na
 
method predict(Fit f, float xv) =>
    f.ready() and not na(xv) ? f.my + f.slope() * (xv - f.mx) : na
 
method zscore(Fit f, float xv, float yv) =>
    float s = f.sigma()
    not na(yv) and not na(s) and s > 1e-10 ? (yv - f.predict(xv)) / s : na
 
f_exp(float value) =>
    not na(value) and value > -700.0 and value < 700.0 ? math.exp(value) : na
 
f_x(int tv) =>
    float days = (tv - originTime) / dayMs
    power ? (days > 0.0 ? math.log(days) : na) : (tv - startTime) / yearMs
 
f_date(int tv) =>
    na(tv) ? "n/a" : str.format_time(tv, "yyyy-MM-dd", "UTC")
 
f_num(float v, string fmt) =>
    na(v) ? "n/a" : str.tostring(v, fmt)
 
f_z(float v) =>
    na(v) ? "n/a" : (v > 0.0 ? "+" : "") + str.tostring(v, "#.00") + "σ"
 
var Fit exponentialFit = Fit.new()
var Fit powerFit = Fit.new()
var Fit compare2015 = Fit.new()
var Fit compare2017 = Fit.new()
var Fit compare2021 = Fit.new()
Fit mainFit = power ? powerFit : exponentialFit
 
// Evaluate before adding the current observation: strictly out of sample.
float priorExpLog = exponentialFit.predict(xExp)
float priorPowerLog = powerFit.predict(xPower)
float priorLog = power ? priorPowerLog : priorExpLog
float priorZ = mainFit.zscore(x, logSource)
var float expSquaredErrors = 0.0
var float powerSquaredErrors = 0.0
var int forecastCount = 0
bool sharedForecast = barstate.isconfirmed and sourceOK and not na(priorExpLog) and not na(priorPowerLog)
if sharedForecast
    expSquaredErrors += math.pow(logSource - priorExpLog, 2)
    powerSquaredErrors += math.pow(logSource - priorPowerLog, 2)
    forecastCount += 1
 
bool inMainRange = time >= startTime and endOK
if inMainRange and sourceOK and commitOK
    exponentialFit.add(xExp, logSource, time)
    if not na(xPower)
        powerFit.add(xPower, logSource, time)
 
if sourceOK and commitOK and endOK and not na(x)
    if time >= timestamp("01 Jan 2015 00:00 +0000")
        compare2015.add(x, logSource, time)
    if time >= timestamp("01 Jan 2017 00:00 +0000")
        compare2017.add(x, logSource, time)
    if time >= timestamp("01 Jan 2021 00:00 +0000")
        compare2021.add(x, logSource, time)
 
float fittedLog = mainFit.predict(x)
float sigma = mainFit.sigma()
float currentZ = mainFit.zscore(x, logSource)
float currentTrend = f_exp(fittedLog)
bool fitOK = mainFit.ready() and not na(currentTrend)
float rSquared = mainFit.ready() and mainFit.yy > 0.0 ? math.min(1.0, math.max(0.0, mainFit.xy * mainFit.xy / (mainFit.xx * mainFit.yy))) : na
float growthLog = power ? (ageDays > 0.0 ? mainFit.slope() * math.log((ageDays + 365.25) / ageDays) : na) : mainFit.slope()
float growth = f_exp(growthLog) - 1.0
 
// Shared palette for both channel views. Outer zones carry more color while
// the central zone stays quiet so candles remain readable.
f_bandColor(int band) =>
    band == 0 ? trendColor : color.new(band > 0 ? upperColor : lowerColor, math.abs(band) == 1 ? 38 : math.abs(band) == 2 ? 12 : 0)
 
f_zoneColor(int zone) =>
    bool central = zone == 2 or zone == 3
    bool extreme = zone == 0 or zone == 5
    int transparency = shadeTransparency == 100 ? 100 : math.min(100, math.max(0, shadeTransparency + (central ? 6 : extreme ? -4 : 0)))
    color.new(central ? trendColor : zone < 3 ? lowerColor : upperColor, transparency)
 
// Series store the fit available on each confirmed bar, rather than applying
// today's coefficients retroactively. Changing inputs/data recalculates them.
float historicalLog = barstate.isconfirmed ? fittedLog : na
float historicalSigma = barstate.isconfirmed ? sigma : na
historyTrend = plot(historyView and showTrend ? f_exp(historicalLog) : na, "As-known trend", color = trendColor, linewidth = trendWidth, style = plot.style_linebr)
historyPlus1 = plot(historyView and show1 ? f_exp(historicalLog + historicalSigma) : na, "As-known +1 sigma", color = f_bandColor(1), linewidth = bandWidth, style = plot.style_linebr)
historyMinus1 = plot(historyView and show1 ? f_exp(historicalLog - historicalSigma) : na, "As-known -1 sigma", color = f_bandColor(-1), linewidth = bandWidth, style = plot.style_linebr)
historyPlus2 = plot(historyView and show2 ? f_exp(historicalLog + 2 * historicalSigma) : na, "As-known +2 sigma", color = f_bandColor(2), linewidth = bandWidth, style = plot.style_linebr)
historyMinus2 = plot(historyView and show2 ? f_exp(historicalLog - 2 * historicalSigma) : na, "As-known -2 sigma", color = f_bandColor(-2), linewidth = bandWidth, style = plot.style_linebr)
historyPlus3 = plot(historyView and show3 ? f_exp(historicalLog + 3 * historicalSigma) : na, "As-known +3 sigma", color = f_bandColor(3), linewidth = bandWidth, style = plot.style_linebr)
historyMinus3 = plot(historyView and show3 ? f_exp(historicalLog - 3 * historicalSigma) : na, "As-known -3 sigma", color = f_bandColor(-3), linewidth = bandWidth, style = plot.style_linebr)
 
// fillgaps=false keeps missing and unfinished observations unpainted.
fill(historyMinus3, historyMinus2, color = showShading ? f_zoneColor(0) : na, title = "Historical zone 1", fillgaps = false)
fill(historyMinus2, historyMinus1, color = showShading ? f_zoneColor(1) : na, title = "Historical zone 2", fillgaps = false)
fill(historyMinus1, historyTrend, color = showShading ? f_zoneColor(2) : na, title = "Historical zone 3", fillgaps = false)
fill(historyTrend, historyPlus1, color = showShading ? f_zoneColor(3) : na, title = "Historical zone 4", fillgaps = false)
fill(historyPlus1, historyPlus2, color = showShading ? f_zoneColor(4) : na, title = "Historical zone 5", fillgaps = false)
fill(historyPlus2, historyPlus3, color = showShading ? f_zoneColor(5) : na, title = "Historical zone 6", fillgaps = false)
 
// Numeric outputs are exportable without distorting the overlay price scale.
plot(currentZ, "Current source deviation sigma (live)", display = display.data_window)
plot(barstate.isconfirmed ? currentZ : na, "Confirmed as-known deviation sigma", display = display.data_window)
plot(barstate.isconfirmed ? priorZ : na, "Confirmed prior-fit deviation sigma (out of sample)", display = display.data_window)
plot(barstate.isconfirmed ? f_exp(priorLog) : na, "Confirmed prior-fit forecast", display = display.data_window)
plot(barstate.isconfirmed ? f_exp(fittedLog) : na, "Confirmed as-known fitted trend", display = display.data_window)
plot(barstate.isconfirmed ? sigma : na, "Confirmed residual sigma (log units)", display = display.data_window)
 
// Calendar-time coordinates remove bar-index drawing limits. Reuse the same
// bounded pool (7 * at most 60 = 420 lines) instead of allocating every tick.
var array<line> channelLines = array.new_line(420, na)
float nominalBarMs = timeframe.in_seconds() * 1000.0
int barMs = int(math.max(nz(nominalBarMs, dayMs), 1.0))
int projectionEnd = time + projectionBars * barMs
if barstate.islast
    for slot = 0 to 419
        int band = int(math.floor(slot / segments)) - 3
        int segment = slot % segments
        bool activeSlot = slot < 7 * segments
        bool visibleBand = band == 0 ? showTrend : math.abs(band) == 1 ? show1 : math.abs(band) == 2 ? show2 : show3
        bool visible = activeSlot and not historyView and fitOK and visibleBand and not na(sigma)
        line ln = array.get(channelLines, slot)
        if visible
            int ta = mainFit.firstTime + int(math.round((projectionEnd - mainFit.firstTime) * (float(segment) / segments)))
            int tb = mainFit.firstTime + int(math.round((projectionEnd - mainFit.firstTime) * (float(segment + 1) / segments)))
            float ya = f_exp(mainFit.predict(f_x(ta)) + band * sigma)
            float yb = f_exp(mainFit.predict(f_x(tb)) + band * sigma)
            bool projected = ta >= mainFit.lastTime
            color c = projected ? color.new(f_bandColor(band), 55) : f_bandColor(band)
            string lineStyle = projected ? line.style_dotted : band == 0 ? line.style_solid : math.abs(band) == 2 ? line.style_dashed : line.style_dotted
            int width = band == 0 ? trendWidth : bandWidth
            if tb > ta and not na(ya) and not na(yb)
                if na(ln)
                    ln := line.new(ta, ya, tb, yb, xloc = xloc.bar_time, color = c, style = lineStyle, width = width)
                    array.set(channelLines, slot, ln)
                else
                    line.set_xy1(ln, ta, ya)
                    line.set_xy2(ln, tb, yb)
                    line.set_color(ln, c)
                    line.set_style(ln, lineStyle)
                    line.set_width(ln, width)
            else if not na(ln)
                line.delete(ln)
                array.set(channelLines, slot, na)
        else if not na(ln)
            line.delete(ln)
            array.set(channelLines, slot, na)
 
// A line pair supports one fill; TradingView replaces its previous fill when
// linefill.new is called again. Deleting a boundary line removes its fill.
// Only adjacent visible boundaries are shaded (at most 6 * 60 fills).
if barstate.islast and showShading and not historyView and fitOK
    for zone = 0 to 5
        for segment = 0 to segments - 1
            line lowerBoundary = array.get(channelLines, zone * segments + segment)
            line upperBoundary = array.get(channelLines, (zone + 1) * segments + segment)
            if not na(lowerBoundary) and not na(upperBoundary)
                linefill.new(lowerBoundary, upperBoundary, f_zoneColor(zone))
 
var label currentLabel = na
if barstate.islast
    if showLabel and sourceOK and not na(currentZ)
        string liveText = barstate.isconfirmed ? "CONFIRMED" : "LIVE"
        string positionText = math.abs(currentZ) < 0.05 ? "AT TREND" : currentZ < 0.0 ? "BELOW TREND" : "ABOVE TREND"
        color badgeAccent = math.abs(currentZ) < 0.05 ? trendColor : currentZ < 0.0 ? lowerColor : upperColor
        string labelText = f_z(currentZ) + "  ·  " + positionText + "\n" + liveText + "  ·  " + sourceMode
        string badgeTooltip = model + " | " + sourceMode + "\nFitted trend: " + f_num(currentTrend, "#.00") + "\nResidual dispersion, not reversal probability."
        if na(currentLabel)
            currentLabel := label.new(time + 2 * barMs, src, labelText, xloc = xloc.bar_time, style = label.style_label_left, color = color.rgb(23, 29, 43), textcolor = badgeAccent, size = size.normal, textalign = text.align_left)
        else
            label.set_xy(currentLabel, time + 2 * barMs, src)
            label.set_text(currentLabel, labelText)
        label.set_textcolor(currentLabel, badgeAccent)
        label.set_tooltip(currentLabel, badgeTooltip)
    else if not na(currentLabel)
        label.delete(currentLabel)
        currentLabel := na
 
f_row(table tbl, int row, string key, string value) =>
    color rowBackground = row == 0 ? color.rgb(42, 37, 66) : row % 2 == 0 ? color.rgb(23, 29, 43) : color.rgb(28, 35, 50)
    table.cell(tbl, 0, row, key, text_color = row == 0 ? trendColor : color.rgb(160, 172, 194), bgcolor = rowBackground, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, row, value, text_color = color.rgb(230, 235, 245), bgcolor = rowBackground, text_size = size.small, text_halign = text.align_left)
 
f_comparison(Fit f) =>
    f_date(f.firstTime) + " | " + f_z(f.zscore(x, logSource))
 
var int firstLoadedTime = time
var table diagnostics = table.new(position.top_right, 2, 19, border_width = 0, frame_color = color.rgb(60, 68, 88), frame_width = 1)
if barstate.islast
    table.clear(diagnostics, 0, 0, 1, 18)
    if showTable
        string status = fixedEnd and endTime < startTime ? "End precedes start" : power and startTime <= originTime ? "Origin clips requested sample" : not mainFit.ready() ? "Need " + str.tostring(minimumBars) + " valid bars" : not fitOK ? "Projection outside numeric range" : not sourceOK ? "Invalid current price source" : sigma <= 1e-10 ? "Zero residual spread: sigma score n/a" : "OK"
        string sampleState = not barstate.isconfirmed and includeLive and inMainRange and sourceOK ? "Includes live bar" : "Confirmed bars only"
        string horizon = fitOK ? f_num((time - mainFit.lastTime) / dayMs, "#.0") + " days after last fit bar open" : "n/a"
        f_row(diagnostics, 0, "LogReg v2 | " + timeframe.period, model + " | " + sourceMode)
        f_row(diagnostics, 1, "Status / sample", status + " | n=" + str.tostring(mainFit.n))
        f_row(diagnostics, 2, "Actual fit dates (bar opens)", f_date(mainFit.firstTime) + " to " + f_date(mainFit.lastTime))
        f_row(diagnostics, 3, "End mode", endMode + " | " + sampleState)
        f_row(diagnostics, 4, "Evaluation", horizon)
        f_row(diagnostics, 5, "Current trend / source", f_num(currentTrend, "#.00") + " / " + f_num(src, "#.00"))
        f_row(diagnostics, 6, "Current source deviation", f_z(currentZ) + (barstate.isconfirmed ? " | confirmed" : " | live"))
        f_row(diagnostics, 7, "Fitted next-year growth", f_num(growth * 100.0, "#.1") + "%")
        f_row(diagnostics, 8, "Residual sigma / log-fit R2", f_num(sigma, "#.000") + " / " + f_num(rSquared, "#.000"))
        f_row(diagnostics, 9, "Channel history", historyView ? "As known then; confirmed only" : "Redrawn using latest fit")
        f_row(diagnostics, 10, "Bands", "Residual dispersion; not probabilities")
        f_row(diagnostics, 11, "History coverage", firstLoadedTime > startTime + barMs ? "Loaded history starts after requested start" : "Check actual dates above")
        if showComparisons
            f_row(diagnostics, 12, "Start sensitivity | actual first", "Same model/source/end settings")
            f_row(diagnostics, 13, "2015 anchor", f_comparison(compare2015))
            f_row(diagnostics, 14, "2017 anchor", f_comparison(compare2017))
            f_row(diagnostics, 15, "2021 anchor", f_comparison(compare2021))
        float expRMSE = forecastCount > 0 ? math.sqrt(expSquaredErrors / forecastCount) : na
        float powerRMSE = forecastCount > 0 ? math.sqrt(powerSquaredErrors / forecastCount) : na
        f_row(diagnostics, 16, "Prior-fit log RMSE | same bars", "Exp " + f_num(expRMSE, "#.000") + " | Power " + f_num(powerRMSE, "#.000"))
        f_row(diagnostics, 17, "Forecast evaluation count", str.tostring(forecastCount) + " | lower RMSE is better")
        f_row(diagnostics, 18, "Model comparison", fixedEnd ? "One-step while fitting; frozen after end" : "Expanding one-bar-ahead forecasts")

← 返回列表