PINE LIBRARY
Aggiornato ml_robuststats

A small robust-statistics toolkit for building stable, outlier-resistant indicators.
Provides MAD-based robust z-scores (median/MAD, breakdown point 0.5), robust variance,
winsorization, percentile rank, multi-window boolean consensus, and inverse-variance
"precision" weighting (ridge-regularized, capped, normalized) for combining several
factors into one composite so quiet/reliable inputs get more weight and noisy ones fade.
Intended as a shared building block imported by other scripts, not as a standalone chart
indicator. MPL-2.0.
Library "ml_robuststats"
robMedian(src, len)
Parameters:
src (float)
len (simple int)
robMAD(src, len)
Parameters:
src (float)
len (simple int)
robZ(src, len)
Parameters:
src (float)
len (simple int)
robVar(src, len)
Parameters:
src (float)
len (simple int)
winsor(x, cap)
Parameters:
x (float)
cap (simple float)
pctRank(src, len)
Parameters:
src (float)
len (simple int)
consensus(sShort, sMid, sLong, mode)
Parameters:
sShort (bool)
sMid (bool)
sLong (bool)
mode (simple string)
precisionWeights(variances, wCap, ridgeFrac)
Parameters:
variances (array<float>)
wCap (simple float)
ridgeFrac (simple float)
dot(values, weights)
Parameters:
values (array<float>)
weights (array<float>)
Provides MAD-based robust z-scores (median/MAD, breakdown point 0.5), robust variance,
winsorization, percentile rank, multi-window boolean consensus, and inverse-variance
"precision" weighting (ridge-regularized, capped, normalized) for combining several
factors into one composite so quiet/reliable inputs get more weight and noisy ones fade.
Intended as a shared building block imported by other scripts, not as a standalone chart
indicator. MPL-2.0.
Library "ml_robuststats"
robMedian(src, len)
Parameters:
src (float)
len (simple int)
robMAD(src, len)
Parameters:
src (float)
len (simple int)
robZ(src, len)
Parameters:
src (float)
len (simple int)
robVar(src, len)
Parameters:
src (float)
len (simple int)
winsor(x, cap)
Parameters:
x (float)
cap (simple float)
pctRank(src, len)
Parameters:
src (float)
len (simple int)
consensus(sShort, sMid, sLong, mode)
Parameters:
sShort (bool)
sMid (bool)
sLong (bool)
mode (simple string)
precisionWeights(variances, wCap, ridgeFrac)
Parameters:
variances (array<float>)
wCap (simple float)
ridgeFrac (simple float)
dot(values, weights)
Parameters:
values (array<float>)
weights (array<float>)
Note di rilascio
ml_robuststats is a dependency-free library of robust-statistics primitives for Pine v6. It exists to fix a common weakness in indicator maths: the ordinary mean/standard-deviation z-score is dominated by a single fat-tailed bar — one gap, news spike, or expiry print stretches the σ scale and distorts every band and threshold built on it. The estimators here use the median and the median-absolute-deviation instead, which tolerate up to half the sample being outliers before they break down, so bands and scores keep a consistent meaning across regimes.Everything is exported for reuse via import. Each function takes a series float source (and a simple int window where relevant), so they slot in wherever you currently compute a z-score, a percentile, or a weighted composite.
What's inside
robMedian(src, len) — rolling median. The robust centre of a window.
robMAD(src, len) — rolling median absolute deviation. The robust spread of a window.
robZ(src, len) — robust z-score: (x − median) / (1.4826 × MAD). The 1.4826 factor makes MAD ≈ σ under Gaussian data, so a robust z reads on the same scale as a classic z but shrugs off outliers. Returns 0 when the window has essentially no spread. This is the drop-in replacement for a mean/stdev z-score.
robVar(src, len) — robust variance, (1.4826 × MAD)². Useful as the per-factor variance input to precision weighting.
winsor(x, cap) — clamp a value to ±cap. A second layer of outlier control to apply before compositing several factors.
pctRank(src, len) — percentile rank 0–100. Self-calibrating strength that needs no fixed threshold; naturally bounded and outlier-tolerant.
consensus(sShort, sMid, sLong, mode) — multi-window boolean agreement across a short/medium/long signal, with mode "Any" | "Majority" | "All". Turns three single-window reads into one agreement gate.
precisionWeights(variances, wCap, ridgeFrac) — inverse-variance (precision) weights from an array of per-factor variances, ridge-regularized, capped per factor, and normalized to sum to 1. Quiet, reliable factors earn more weight; noisy ones fade — a principled replacement for hand-set weights. wCap prevents any single factor from dominating; ridgeFrac stabilizes the weights when a variance is near zero.
dot(values, weights) — safe dot product of a values array with a weights array (handles size mismatch and na), for turning factors + precision weights into one composite score.
How to use
Import the library, then call what you need. A robust z on any series:
//version=6
indicator("Example — robust z", overlay = false)
import Market_Logic_India/ml_robuststats/1 as rs
len = input.int(100, "Window")
z = rs.robZ(close - ta.vwap(hlc3), len) // robust vs (x - mean)/stdev
plot(z, "robZ", color = color.new(#5b9cf6, 0))
hline(0)
A precision-weighted composite of several factors:
import Market_Logic_India/ml_robuststats/1 as rs
f1 = rs.robZ(factorA, 100)
f2 = rs.robZ(factorB, 100)
f3 = rs.robZ(factorC, 100)
var array<float> vals = array.new<float>(3)
array.set(vals, 0, f1), array.set(vals, 1, f2), array.set(vals, 2, f3)
var array<float> vars = array.new<float>(3)
array.set(vars, 0, rs.robVar(factorA, 100))
array.set(vars, 1, rs.robVar(factorB, 100))
array.set(vars, 2, rs.robVar(factorC, 100))
w = rs.precisionWeights(vars, 0.6, 0.10) // cap 0.6, ridge 10%
composite = rs.dot(vals, w)
plot(composite, "composite")
Notes
Non-repainting: all estimators use only closed historical bars — no request.*, no future references. The last bar updates intrabar and settles on close.
Warm-up: the rolling estimators need len bars of history before they are meaningful; treat the start of history as warm-up.
Types: pass simple int windows and simple float caps (plain inputs or constants), not series values. consensus takes a simple string mode.
precisionWeights and dot operate on array<float> — build the arrays each bar (or as var arrays you overwrite).
Concept credits
The median / MAD robust z-score (with the 1.4826 consistency constant), winsorization, inverse-variance precision weighting, and percentile-rank strength are standard robust-statistics and meta-analysis techniques. This library is an original Pine v6 packaging of those public methods for reuse; it is not affiliated with, nor endorsed by, any originator.
License
Mozilla Public License 2.0 — as required for TradingView libraries (open source). Free to import and build on.
Note di rilascio
v3Added:
pctCap(src, pct, len)
Parameters:
src (float)
pct (simple float)
len (simple int)
Libreria Pine
Nello spirito di TradingView, l'autore ha pubblicato questo codice Pine come libreria open source affinché altri programmatori della nostra community possano riutilizzarlo. Complimenti all'autore! È possibile utilizzare questa libreria privatamente o in altre pubblicazioni open source, ma il riutilizzo di questo codice nelle pubblicazioni è soggetto al Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Libreria Pine
Nello spirito di TradingView, l'autore ha pubblicato questo codice Pine come libreria open source affinché altri programmatori della nostra community possano riutilizzarlo. Complimenti all'autore! È possibile utilizzare questa libreria privatamente o in altre pubblicazioni open source, ma il riutilizzo di questo codice nelle pubblicazioni è soggetto al Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.