本页源码来自 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/
// © Market_Logic_India
// ══════════════════════════════════════════════════════════════════════════════
// ml_forecast — Probabilistic forecasting toolkit (Batch-6 foundation library)
// The "emit P(event), don't assert yes/no" pillar: an analytical volatility cone, an
// empirical session-open reach-probability counter, a robust (Theil-Sen) trendline, a
// pretrained logistic hazard head with its survival curve, total-variation distance for
// scoring a predicted distribution, and empirical-Bayes trust shrinkage.
// import Market_Logic_India/ml_forecast/1 as fc
//
// DESIGN Pine has no RNG, so the cone is ANALYTICAL (z·σ·√h), not a random Monte-Carlo —
// deterministic and non-repainting. The hazard head is a FORWARD PASS over weights you train
// OFFLINE (logistic regression on your labeled events) and pass frozen — the library does the
// inference, not the training. Stateful pieces (reach counters, particle swarms) keep their
// state HOST-side; this library owns the math.
//
// CONCEPT CREDIT Volatility cones, empirical reach / touch probability, Theil-Sen robust
// regression, discrete-time survival hazards, total-variation distance, and empirical-Bayes
// shrinkage are standard statistical techniques. Original, dependency-free Pine v6 packaging.
// ══════════════════════════════════════════════════════════════════════════════
//@version=6
library("ml_forecast", overlay = false)
// ── ANALYTICAL VOLATILITY CONE ──────────────────────────────────────────────────
// Deterministic forecast band from an anchor price: price · exp(±z·σ·√horizon). `sigmaPerBar`
// = per-bar return stdev as a FRACTION (e.g. ta.stdev(close/close[1]-1, N)). Lognormal, so it
// never goes negative and is correct for a %-scaled instrument. Returns [upper, lower].
export volCone(series float price, series float sigmaPerBar, simple int horizon, simple float z) =>
float s = sigmaPerBar * math.sqrt(math.max(horizon, 1))
float up = price * math.exp( z * s)
float dn = price * math.exp(-z * s)
[up, dn]
// ── EMPIRICAL SESSION REACH-PROBABILITY ─────────────────────────────────────────
// Count, over sessions, how often price reached each %-distance from the session open — the
// empirical P(touch) by distance (the counterpart to the cone). Host owns:
// var float[] hitsUp = array.new_float(K, 0.0) // K distance buckets, bucket k = (k+1)·step %
// var float sessN = 0.0
// Call reachRecord ONCE per COMPLETED session with that session's max favorable excursion in %
// (e.g. up = (sessionHigh/sessionOpen − 1)·100). Excursion is monotone, so a session reaching
// 1.0% also counts for every smaller bucket. Do the same with a second array for the downside.
export reachRecord(array<float> hits, series float maxExcursionPct, simple float stepPct) =>
int n = array.size(hits)
if not na(maxExcursionPct) and n > 0
for k = 0 to n - 1
if maxExcursionPct >= (k + 1) * stepPct
array.set(hits, k, array.get(hits, k) + 1.0)
// Reach probability (%) at bucket k = hits[k] / sessions. Wrap with your Wilson LB (ml_calib)
// for the honest floor on small samples.
export reachProb(array<float> hits, series int k, series float sessions) =>
(sessions > 0.0 and k >= 0 and k < array.size(hits)) ? array.get(hits, k) / sessions * 100.0 : na
// ── THEIL-SEN ROBUST TRENDLINE ──────────────────────────────────────────────────
// Median of pairwise slopes over the last `len` bars — outlier-resistant vs OLS (a wick or
// spike can't tilt it). Returns [slopePerBar, valueAtCurrentBar]. O(len²) — keep len modest.
export theilSen(series float src, simple int len) =>
float slope = na
float valNow = na
if bar_index >= len - 1 and len >= 2
array<float> slopes = array.new<float>()
for i = 0 to len - 2
for j = i + 1 to len - 1
float dy = nz(src[i]) - nz(src[j]) // newer − older
int dx = j - i // bars apart (>0)
slopes.push(dy / dx) // rise per bar going forward
slope := array.median(slopes)
array<float> ints = array.new<float>()
for i = 0 to len - 1
ints.push(nz(src[i]) + slope * i) // project each bar to the current bar (x=0)
valNow := array.median(ints)
[slope, valNow]
// ── PRETRAINED LOGISTIC HAZARD / EVENT-PROBABILITY HEAD ─────────────────────────
// Generic forward pass: P = sigmoid(bias + Σ wᵢ·fᵢ). Train the weights OFFLINE (logistic
// regression on labeled events); pass them frozen. Emits P(event this bar) from features —
// P(level breaks), P(trade fails), P(regime flips): the learned replacement for hand thresholds.
export logisticHazard(array<float> features, array<float> weights, simple float bias) =>
int n = math.min(array.size(features), array.size(weights))
float z = bias
if n > 0
for i = 0 to n - 1
z += nz(array.get(features, i)) * nz(array.get(weights, i))
1.0 / (1.0 + math.exp(-math.max(math.min(z, 30.0), -30.0)))
// Survival probability over k bars at constant per-bar hazard h: p0·(1−h)^k.
export survivalProb(series float p0, series float h, simple int k) =>
(not na(p0) and not na(h)) ? p0 * math.pow(math.max(1.0 - h, 0.0), k) : na
// Predicted remaining life (bars): where the survival curve from p0 at hazard h crosses 0.5
// (capped at kmax). A "how mature is this line/trade" readout.
export survLen(series float p0, series float h, simple int kmax) =>
int outv = kmax
float s = p0
bool found = false
for k = 1 to kmax
s := s * math.max(1.0 - h, 0.0)
if s < 0.5 and not found
outv := k
found := true
outv
// ── TOTAL-VARIATION DISTANCE (distribution error) ───────────────────────────────
// TVD = ½·Σ|pᵢ − qᵢ| over two same-length distributions (each should sum to 1). Bounded [0,1];
// 0 = identical. Score a predicted profile/histogram against the realized one.
export tvd(array<float> p, array<float> q) =>
int n = math.min(array.size(p), array.size(q))
float s = 0.0
if n > 0
for i = 0 to n - 1
s += math.abs(nz(array.get(p, i)) - nz(array.get(q, i)))
n > 0 ? 0.5 * s : na
// ── EMPIRICAL-BAYES TRUST SHRINKAGE ─────────────────────────────────────────────
// A forecast should be trusted in proportion to how well it has tracked. trust = clamp(cx/cc,
// 0, 1) from your running "how well past forecasts matched" accumulators. trustShrink blends:
// trust·forecast + (1−trust)·realized — a forecaster that EARNS its confidence (cf. Wilson).
export trustWeight(series float trustCx, series float trustCc) =>
(not na(trustCc) and trustCc != 0.0) ? math.max(0.0, math.min(trustCx / trustCc, 1.0)) : 0.0
export trustShrink(series float forecast, series float realized, series float trust) =>
float t = na(trust) ? 0.0 : math.max(0.0, math.min(trust, 1.0))
t * forecast + (1.0 - t) * realized
// ── demo output (library preview only) ──
[coneUp, coneDn] = volCone(close, ta.stdev(close / close[1] - 1.0, 20), 10, 1.0)
plot(coneUp, "1σ 10-bar cone upper (demo)", color = color.new(#6f9bd8, 0))