Anchored Log-Linear Regression Channels

ionaryu · study · 236 行 · 点赞 18 · TradingView 原页

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

Pine Script

//@version=6
// =============================================================================
// Title:       Anchored Log-Linear Regression Channels
// Short Title: LogReg Channels
// Description: 
//   Interactive anchored exponential (log-linear) regression trendline with 
//   up to 4 customizable Standard Deviation (SD) bands.
//
// Key Technical Features:
//   1. Interactive Chart Anchoring: Uses `confirm = true` so users can click 
//      start and end points directly on the chart and drag anchor lines freely.
//   2. Auto-Chronological Sorting: Automatically orders the two anchor points 
//      even if clicked or dragged in reverse chronological order.
//   3. O(1) Loopless Execution: Uses cumulative prefix-sum snapshots (ta.cum) 
//      instead of historical loops, ensuring zero lag across massive datasets.
//   4. Numerical Stability & Buffer Safety: Uses exact closed-form X-variance 
//      math and clamps visual coordinates to respect historical buffer limits.
// =============================================================================
indicator(title = "Anchored Log-Linear Regression Channels", shorttitle = "LogReg Channels", overlay = true)
 
// =============================================================================
// --- INPUTS ---
// =============================================================================
grp_general = "General Settings"
source       = input.source(close, title = "Source", group = grp_general, tooltip = "Price or indicator source for the log-linear regression. Must be strictly positive.")
extend_right = input.int(20, title = "Extend Right (Bars)", minval = 0, maxval = 500, group = grp_general, tooltip = "Number of bars to project the regression channel to the right of the end anchor. TradingView draws at most 500 bars into the future.")
 
grp_anchor = "Interactive Date Anchor Settings"
use_anchor     = input.bool(true, title = "Use Start Anchor (1st Click)", group = grp_anchor, tooltip = "If enabled, regression starts at the 1st interactive anchor point. If disabled, it starts from the very first bar on the chart.")
start_time     = input.time(timestamp("2026-01-01T00:00:00"), title = "Start Anchor", group = grp_anchor, confirm = true, tooltip = "Click on the chart when adding the indicator, or drag the vertical anchor line on the chart.")
use_end_anchor = input.bool(true, title = "Use End Anchor (2nd Click)", group = grp_anchor, tooltip = "If enabled, regression stops at the 2nd interactive anchor point. Uncheck this to continuously calculate up to the latest real-time bar.")
end_time       = input.time(timestamp("2099-12-31T00:00:00"), title = "End Anchor", group = grp_anchor, confirm = true, tooltip = "Click the second point on the chart when adding the indicator, or drag the second vertical anchor line.")
 
grp_performance = "Performance Settings"
max_bars = input.int(5000, title = "Max Bars for Drawing", minval = 10, maxval = 9999, group = grp_performance, tooltip = "Limits the visual start point of lines to prevent TradingView historical buffer errors while preserving full-range regression accuracy.")
 
grp_visual = "Visual Settings"
enum LineStyle
    solid  = "Solid"
    dashed = "Dashed"
    dotted = "Dotted"
 
// Basis Line
bool      show_0  = input.bool(true, "Basis", group = grp_visual, inline = "row0")
color     col_0   = input.color(color.white, "", group = grp_visual, inline = "row0")
int       width_0 = input.int(1, "", minval = 1, group = grp_visual, inline = "row0")
LineStyle style_0 = input.enum(LineStyle.solid, "", group = grp_visual, inline = "row0")
 
// Standard Deviation Band 0.5
bool      show_1  = input.bool(true, "Band 0.5 (±σ)", group = grp_visual, inline = "row1")
float     val_1   = input.float(0.5, "", step = 0.1, group = grp_visual, inline = "row1")
color     col_1   = input.color(color.green, "", group = grp_visual, inline = "row1")
int       width_1 = input.int(1, "", minval = 1, group = grp_visual, inline = "row1")
LineStyle style_1 = input.enum(LineStyle.dotted, "", group = grp_visual, inline = "row1")
 
// Standard Deviation Band 1
bool      show_2  = input.bool(true, "Band 1 (±σ)", group = grp_visual, inline = "row2")
float     val_2   = input.float(1.0, "", step = 0.1, group = grp_visual, inline = "row2")
color     col_2   = input.color(color.yellow, "", group = grp_visual, inline = "row2")
int       width_2 = input.int(1, "", minval = 1, group = grp_visual, inline = "row2")
LineStyle style_2 = input.enum(LineStyle.dashed, "", group = grp_visual, inline = "row2")
 
// Standard Deviation Band 1.5
bool      show_3  = input.bool(true, "Band 1.5 (±σ)", group = grp_visual, inline = "row3")
float     val_3   = input.float(1.5, "", step = 0.1, group = grp_visual, inline = "row3")
color     col_3   = input.color(color.orange, "", group = grp_visual, inline = "row3")
int       width_3 = input.int(1, "", minval = 1, group = grp_visual, inline = "row3")
LineStyle style_3 = input.enum(LineStyle.dotted, "", group = grp_visual, inline = "row3")
 
// Standard Deviation Band 2
bool      show_4  = input.bool(true, "Band 2 (±σ)", group = grp_visual, inline = "row4")
float     val_4   = input.float(2.0, "", step = 0.1, group = grp_visual, inline = "row4")
color     col_4   = input.color(color.red, "", group = grp_visual, inline = "row4")
int       width_4 = input.int(1, "", minval = 1, group = grp_visual, inline = "row4")
LineStyle style_4 = input.enum(LineStyle.solid, "", group = grp_visual, inline = "row4")
 
// =============================================================================
// --- HELPER FUNCTIONS & LINE INITIALIZATION ---
// =============================================================================
// Converts custom enum selection to built-in Pine Script line style
parseLineStyle(LineStyle style_val) =>
    switch style_val
        LineStyle.solid  => line.style_solid
        LineStyle.dashed => line.style_dashed
        LineStyle.dotted => line.style_dotted
 
// Parses a channel line
method hideChannel(line ln) =>
    ln.set_y1(na)
    ln.set_y2(na)
 
// Updates line style and coordinates by transforming log-space values back to price space
method updateChannelLine(line ln, bool visible, int x1, float y1_log, int x2, float y2_log, color col, int w, string st) =>
    if visible
        ln.set_style(st)
        ln.set_color(col)
        ln.set_width(w)
        ln.set_x1(x1)
        ln.set_y1(math.exp(y1_log))
        ln.set_x2(x2)
        ln.set_y2(math.exp(y2_log))
    else
        ln.hideChannel()
 
// Persistent line objects allocated once at initialization
var line trend_line  = line.new(na, na, na, na, style = parseLineStyle(style_0), width = width_0, color = col_0)
var line plus1_line  = line.new(na, na, na, na, style = parseLineStyle(style_1), width = width_1, color = col_1)
var line minus1_line = line.new(na, na, na, na, style = parseLineStyle(style_1), width = width_1, color = col_1)
var line plus2_line  = line.new(na, na, na, na, style = parseLineStyle(style_2), width = width_2, color = col_2)
var line minus2_line = line.new(na, na, na, na, style = parseLineStyle(style_2), width = width_2, color = col_2)
var line plus3_line  = line.new(na, na, na, na, style = parseLineStyle(style_3), width = width_3, color = col_3)
var line minus3_line = line.new(na, na, na, na, style = parseLineStyle(style_3), width = width_3, color = col_3)
var line plus4_line  = line.new(na, na, na, na, style = parseLineStyle(style_4), width = width_4, color = col_4)
var line minus4_line = line.new(na, na, na, na, style = parseLineStyle(style_4), width = width_4, color = col_4)
 
// =============================================================================
// --- CORE LOGIC: PREFIX SUMS & SNAPSHOTS ---
// =============================================================================
// Automatically sort anchor timestamps in case the user clicks or drags in reverse order
int actual_start_time = (use_anchor and use_end_anchor) ? math.min(start_time, end_time) : start_time
int actual_end_time   = (use_anchor and use_end_anchor) ? math.max(start_time, end_time) : end_time
 
// Guard against 'na' or non-positive values on early bars to prevent corrupting ta.cum()
bool  is_valid_src = not na(source) and source > 0
float log_source   = is_valid_src ? math.log(source) : 0.0
 
// 1. Cumulative Prefix Sums (O(1) range query preparation)
float cumY  = ta.cum(log_source)
float cumY2 = ta.cum(log_source * log_source)
float cumXY = ta.cum(bar_index * log_source)
 
// 2. State Variables for Anchor Snapshots
var float start_snap_Y   = 0.0
var float start_snap_Y2  = 0.0
var float start_snap_XY  = 0.0
var int   start_idx      = 0
var bool  is_start_found = false
 
var float end_snap_Y     = 0.0
var float end_snap_Y2    = 0.0
var float end_snap_XY    = 0.0
var int   end_idx        = 0
var bool  is_end_found   = false
 
// 3. Start Anchor Detection
// Captures the cumulative sum immediately prior to the first valid anchored bar
if not is_start_found and is_valid_src
    if not use_anchor or time >= actual_start_time
        start_snap_Y   := (bar_index == 0) ? 0.0 : cumY[1]
        start_snap_Y2  := (bar_index == 0) ? 0.0 : cumY2[1]
        start_snap_XY  := (bar_index == 0) ? 0.0 : cumXY[1]
        start_idx      := bar_index
        is_start_found := true
 
// 4. End Anchor Detection
// Continuously updates the end snapshot until actual_end_time is exceeded
if is_start_found and is_valid_src
    if not use_end_anchor or time <= actual_end_time
        end_snap_Y   := cumY
        end_snap_Y2  := cumY2
        end_snap_XY  := cumXY
        end_idx      := bar_index
        is_end_found := true
 
// =============================================================================
// --- REGRESSION CALCULATION & RENDERING ---
// =============================================================================
if barstate.islast
    // Require both anchors and at least 2 data points to define a regression line
    bool drawable = is_start_found and is_end_found and (end_idx - start_idx + 1) >= 2
 
    if drawable
        int   n       = end_idx - start_idx + 1
        float n_float = float(n)
 
        // Range Sums = End Snapshot - Start Pre-Snapshot
        float sumY  = end_snap_Y - start_snap_Y
        float sumY2 = end_snap_Y2 - start_snap_Y2
        float sumXY = end_snap_XY - start_snap_XY
 
        // Closed-form X statistics for consecutive bar indices (avoids float overflow)
        float meanX = 0.5 * (start_idx + end_idx)
        float meanY = sumY / n_float
        float sumX  = n_float * meanX
 
        // Centered sums of squares and cross-products
        float Sxx = n_float * (n_float * n_float - 1.0) / 12.0
        float Sxy = sumXY - sumX * meanY
        float Syy = sumY2 - sumY * meanY
 
        // Ordinary Least Squares (OLS) Slope and Intercept in log-space
        float slope     = Sxx == 0.0 ? 0.0 : Sxy / Sxx
        float intercept = meanY - slope * meanX
 
        // Unbiased residual standard deviation (degrees of freedom = n - 2)
        float sumDev2 = math.max(0.0, Syy - slope * Sxy)
        float df      = math.max(1.0, n_float - 2.0)
        float stdev   = math.sqrt(sumDev2 / df)
 
        // Clamp visual start coordinate to max_bars to respect historical buffer limits
        int x1 = math.max(start_idx, bar_index - max_bars)
        int x2 = end_idx + extend_right
 
        float y1_log = intercept + slope * x1
        float y2_log = intercept + slope * x2
 
        string st0 = parseLineStyle(style_0)
        string st1 = parseLineStyle(style_1)
        string st2 = parseLineStyle(style_2)
        string st3 = parseLineStyle(style_3)
        string st4 = parseLineStyle(style_4)
 
        trend_line.updateChannelLine(show_0, x1, y1_log, x2, y2_log, col_0, width_0, st0)
 
        plus1_line.updateChannelLine(show_1, x1, y1_log + val_1 * stdev, x2, y2_log + val_1 * stdev, col_1, width_1, st1)
        minus1_line.updateChannelLine(show_1, x1, y1_log - val_1 * stdev, x2, y2_log - val_1 * stdev, col_1, width_1, st1)
 
        plus2_line.updateChannelLine(show_2, x1, y1_log + val_2 * stdev, x2, y2_log + val_2 * stdev, col_2, width_2, st2)
        minus2_line.updateChannelLine(show_2, x1, y1_log - val_2 * stdev, x2, y2_log - val_2 * stdev, col_2, width_2, st2)
 
        plus3_line.updateChannelLine(show_3, x1, y1_log + val_3 * stdev, x2, y2_log + val_3 * stdev, col_3, width_3, st3)
        minus3_line.updateChannelLine(show_3, x1, y1_log - val_3 * stdev, x2, y2_log - val_3 * stdev, col_3, width_3, st3)
 
        plus4_line.updateChannelLine(show_4, x1, y1_log + val_4 * stdev, x2, y2_log + val_4 * stdev, col_4, width_4, st4)
        minus4_line.updateChannelLine(show_4, x1, y1_log - val_4 * stdev, x2, y2_log - val_4 * stdev, col_4, width_4, st4)
    else
        // Regression undefined for this range: remove the previously drawn channel
        trend_line.hideChannel()
        plus1_line.hideChannel()
        minus1_line.hideChannel()
        plus2_line.hideChannel()
        minus2_line.hideChannel()
        plus3_line.hideChannel()
        minus3_line.hideChannel()
        plus4_line.hideChannel()
        minus4_line.hideChannel()

← 返回列表