Indicator · Pine Script v6 · Own pane

Normal Distribution CDF (NORMDIST)

by mihakralj

Normal Distribution CDF (NORMDIST) calculates the cumulative distribution function for a normalized price series in a separate indicator pane.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code80
Settings4inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

80 lines of Pine Script v6 from lib/numerics/normdist/normdist.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

normdist.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Normal Distribution CDF (NORMDIST)", "NORMDIST", overlay=false, precision=6)

//@function Computes Normal Distribution CDF for a normalized price series
//@param source Series to transform
//@param period Lookback period for z-score normalization
//@param mu Mean parameter (0.0 for standard normal after z-score)
//@param sigma Standard deviation parameter (1.0 for standard normal after z-score)
//@returns CDF value in [0,1]: Φ(z) = 0.5 × (1 + erf(z / √2))
//@optimized O(period) per bar for mean/variance scan; CDF itself is O(1)
normdist(series float source, simple int period, simple float mu, simple float sigma) =>
    if period <= 0
        runtime.error("Period must be greater than 0")
    if sigma <= 0.0
        runtime.error("Sigma must be greater than 0")

    // Compute rolling mean and standard deviation over lookback
    float sum = 0.0
    float sumSq = 0.0
    int count = 0
    for i = 0 to period - 1
        float v = source[i]
        if not na(v)
            sum += v
            sumSq += v * v
            count += 1

    float result = 0.5
    if count >= 2
        float mean = sum / count
        float variance = (sumSq / count) - (mean * mean)
        float stddev = variance > 0.0 ? math.sqrt(variance) : 0.0

        // Z-score: normalize source relative to its own rolling distribution
        float z = stddev > 0.0 ? (source - mean) / stddev : 0.0

        // Apply user-specified mu/sigma shift: z_final = (z - mu) / sigma
        float z_final = (z - mu) / sigma

        // Approximate erf via Abramowitz & Stegun (max error < 1.5e-7)
        // erf(x) = 1 - (a1*t + a2*t^2 + a3*t^3) * exp(-x^2)
        // where t = 1 / (1 + 0.47047 * |x|)
        float x = z_final / math.sqrt(2.0)
        float ax = math.abs(x)
        float t = 1.0 / (1.0 + 0.47047 * ax)
        float t2 = t * t
        float t3 = t2 * t

        float a1 = 0.3480242
        float a2 = -0.0958798
        float a3 = 0.7478556

        float erfApprox = 1.0 - (a1 * t + a2 * t2 + a3 * t3) * math.exp(-(ax * ax))
        float erf = x >= 0.0 ? erfApprox : -erfApprox

        // CDF: Φ(z) = 0.5 * (1 + erf(z / sqrt(2)))
        result := 0.5 * (1.0 + erf)

    result

// ---------- Main loop ----------

// Inputs
i_source = input.source(close, "Source")
i_period = input.int(50, "Lookback Period", minval=2, maxval=5000, tooltip="Rolling window for z-score normalization")
i_mu     = input.float(0.0, "Mu (μ)", step=0.1, tooltip="Mean shift parameter (0 = standard normal)")
i_sigma  = input.float(1.0, "Sigma (σ)", minval=0.01, step=0.1, tooltip="Scale parameter (1 = standard normal)")

// Calculation
float result = normdist(i_source, i_period, i_mu, i_sigma)

// Plot
plot(result, "NORMDIST", color=color.yellow, linewidth=2)
hline(0.5, "Midline", color=color.gray, linestyle=hline.style_dotted)
hline(0.975, "Upper 2σ", color=color.red, linestyle=hline.style_dashed)
hline(0.025, "Lower 2σ", color=color.green, linestyle=hline.style_dashed)
hline(0.841, "Upper 1σ", color=color.orange, linestyle=hline.style_dashed)
hline(0.159, "Lower 1σ", color=color.teal, linestyle=hline.style_dashed)

Overview

Normal Distribution CDF (NORMDIST) standardizes price values using a rolling mean and standard deviation over a customizable lookback window, then scales the z-score via mean shift (mu) and scale (sigma) inputs. Using an error function approximation, it outputs probability values between 0 and 1 alongside reference lines for 1-sigma and 2-sigma statistical levels.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosei_source
Lookback Periodint50i_period
Mu (μ)float0.0i_mu
Sigma (σ)float1.0i_sigma
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

This indicator calculates standardized z-scores of price data across four different lookback periods (6, 14, 26, and 100). Standardizing data subtracts the moving average from the price and divides by the standard deviation. It applies a Double Exponential Mov

Indicator v5 Mean reversionVolatility & bands
114 stars

This indicator implements a dual-direction variation of the Williams Vix Fix oscillator in a separate pane. It normalizes price data using min-max scaling to compute both upward and downward synthetic volatility metrics across two selectable calculation modes

Indicator v4 Volatility & bandsMean reversion
Updated 1 year ago · None stated GitHub repository of Combo Williams Vix Fix (Twin)
47 stars

This indicator applies the hyperbolic tangent to a chosen source series and plots the result in a separate pane. It centers the transform on a 200-bar simple moving average of that source, multiplies the deviation by a steepness factor, and maps the output int

Indicator v6 Moving averagesMean reversion
Updated 8 months ago · MIT GitHub repository of Hyperbolic Tangent (TANH)

AutoCorrelation Function

by Anderson-ALGO
9 stars

This indicator calculates sample autocorrelation across multiple lag intervals for a selected price series. It computes correlation values over a user-specified lookback period using raw prices, log returns, absolute log returns, or squared log returns. Plotte

Indicator v4 TrendMean reversion
Updated 5 years ago · None stated GitHub repository of AutoCorrelation Function

Calculates a composite carry and decay oscillator fusing impulse-autocorrelation half-life, a Hurst exponent approximation, path efficiency, and range expansion ratios. It evaluates whether an impulse is likely to persist or mean-revert, plotting the oscillato

Indicator v6 TrendOscillators & momentum
Updated yesterday · MIT GitHub repository of Market Memory & Decay Oscillator [WavesUnchained]

This indicator builds a channel from a Hull moving average of the source and an ATR scaled by a band multiplier, then normalizes price inside that channel into a 0 to 100 oscillator. It smooths the result with a weighted moving average and plots the line in a

Indicator v6 Mean reversionVolatility & bands
Updated 3 months ago · None stated GitHub repository of Radiant Mean Reversion Channels [Pineify]

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers