Residual Persistence Breakdown Map [Pineify]

Pineify · study · 247 行 · 点赞 211 · TradingView 原页

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

Pine Script

//@version=6
indicator("Residual Persistence Breakdown Map [Pineify]", shorttitle="Residual Map [Pineify]", overlay=false, max_bars_back=250)
 
// Independent implementation. Median paired slopes are not full Theil-Sen regression.
int halfWindow = input.int(16, "Half training window", minval=6, maxval=60, group="Model")
int atrLength = input.int(14, "ATR floor length", minval=2, maxval=100, group="Model")
float floorFraction = input.float(0.20, "ATR scale floor", minval=0.02, maxval=2.0, step=0.02, group="Model")
float entryZ = input.float(2.0, "Episode entry residual", minval=1.0, maxval=5.0, step=0.1, group="Episode")
float quietZ = input.float(0.75, "Quiet / same-sign deadband", minval=0.1, maxval=0.9, step=0.05, group="Episode")
int persistenceBars = input.int(4, "Same-sign closes for migration", minval=2, maxval=20, group="Episode")
int memoryBars = input.int(8, "Energy memory", minval=2, maxval=40, group="Episode")
float energyGate = input.float(0.08, "Migration energy threshold", minval=0.01, maxval=0.8, step=0.01, group="Episode")
float retentionGate = input.float(0.35, "Breakdown slope retention below", minval=-0.5, maxval=0.8, step=0.05, group="Episode")
float baselineGate = input.float(1.0, "Minimum baseline span / scale", minval=0.1, maxval=5.0, step=0.1, group="Episode")
int confirmBars = input.int(2, "Consecutive state candidates", minval=1, maxval=8, group="Episode")
int recoveryBars = input.int(3, "Quiet closes to end episode", minval=2, maxval=20, group="Episode")
int maxAge = input.int(120, "Episode expiry in bars", minval=20, maxval=300, group="Episode")
bool showEnergy = input.bool(true, "Signed persistence energy columns", group="Display")
bool showHalo = input.bool(true, "Energy halo", group="Display")
bool showBackground = input.bool(true, "Confirmed state background", group="Display")
bool showMarkers = input.bool(true, "State transition markers", group="Display")
bool showTable = input.bool(true, "Diagnostic table", group="Display")
 
int n = halfWindow * 2
float atr = ta.atr(atrLength)
 
// Train on [n]..[1]; current close never influences its own baseline fit.
f_fit(int half, float floorValue) =>
    int count = half * 2
    array<float> prices = array.new<float>(count, na)
    bool complete = not na(floorValue) and floorValue > 0
    for i = 0 to count - 1
        float y = close[count - i]
        array.set(prices, i, y)
        complete := complete and not na(y)
    float forecast = na
    float slope = na
    float scale = na
    if complete
        array<float> slopes = array.new<float>(half, 0.0)
        for i = 0 to half - 1
            array.set(slopes, i, (array.get(prices, i + half) - array.get(prices, i)) / half)
        slope := array.median(slopes)
        array<float> intercepts = array.new<float>(count, 0.0)
        for i = 0 to count - 1
            array.set(intercepts, i, array.get(prices, i) - slope * i)
        float intercept = array.median(intercepts)
        array<float> deviations = array.new<float>(count, 0.0)
        for i = 0 to count - 1
            array.set(deviations, i, math.abs(array.get(prices, i) - intercept - slope * i))
        scale := math.max(1.4826 * array.median(deviations), math.max(floorValue, syminfo.mintick))
        forecast := intercept + slope * count
    [forecast, slope, scale]
 
[rollingForecast, rollingSlope, rollingScale] = f_fit(halfWindow, atr[1] * floorFraction)
bool validNow = not na(close) and not na(rollingForecast) and not na(rollingScale) and rollingScale > 0
float rollingZ = validNow ? (close - rollingForecast) / rollingScale : na
 
var bool coverage = false
var bool active = false
var int originBar = 0
var float frozenForecast = na
var float frozenSlope = na
var float frozenScale = na
var bool baselineInformative = false
var int runSign = 0
var int runLength = 0
var int quietCount = 0
var float energy = 0.0
var int state = 0
var int candidate = 0
var int candidateCount = 0
var float zSnapshot = na
var float retention = na
var int age = 0
var bool frozenSnapshot = false
var bool frameReset = false
bool migrationEvent = false
bool breakdownEvent = false
bool recoveryEvent = false
bool expiryEvent = false
bool coverageLost = false
bool coverageRestored = false
 
if barstate.isconfirmed
    coverageLost := coverage and not validNow
    coverageRestored := not coverage and validNow
    coverage := validNow
    frameReset := frozenSnapshot and not active
    frozenSnapshot := false
    if not coverage
        active := false
        state := 0
        candidate := 0
        candidateCount := 0
        energy := 0.0
        runLength := 0
        runSign := 0
        quietCount := 0
        age := 0
        zSnapshot := na
        retention := na
        baselineInformative := false
    else
        // Expiry ends an observation; it is never reported as recovery.
        bool expired = active and bar_index - originBar >= maxAge
        if expired
            active := false
            state := 0
            candidate := 0
            candidateCount := 0
            runLength := 0
            runSign := 0
            quietCount := 0
            energy := 0.0
            age := 0
            retention := na
            baselineInformative := false
            expiryEvent := true
            frameReset := true
        if not active and not expired and math.abs(rollingZ) >= entryZ
            active := true
            originBar := bar_index
            frozenForecast := rollingForecast
            frozenSlope := rollingSlope
            frozenScale := rollingScale
            baselineInformative := math.abs(frozenSlope) * n / frozenScale >= baselineGate
            runLength := 0
            runSign := 0
            quietCount := 0
            energy := 0.0
            candidate := 0
            candidateCount := 0
        zSnapshot := rollingZ
        if active
            frozenSnapshot := true
            age := bar_index - originBar
            zSnapshot := (close - frozenForecast - frozenSlope * age) / frozenScale
            retention := baselineInformative ? math.sign(frozenSlope) * rollingSlope / math.abs(frozenSlope) : na
            int side = zSnapshot > quietZ ? 1 : zSnapshot < -quietZ ? -1 : 0
            float alpha = 2.0 / (memoryBars + 1.0)
            float excess = math.min(6.0, math.max(0.0, math.abs(zSnapshot) - quietZ)) / 6.0
            if side == 0
                runLength := 0
                runSign := 0
                quietCount += 1
                energy *= 1.0 - alpha
            else
                bool sameSide = side == runSign
                runLength := sameSide ? runLength + 1 : 1
                energy := (sameSide ? energy * (1.0 - alpha) : 0.0) + alpha * excess * excess
                runSign := side
                quietCount := 0
            if quietCount >= recoveryBars
                active := false
                recoveryEvent := true
                state := 0
                candidate := 0
                candidateCount := 0
                runLength := 0
                runSign := 0
                energy := 0.0
                retention := na
                baselineInformative := false
                age := 0
                // This bar keeps its frozen-frame residual; next bar resumes rolling fit.
            else
                bool holdingMigration = state == 2 or state == 3
                int requiredRun = holdingMigration ? math.max(2, persistenceBars - 1) : persistenceBars
                float requiredEnergy = energyGate * (holdingMigration ? 0.7 : 1.0)
                bool migrating = runLength >= requiredRun and energy >= requiredEnergy
                float requiredRetention = retentionGate + (state == 3 ? 0.15 : 0.0)
                bool broken = migrating and baselineInformative and retention < requiredRetention
                int desired = broken ? 3 : migrating ? 2 : state >= 2 ? 4 : side != 0 ? 1 : 0
                if desired == state
                    candidate := state
                    candidateCount := 0
                else
                    candidateCount := desired == candidate ? candidateCount + 1 : 1
                    candidate := desired
                    if candidateCount >= confirmBars
                        state := desired
                        candidateCount := 0
                        migrationEvent := state == 2
                        breakdownEvent := state == 3
        else if not expired
            retention := na
            age := 0
 
color amber = color.rgb(176, 111, 0)
color blue = color.rgb(35, 118, 203)
color coral = color.rgb(211, 65, 82)
color teal = color.rgb(0, 139, 119)
color stateColor = state == 1 ? amber : state == 2 ? blue : state == 3 ? coral : state == 4 ? teal : chart.fg_color
float displayZ = math.max(-6.0, math.min(6.0, zSnapshot))
float signedEnergy = coverage and active ? runSign * 3.0 * energy : na
plot(showEnergy ? signedEnergy : na, "Signed energy (3 x E)", color=color.new(stateColor, 55), style=plot.style_columns)
plot(showHalo and coverage and not frameReset ? displayZ : na, "Energy halo", color=color.new(stateColor, int(94 - 25 * energy)), linewidth=10, style=plot.style_linebr)
plot(coverage and not frameReset ? displayZ : na, "Confirmed residual (clipped at 6)", color=stateColor, linewidth=3, style=plot.style_linebr)
topQuiet = hline(quietZ, "Quiet upper", color=color.new(chart.fg_color, 80))
bottomQuiet = hline(-quietZ, "Quiet lower", color=color.new(chart.fg_color, 80))
fill(topQuiet, bottomQuiet, color=color.new(chart.fg_color, 95), title="Quiet region")
hline(0, "Model center", color=color.new(chart.fg_color, 60))
hline(entryZ, "Rolling entry upper", color=color.new(amber, 55), linestyle=hline.style_dashed)
hline(-entryZ, "Rolling entry lower", color=color.new(amber, 55), linestyle=hline.style_dashed)
bgcolor(showBackground and coverage and state > 0 ? color.new(stateColor, 93) : na, title="Confirmed episode state")
plotshape(showMarkers and migrationEvent, "Migration", shape.triangleup, location.top, blue, size=size.tiny, text="M")
plotshape(showMarkers and breakdownEvent, "Breakdown", shape.diamond, location.top, coral, size=size.tiny, text="B")
plotshape(showMarkers and recoveryEvent, "Quiet recovery", shape.circle, location.bottom, teal, size=size.tiny, text="Q")
plotshape(showMarkers and expiryEvent, "Expiry", shape.xcross, location.bottom, amber, size=size.tiny, text="X")
plot(zSnapshot, "Raw residual (unclipped)", display=display.data_window)
plot(coverage ? energy : na, "Energy 0-1", display=display.data_window)
plot(retention, "Frozen baseline slope retention", display=display.data_window)
plot(coverage ? runLength : na, "Same-sign run", display=display.data_window)
plot(coverage ? state : na, "State: 0 neutral 1 anomaly 2 migration 3 breakdown 4 recovery", display=display.data_window)
 
f_number(float value) =>
    na(value) ? "n/a" : str.tostring(value, "#.##")
 
var table dashboard = table.new(position.top_right, 2, 8, bgcolor=color.new(chart.bg_color, 8), frame_color=color.new(chart.fg_color, 70), frame_width=1)
if barstate.islast
    table.clear(dashboard, 0, 0, 1, 7)
    if showTable
        string stateText = not coverage ? "WARMUP / GAP" : state == 0 ? (active ? "PENDING" : "NEUTRAL") : state == 1 ? "ANOMALY" : state == 2 ? "MIGRATION" : state == 3 ? "BREAKDOWN" : "RECOVERY WATCH"
        table.cell(dashboard, 0, 0, "RESIDUAL MAP", text_color=chart.fg_color, text_size=size.small)
        table.cell(dashboard, 1, 0, stateText, text_color=stateColor, text_size=size.small)
        table.cell(dashboard, 0, 1, "Raw residual", text_color=chart.fg_color)
        table.cell(dashboard, 1, 1, f_number(zSnapshot), text_color=chart.fg_color)
        table.cell(dashboard, 0, 2, "Same-sign closes", text_color=chart.fg_color)
        table.cell(dashboard, 1, 2, str.tostring(runLength), text_color=chart.fg_color)
        table.cell(dashboard, 0, 3, "Energy %", text_color=chart.fg_color)
        table.cell(dashboard, 1, 3, f_number(energy * 100), text_color=chart.fg_color)
        table.cell(dashboard, 0, 4, "Slope retained", text_color=chart.fg_color)
        table.cell(dashboard, 1, 4, f_number(retention), text_color=chart.fg_color)
        table.cell(dashboard, 0, 5, "Frozen age / limit", text_color=chart.fg_color)
        table.cell(dashboard, 1, 5, active ? str.tostring(age) + " / " + str.tostring(maxAge) : "inactive", text_color=chart.fg_color)
        table.cell(dashboard, 0, 6, "Slope baseline", text_color=chart.fg_color)
        table.cell(dashboard, 1, 6, active ? (baselineInformative ? "directional" : "too flat") : "inactive", text_color=chart.fg_color)
        table.cell(dashboard, 0, 7, "Residual frame", text_color=chart.fg_color)
        table.cell(dashboard, 1, 7, frozenSnapshot ? "frozen" : "rolling", text_color=chart.fg_color)
 
alertcondition(migrationEvent, "Confirmed residual migration", "Residual Map: same-sign energy migration confirmed.")
alertcondition(breakdownEvent, "Confirmed slope breakdown", "Residual Map: persistent residual with frozen baseline slope loss.")
alertcondition(recoveryEvent, "Quiet recovery to neutral", "Residual Map: consecutive closes inside the frozen quiet band; neutral restored.")
alertcondition(expiryEvent, "Episode expired", "Residual Map: frozen observation expired; expiry is not recovery.")
alertcondition(coverageLost, "Data coverage lost", "Residual Map: model unavailable; episode and state cleared.")
alertcondition(coverageRestored, "Data coverage restored", "Residual Map: complete prior training window available.")

← 返回列表