PINE LIBRARY
Aggiornato CyberNumLib

# CyberNumLib v5
CyberNumLib provides stateless numerical primitives for Pine Script traders who need advanced statistical calculations, robust normalization methods, and mathematical functions not available in TradingView's native library.
## What it does
NumLib delivers 56 pure functions covering five categories: mathematical polyfills (hyperbolic functions, normal distribution CDF/inverse, error function), advanced smoothing filters (Ehlers Super Smoother, Butterworth, Savitzky-Golay), robust statistics (median-MAD, IQR-based scaling, Winsorized bounds), normalization methods (z-scores, percentile ranks, min-max scaling), and correlation analysis (Pearson, Spearman, Kendall, Hurst exponent). Traders use these functions to build custom indicators requiring statistical rigor beyond Pine's built-in ta.* namespace—for example, calculating confidence intervals from normal quantiles, applying outlier-resistant smoothing to noisy price data, or measuring non-linear correlation between assets.
The library outputs standardized numerical values ready for downstream indicator logic: z-scores for mean-reversion signals, normalized coefficients for ML feature engineering, correlation matrices for multi-asset analysis, and smoothed series for trend detection. All functions are stateless (no internal state variables), making them composable and predictable across different timeframes and symbols.
## How it works
NumLib implements well-documented statistical algorithms with explicit citations. The normal CDF uses the Abramowitz & Stegun 26.2.17 polynomial approximation (max error ~7e-8), while the inverse normal CDF employs the Beasley-Springer-Moro rational approximation for converting probabilities to z-scores with ~1e-10 precision—critical for quantile-based risk calculations. Hyperbolic tangent (tanh) is computed via the numerically stable identity `(e^(2x) - 1) / (e^(2x) + 1)` with argument clamping to ±20 to prevent math.exp overflow.
Smoothing filters follow Ehlers' DSP methodology: the Super Smoother is a 2-pole IIR Butterworth-equivalent with coefficients derived from `exp(-1.414π/len)`, providing lag reduction vs simple moving averages while suppressing high-frequency noise. The Savitzky-Golay filter uses fixed polynomial coefficients (order 2, length 13) for edge-preserving smoothing without phase shift.
Robust statistics leverage percentile-based methods resistant to outliers. The median-MAD estimator computes scale as `(Q75 - Q25) / 0.7413`, where 0.7413 is the IQR-to-standard-deviation conversion factor for normal distributions. Correlation functions implement textbook formulas: Pearson via covariance normalization, Spearman via rank transformation, Kendall via concordant-discordant pair counting. The Hurst exponent uses rescaled range (R/S) analysis to detect mean-reversion (H < 0.5) vs trending (H > 0.5) regimes.
## Why this is original
NumLib fills critical gaps in Pine Script's native math library. TradingView provides no hyperbolic functions (tanh, sinh, cosh), no normal distribution quantile functions, no Savitzky-Golay smoothing, and no robust statistics beyond basic percentiles. Existing public libraries either bundle these functions with unrelated indicator logic (mixing calculation with rendering) or implement simplified versions without numerical stability guards.
This library is the only TradingView publication offering:
- **Numerically stable implementations**: tanh with overflow clamping, normal CDF with Abramowitz-Stegun precision, inverse CDF with Beasley-Springer-Moro accuracy
- **Robust statistics suite**: median-MAD, IQR normalization, Winsorization—essential for outlier-resistant indicators in volatile markets
- **Ehlers DSP filters**: Super Smoother and Butterworth implementations with exact coefficient formulas from Ehlers' published work
- **Comprehensive correlation toolkit**: Pearson, Spearman, Kendall, plus Hurst exponent for regime detection—all in one dependency-free library
No other Pine library combines these four categories with explicit algorithm citations and edge-case handling (NA guards, zero-division checks, warmup period validation).
## How to use it
```pine
//version=6
indicator("CyberNumLib Demo", overlay=false)
import cybermediaboy/CyberNumLib/5 as N
// Example 1: Z-score with robust median-MAD scaling
[med, scale, _, _, z_robust] = N.f_basis_median_mad(close, 50)
plot(z_robust, "Robust Z-Score", color.blue)
// Example 2: Smooth price with Ehlers Super Smoother
smooth_close = N.f_supersmoother(close, 20)
plot(smooth_close, "Super Smooth", color.orange)
// Example 3: Calculate correlation between two assets
// (Assumes you have arrays x_data and y_data populated)
var x_arr = array.new<float>(50)
var y_arr = array.new<float>(50)
array.push(x_arr, close)
array.push(y_arr, volume)
if array.size(x_arr) > 50
array.shift(x_arr)
array.shift(y_arr)
corr_pearson = N.f_pearson(x_arr, y_arr, 50)
plot(corr_pearson, "Pearson Correlation", color.green)
// Example 4: Convert confidence level to z-score
conf_95 = 0.95
z_95 = N.f_norm_inv((1.0 + conf_95) / 2.0) // Returns ~1.96
plot(z_95, "95% Confidence Z", color.red)
```
## Inputs, outputs, expected behavior
**Smoothing functions** (`f_supersmoother`, `f_buttersmooth`, `f_savgol_2_13`):
- **Inputs**: `src` (float, typically close/high/low), `len` (int, window size 5-100 typical)
- **Outputs**: Smoothed float value, range matches input series
- **Edge cases**: Returns input value on first bar (no warmup), handles NA via nz()
**Statistical functions** (`f_zscore`, `f_basis_median_mad`, `f_percentile_bands`):
- **Inputs**: `src` (float series), `len` (int, minimum 10 for stability)
- **Outputs**: Z-scores (unbounded float), percentiles (price units), scale factors (positive float)
- **Edge cases**: Returns 0.0 for z-score if stdev = 0, returns NA for insufficient data (bar_index < len)
**Correlation functions** (`f_pearson`, `f_spearman`, `f_kendall`, `f_hurst_rs`):
- **Inputs**: `array<float>` (length ≥ 10), `len` (int, sample size)
- **Outputs**: Correlation coefficient [-1, 1] for Pearson/Spearman/Kendall, Hurst [0, 1]
- **Edge cases**: Returns 0.0 if array size < len, handles NA elements via filtering
**Math polyfills** (`f_tanh`, `f_norm_cdf`, `f_norm_inv`, `f_erf`):
- **Inputs**: Float values (unbounded for tanh/erf, [0,1] for norm_inv, any for norm_cdf)
- **Outputs**: Bounded floats (tanh: [-1,1], sigmoid: [0,1], norm_cdf: [0,1], norm_inv: unbounded)
- **Edge cases**: Clamps extreme inputs to prevent overflow (tanh at ±20, norm_inv at [1e-10, 1-1e-10])
**Normalization functions** (`f_normalize`, `f_iqr_normalize`, `f_tanh_norm`):
- **Inputs**: `value` (float), `minval/maxval` (float bounds) or `len` (int window)
- **Outputs**: Normalized float in [0,1] for f_normalize, [-1,1] for tanh-based methods
- **Edge cases**: Returns 0.0 if range is zero, handles NA inputs gracefully
## Limitations
1. **No dynamic array sizing**: Correlation functions require pre-allocated arrays of fixed size. If your data stream length varies, you must manage array resizing externally (e.g., via array.push + array.shift pattern). The library does not auto-resize or buffer data.
2. **Warmup period required**: Statistical functions (z-score, percentile bands, correlation) return unreliable values during the first `len` bars. Indicators using NumLib should display a warmup warning (e.g., "Insufficient data: need 50 bars") or gate signals until `bar_index >= len`.
3. **Precision limits on extreme inputs**: Math polyfills use polynomial approximations with documented error bounds (e.g., normal CDF ~7e-8, erf ~1.5e-7). For applications requiring higher precision (e.g., options pricing), these approximations may be insufficient. Extreme inputs (|x| > 20 for tanh, p < 1e-10 for norm_inv) are clamped to prevent overflow, which can distort tail probabilities.
4. **Correlation functions assume stationarity**: Pearson, Spearman, and Kendall correlations are computed over rolling windows without detrending. In strongly trending markets, these measures may overstate correlation due to common trend components. For non-stationary data, consider differencing the series first or using Hurst exponent to detect regime changes.
5. **No built-in significance testing**: The library returns raw correlation coefficients without p-values or confidence intervals. Traders must implement their own significance tests (e.g., t-test for Pearson correlation) or use rule-of-thumb thresholds (|r| > 0.7 for strong correlation).
6. **Single-threaded execution**: All functions execute sequentially on each bar. For indicators calling multiple NumLib functions per bar (e.g., computing 10 correlations), execution time may exceed TradingView's script timeout on lower timeframes with large datasets. Optimize by caching results or reducing calculation frequency.
CyberNumLib provides stateless numerical primitives for Pine Script traders who need advanced statistical calculations, robust normalization methods, and mathematical functions not available in TradingView's native library.
## What it does
NumLib delivers 56 pure functions covering five categories: mathematical polyfills (hyperbolic functions, normal distribution CDF/inverse, error function), advanced smoothing filters (Ehlers Super Smoother, Butterworth, Savitzky-Golay), robust statistics (median-MAD, IQR-based scaling, Winsorized bounds), normalization methods (z-scores, percentile ranks, min-max scaling), and correlation analysis (Pearson, Spearman, Kendall, Hurst exponent). Traders use these functions to build custom indicators requiring statistical rigor beyond Pine's built-in ta.* namespace—for example, calculating confidence intervals from normal quantiles, applying outlier-resistant smoothing to noisy price data, or measuring non-linear correlation between assets.
The library outputs standardized numerical values ready for downstream indicator logic: z-scores for mean-reversion signals, normalized coefficients for ML feature engineering, correlation matrices for multi-asset analysis, and smoothed series for trend detection. All functions are stateless (no internal state variables), making them composable and predictable across different timeframes and symbols.
## How it works
NumLib implements well-documented statistical algorithms with explicit citations. The normal CDF uses the Abramowitz & Stegun 26.2.17 polynomial approximation (max error ~7e-8), while the inverse normal CDF employs the Beasley-Springer-Moro rational approximation for converting probabilities to z-scores with ~1e-10 precision—critical for quantile-based risk calculations. Hyperbolic tangent (tanh) is computed via the numerically stable identity `(e^(2x) - 1) / (e^(2x) + 1)` with argument clamping to ±20 to prevent math.exp overflow.
Smoothing filters follow Ehlers' DSP methodology: the Super Smoother is a 2-pole IIR Butterworth-equivalent with coefficients derived from `exp(-1.414π/len)`, providing lag reduction vs simple moving averages while suppressing high-frequency noise. The Savitzky-Golay filter uses fixed polynomial coefficients (order 2, length 13) for edge-preserving smoothing without phase shift.
Robust statistics leverage percentile-based methods resistant to outliers. The median-MAD estimator computes scale as `(Q75 - Q25) / 0.7413`, where 0.7413 is the IQR-to-standard-deviation conversion factor for normal distributions. Correlation functions implement textbook formulas: Pearson via covariance normalization, Spearman via rank transformation, Kendall via concordant-discordant pair counting. The Hurst exponent uses rescaled range (R/S) analysis to detect mean-reversion (H < 0.5) vs trending (H > 0.5) regimes.
## Why this is original
NumLib fills critical gaps in Pine Script's native math library. TradingView provides no hyperbolic functions (tanh, sinh, cosh), no normal distribution quantile functions, no Savitzky-Golay smoothing, and no robust statistics beyond basic percentiles. Existing public libraries either bundle these functions with unrelated indicator logic (mixing calculation with rendering) or implement simplified versions without numerical stability guards.
This library is the only TradingView publication offering:
- **Numerically stable implementations**: tanh with overflow clamping, normal CDF with Abramowitz-Stegun precision, inverse CDF with Beasley-Springer-Moro accuracy
- **Robust statistics suite**: median-MAD, IQR normalization, Winsorization—essential for outlier-resistant indicators in volatile markets
- **Ehlers DSP filters**: Super Smoother and Butterworth implementations with exact coefficient formulas from Ehlers' published work
- **Comprehensive correlation toolkit**: Pearson, Spearman, Kendall, plus Hurst exponent for regime detection—all in one dependency-free library
No other Pine library combines these four categories with explicit algorithm citations and edge-case handling (NA guards, zero-division checks, warmup period validation).
## How to use it
```pine
//version=6
indicator("CyberNumLib Demo", overlay=false)
import cybermediaboy/CyberNumLib/5 as N
// Example 1: Z-score with robust median-MAD scaling
[med, scale, _, _, z_robust] = N.f_basis_median_mad(close, 50)
plot(z_robust, "Robust Z-Score", color.blue)
// Example 2: Smooth price with Ehlers Super Smoother
smooth_close = N.f_supersmoother(close, 20)
plot(smooth_close, "Super Smooth", color.orange)
// Example 3: Calculate correlation between two assets
// (Assumes you have arrays x_data and y_data populated)
var x_arr = array.new<float>(50)
var y_arr = array.new<float>(50)
array.push(x_arr, close)
array.push(y_arr, volume)
if array.size(x_arr) > 50
array.shift(x_arr)
array.shift(y_arr)
corr_pearson = N.f_pearson(x_arr, y_arr, 50)
plot(corr_pearson, "Pearson Correlation", color.green)
// Example 4: Convert confidence level to z-score
conf_95 = 0.95
z_95 = N.f_norm_inv((1.0 + conf_95) / 2.0) // Returns ~1.96
plot(z_95, "95% Confidence Z", color.red)
```
## Inputs, outputs, expected behavior
**Smoothing functions** (`f_supersmoother`, `f_buttersmooth`, `f_savgol_2_13`):
- **Inputs**: `src` (float, typically close/high/low), `len` (int, window size 5-100 typical)
- **Outputs**: Smoothed float value, range matches input series
- **Edge cases**: Returns input value on first bar (no warmup), handles NA via nz()
**Statistical functions** (`f_zscore`, `f_basis_median_mad`, `f_percentile_bands`):
- **Inputs**: `src` (float series), `len` (int, minimum 10 for stability)
- **Outputs**: Z-scores (unbounded float), percentiles (price units), scale factors (positive float)
- **Edge cases**: Returns 0.0 for z-score if stdev = 0, returns NA for insufficient data (bar_index < len)
**Correlation functions** (`f_pearson`, `f_spearman`, `f_kendall`, `f_hurst_rs`):
- **Inputs**: `array<float>` (length ≥ 10), `len` (int, sample size)
- **Outputs**: Correlation coefficient [-1, 1] for Pearson/Spearman/Kendall, Hurst [0, 1]
- **Edge cases**: Returns 0.0 if array size < len, handles NA elements via filtering
**Math polyfills** (`f_tanh`, `f_norm_cdf`, `f_norm_inv`, `f_erf`):
- **Inputs**: Float values (unbounded for tanh/erf, [0,1] for norm_inv, any for norm_cdf)
- **Outputs**: Bounded floats (tanh: [-1,1], sigmoid: [0,1], norm_cdf: [0,1], norm_inv: unbounded)
- **Edge cases**: Clamps extreme inputs to prevent overflow (tanh at ±20, norm_inv at [1e-10, 1-1e-10])
**Normalization functions** (`f_normalize`, `f_iqr_normalize`, `f_tanh_norm`):
- **Inputs**: `value` (float), `minval/maxval` (float bounds) or `len` (int window)
- **Outputs**: Normalized float in [0,1] for f_normalize, [-1,1] for tanh-based methods
- **Edge cases**: Returns 0.0 if range is zero, handles NA inputs gracefully
## Limitations
1. **No dynamic array sizing**: Correlation functions require pre-allocated arrays of fixed size. If your data stream length varies, you must manage array resizing externally (e.g., via array.push + array.shift pattern). The library does not auto-resize or buffer data.
2. **Warmup period required**: Statistical functions (z-score, percentile bands, correlation) return unreliable values during the first `len` bars. Indicators using NumLib should display a warmup warning (e.g., "Insufficient data: need 50 bars") or gate signals until `bar_index >= len`.
3. **Precision limits on extreme inputs**: Math polyfills use polynomial approximations with documented error bounds (e.g., normal CDF ~7e-8, erf ~1.5e-7). For applications requiring higher precision (e.g., options pricing), these approximations may be insufficient. Extreme inputs (|x| > 20 for tanh, p < 1e-10 for norm_inv) are clamped to prevent overflow, which can distort tail probabilities.
4. **Correlation functions assume stationarity**: Pearson, Spearman, and Kendall correlations are computed over rolling windows without detrending. In strongly trending markets, these measures may overstate correlation due to common trend components. For non-stationary data, consider differencing the series first or using Hurst exponent to detect regime changes.
5. **No built-in significance testing**: The library returns raw correlation coefficients without p-values or confidence intervals. Traders must implement their own significance tests (e.g., t-test for Pearson correlation) or use rule-of-thumb thresholds (|r| > 0.7 for strong correlation).
6. **Single-threaded execution**: All functions execute sequentially on each bar. For indicators calling multiple NumLib functions per bar (e.g., computing 10 correlations), execution time may exceed TradingView's script timeout on lower timeframes with large datasets. Optimize by caching results or reducing calculation frequency.
Note di rilascio
v2Added:
f_supersmoother_seeded(src, len, zero_seed)
Parameters:
src (float)
len (int)
zero_seed (bool)
f_relative_ema(src, len, floor_value, preserve_na)
Parameters:
src (float)
len (simple int)
floor_value (float)
preserve_na (bool)
f_zscore_mean_mad(src, len, consistency, floor_value)
Parameters:
src (float)
len (simple int)
consistency (float)
floor_value (float)
f_parse_float_at(values, idx, fallback)
Parameters:
values (array<string>)
idx (int)
fallback (float)
f_matrix_diag_mean(values, fallback)
Parameters:
values (matrix<float>)
fallback (float)
Note di rilascio
v3Added:
f_nw_weight(d1, d2, d3, i, factor_bw, time_bw)
NW Gaussian factor-distance and time-decay weight
Parameters:
d1 (float)
d2 (float)
d3 (float)
i (int)
factor_bw (float)
time_bw (float)
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.