本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Return Distribution Drift Monitor [Pineify]", shorttitle="Distribution Drift [Pineify]", overlay=false, max_bars_back=500, precision=2)
string gWindow = "Distribution windows"
int recentLen = input.int(24, "Recent returns", minval=20, maxval=80, group=gWindow)
int referenceLen = input.int(120, "Prior reference returns", minval=80, maxval=320, group=gWindow)
float tailPercent = input.float(20, "Reference tail percentile", minval=15, maxval=25, step=1, group=gWindow)
float floorBps = input.float(0.1, "Robust scale floor (basis points)", minval=0.01, maxval=10, step=0.01, group=gWindow)
string gState = "Evidence and persistence"
float centerGate = input.float(0.5, "Center effect entry", minval=0.1, maxval=3, step=0.05, group=gState)
float scaleGate = input.float(0.5, "Relative scale expansion entry", minval=0.1, maxval=3, step=0.05, group=gState)
float tailGate = input.float(0.1, "Tail share change entry", minval=0.02, maxval=0.5, step=0.01, group=gState)
int memoryLen = input.int(5, "Closed evidence memory", minval=2, maxval=20, group=gState)
float voteGate = input.float(0.6, "Required memory share", minval=0.5, maxval=1, step=0.05, group=gState)
int confirmBars = input.int(2, "Consecutive candidate closes", minval=1, maxval=10, group=gState)
int settleBars = input.int(5, "Quiet closes for recalibration", minval=2, maxval=30, group=gState)
string gView = "Visual layers"
bool showScale = input.bool(true, "Scale change envelope", group=gView)
bool showTails = input.bool(true, "Tail balance columns", group=gView)
bool showBackground = input.bool(true, "Confirmed state background", group=gView)
bool showEvents = input.bool(true, "Confirmed event markers", group=gView)
bool showTable = input.bool(true, "Diagnostic table", group=gView)
// The reference ends before the recent window starts. No return is in both.
// One invalid slot blocks statistics instead of shortening calendar observation slots.
float logReturn = not na(close) and not na(close[1]) and close > 0 and close[1] > 0 ? math.log(close / close[1]) : na
array<float> recent = array.new_float(0)
array<float> reference = array.new_float(0)
int validSlots = 0
for i = 0 to recentLen + referenceLen - 1
float value = logReturn[i]
if not na(value)
validSlots += 1
if i < recentLen
array.push(recent, value)
else
array.push(reference, value)
bool complete = chart.is_standard and validSlots == recentLen + referenceLen
float coverage = float(validSlots) / (recentLen + referenceLen)
float centerEffect = na
float scaleEffect = na
float tailBalance = na
float tailExcess = na
float recentMedian = na
float referenceMedian = na
float recentScale = na
float referenceScale = na
float recentLow = na
float recentHigh = na
float referenceLow = na
float referenceHigh = na
bool usable = false
if complete
array.sort(recent)
array.sort(reference)
recentMedian := array.median(recent)
referenceMedian := array.median(reference)
array<float> recentDeviation = array.new_float(0)
array<float> referenceDeviation = array.new_float(0)
for value in recent
array.push(recentDeviation, math.abs(value - recentMedian))
for value in reference
array.push(referenceDeviation, math.abs(value - referenceMedian))
recentScale := math.max(1.4826 * array.median(recentDeviation), floorBps / 10000)
referenceScale := math.max(1.4826 * array.median(referenceDeviation), floorBps / 10000)
recentLow := array.percentile_linear_interpolation(recent, tailPercent)
recentHigh := array.percentile_linear_interpolation(recent, 100 - tailPercent)
referenceLow := array.percentile_linear_interpolation(reference, tailPercent)
referenceHigh := array.percentile_linear_interpolation(reference, 100 - tailPercent)
// A flat reference has no distinct empirical tails; a floor alone is insufficient.
usable := referenceHigh > referenceLow
if usable
float upperRecent = 0
float lowerRecent = 0
float upperReference = 0
float lowerReference = 0
for value in recent
upperRecent += value > referenceHigh ? 1 : 0
lowerRecent += value < referenceLow ? 1 : 0
for value in reference
upperReference += value > referenceHigh ? 1 : 0
lowerReference += value < referenceLow ? 1 : 0
float upperChange = upperRecent / recentLen - upperReference / referenceLen
float lowerChange = lowerRecent / recentLen - lowerReference / referenceLen
centerEffect := (recentMedian - referenceMedian) / referenceScale
scaleEffect := recentScale / referenceScale - 1
tailBalance := upperChange - lowerChange
tailExcess := upperChange + lowerChange
// Codes: 1 quiet, 2 upward center shift, 3 downward center shift,
// 4 scale expansion, 5 mixed/unconfirmed; directional evidence has priority.
bool upEvidence = usable and centerEffect >= centerGate and tailBalance >= tailGate
bool downEvidence = usable and centerEffect <= -centerGate and tailBalance <= -tailGate
bool expansionEvidence = usable and scaleEffect >= scaleGate and tailExcess >= tailGate
bool quietEvidence = usable and math.abs(centerEffect) <= centerGate * 0.5 and math.abs(scaleEffect) <= scaleGate * 0.5 and math.abs(tailBalance) <= tailGate * 0.5 and math.abs(tailExcess) <= tailGate * 0.5
int rawCode = not usable ? 0 : upEvidence ? 2 : downEvidence ? 3 : expansionEvidence ? 4 : quietEvidence ? 1 : 5
var array<int> memory = array.new_int(0)
var int state = 0
var int pending = 0
var int candidateRun = 0
var int quietRun = 0
var bool driftOpen = false
bool directionEvent = false
bool expansionEvent = false
bool recalibrationEvent = false
int currentVotes = 0
// Persistent memory, clocks, state, and alerts change only on closed bars.
if barstate.isconfirmed
if not usable
array.clear(memory)
state := 0
pending := 0
candidateRun := 0
quietRun := 0
driftOpen := false
else
array.push(memory, rawCode)
if array.size(memory) > memoryLen
array.shift(memory)
quietRun := quietEvidence ? math.min(quietRun + 1, settleBars) : 0
int quietVotes = 0
for code in memory
currentVotes += code == rawCode ? 1 : 0
quietVotes += code == 1 ? 1 : 0
bool mature = array.size(memory) == memoryLen
bool persistentDrift = mature and rawCode >= 2 and rawCode <= 4 and float(currentVotes) / memoryLen >= voteGate
bool persistentQuiet = mature and quietEvidence and float(quietVotes) / memoryLen >= voteGate
int desired = 0
if mature
if persistentDrift
desired := rawCode
else if driftOpen and quietEvidence
desired := quietRun >= settleBars and persistentQuiet ? 1 : 6
else
desired := persistentQuiet ? 1 : 5
if desired != state
if pending == desired
candidateRun := math.min(candidateRun + 1, confirmBars)
else
pending := desired
candidateRun := 1
if candidateRun >= confirmBars
int previous = state
state := desired
directionEvent := (state == 2 or state == 3) and state != previous
expansionEvent := state == 4 and previous != 4
recalibrationEvent := state == 1 and driftOpen
if state >= 2 and state <= 4
driftOpen := true
if recalibrationEvent
driftOpen := false
candidateRun := 0
pending := state
else
candidateRun := 0
pending := state
color upColor = #137AA8
color downColor = #BA467F
color expansionColor = #B0711C
color contractionColor = #7D62C0
color settledColor = #168675
color neutralColor = #737B88
color stateColor = state == 2 ? upColor : state == 3 ? downColor : state == 4 ? expansionColor : state == 6 ? settledColor : neutralColor
color centerColor = centerEffect > 0 ? upColor : centerEffect < 0 ? downColor : neutralColor
// Geometry is clipped only for display. Raw values remain in the Data Window.
float centerView = usable ? math.max(-4, math.min(4, centerEffect)) : na
float scaleWidth = usable ? math.min(2, math.abs(scaleEffect)) : na
color scaleColor = scaleEffect >= 0 ? expansionColor : contractionColor
hline(0, "No center shift", color=color.new(neutralColor, 45))
plot(showTails and usable ? 2 * tailBalance : na, "Tail balance x2", style=plot.style_columns, color=color.new(tailBalance >= 0 ? upColor : downColor, 65), histbase=0)
pUpper = plot(showScale ? centerView + scaleWidth : na, "Scale envelope upper", color=color.new(scaleColor, 100))
pLower = plot(showScale ? centerView - scaleWidth : na, "Scale envelope lower", color=color.new(scaleColor, 100))
fill(pUpper, pLower, color=color.new(scaleColor, 84), title="Absolute relative scale change")
plot(centerView, "Center shift (clipped +/-4)", color=centerColor, linewidth=3, style=plot.style_linebr)
plot(usable ? centerGate : na, "Center entry +", color=color.new(neutralColor, 60), style=plot.style_linebr)
plot(usable ? -centerGate : na, "Center entry -", color=color.new(neutralColor, 60), style=plot.style_linebr)
bgcolor(showBackground and usable and state > 0 ? color.new(stateColor, 94) : na, title="Last confirmed distribution state")
plotshape(showEvents and directionEvent and state == 2 ? centerView : na, "Upward distribution drift", style=shape.triangleup, location=location.absolute, color=upColor, size=size.tiny, text="D", textcolor=chart.fg_color)
plotshape(showEvents and directionEvent and state == 3 ? centerView : na, "Downward distribution drift", style=shape.triangledown, location=location.absolute, color=downColor, size=size.tiny, text="D", textcolor=chart.fg_color)
plotshape(showEvents and expansionEvent ? centerView : na, "Scale expansion drift", style=shape.diamond, location=location.absolute, color=expansionColor, size=size.tiny, text="S", textcolor=chart.fg_color)
plotshape(showEvents and recalibrationEvent ? centerView : na, "Relative recalibration complete", style=shape.circle, location=location.absolute, color=settledColor, size=size.tiny, text="R", textcolor=chart.fg_color)
plot(centerEffect, "Raw center effect", display=display.data_window)
plot(scaleEffect * 100, "Raw relative scale change %", display=display.data_window)
plot(tailBalance * 100, "Tail balance change percentage points", display=display.data_window)
plot(tailExcess * 100, "Total tail share change percentage points", display=display.data_window)
plot(usable ? (recentLow - referenceLow) / referenceScale : na, "Lower quantile shift", display=display.data_window)
plot(usable ? (recentHigh - referenceHigh) / referenceScale : na, "Upper quantile shift", display=display.data_window)
plot(100 * coverage, "Slot coverage %", display=display.data_window)
plot(state, "Confirmed state code", display=display.data_window)
string stateText = state == 1 ? "Balanced" : state == 2 ? "Upward drift" : state == 3 ? "Downward drift" : state == 4 ? "Scale expansion" : state == 5 ? "Mixed / unconfirmed" : state == 6 ? "Recalibrating" : "Warming / unavailable"
string availability = not chart.is_standard ? "Standard chart required" : not complete ? "Incomplete return slots" : not usable ? "Flat reference tails" : "Valid; live metrics"
var table panel = table.new(position.top_right, 2, 9, border_width=0)
if barstate.islast
table.clear(panel, 0, 0, 1, 8)
if showTable
color bg = color.new(chart.bg_color, 8)
table.cell(panel, 0, 0, "DISTRIBUTION DRIFT", text_color=chart.fg_color, bgcolor=bg, text_size=size.small)
table.cell(panel, 1, 0, "State at close", text_color=chart.fg_color, bgcolor=bg, text_size=size.small)
table.cell(panel, 0, 1, "Confirmed state", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 1, stateText, text_color=stateColor, bgcolor=bg)
table.cell(panel, 0, 2, "Recent / prior bars", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 2, str.tostring(recentLen) + " / " + str.tostring(referenceLen), text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 0, 3, "Center / reference scale", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 3, str.tostring(centerEffect, "#.##"), text_color=centerColor, bgcolor=bg)
table.cell(panel, 0, 4, "Relative scale change", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 4, str.tostring(scaleEffect * 100, "#.##") + "%", text_color=scaleColor, bgcolor=bg)
table.cell(panel, 0, 5, "Tail balance / total pp", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 5, str.tostring(tailBalance * 100, "#.##") + " / " + str.tostring(tailExcess * 100, "#.##"), text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 0, 6, "Closed memory / quiet", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 6, str.tostring(array.size(memory)) + "/" + str.tostring(memoryLen) + " | " + str.tostring(quietRun), text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 0, 7, "Data coverage", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 7, str.tostring(coverage * 100, "#.#") + "%", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 0, 8, "Availability", text_color=chart.fg_color, bgcolor=bg)
table.cell(panel, 1, 8, availability, text_color=chart.fg_color, bgcolor=bg, text_size=size.small)
alertcondition(directionEvent, "Confirmed directional distribution drift", "A center shift with matching tail asymmetry passed closed-bar persistence. This is return-distribution context, not an order.")
alertcondition(expansionEvent, "Confirmed scale expansion drift", "Robust scale expansion with excess tail share passed closed-bar persistence.")
alertcondition(recalibrationEvent, "Confirmed relative distribution recalibration", "A previously confirmed drift episode returned to quiet short/prior comparisons. This is relative convergence, not a fitted new distribution.")