Indicator · Pine Script v6 · Own pane

Standardization (Z-score)

by mihakralj

Calculates the rolling Z-score of an input price series over a specified lookback window.

View on GitHub

GitHub stars47on the repository
Pine versionv6current
Lines of code61
Settings2inputs
LicenceMIT
Last update8 months ago28 Feb 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

61 lines of Pine Script v6 from indicators/numerics/standardize.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

standardize.pine
// The MIT License (MIT)
// © mihakralj
//@version=6
indicator("Standardization (Z-score)", "STANDARDIZE", overlay=false, precision=4)

//@function Calculates the Z-score of a series over a lookback period.
//@param src series float Input data series.
//@param len simple int Lookback period for calculating mean and standard deviation (must be > 1 for sample stdev).
//@returns series float The Z-score of the current data point, or na if issues like insufficient data or zero stdev for a non-mean current value.
standardize(series float src, simple int len) =>
    if len <= 1
        float(na)
    var S1 = 0.0
    var S2 = 0.0
    var N = 0
    var float[] window_data_vals = array.new_float(0)
    var bool[]  window_data_is_na = array.new_bool(0)
    float x_new = src[0]
    bool x_new_is_na = na(x_new)
    if array.size(window_data_vals) == len
        float x_old_val = array.get(window_data_vals, 0)
        bool x_old_was_na = array.get(window_data_is_na, 0)
        array.shift(window_data_vals)
        array.shift(window_data_is_na)
        if not x_old_was_na
            S1 -= x_old_val
            S2 -= x_old_val * x_old_val
            N -= 1
    array.push(window_data_vals, x_new_is_na ? 0.0 : x_new)
    array.push(window_data_is_na, x_new_is_na)
    if not x_new_is_na
        S1 += x_new
        S2 += x_new * x_new
        N += 1
    float z_score = na
    if N < 2
        z_score := na
    else
        float mean_val = S1 / N
        float variance_pop = (S2 / N) - (mean_val * mean_val)
        variance_pop := variance_pop < 1e-10 ? 0.0 : variance_pop
        float variance_sample = variance_pop * N / (N - 1)
        float stdev_val = math.sqrt(variance_sample)
        if x_new_is_na
            z_score := na
        else if stdev_val > 1e-10
            z_score := (x_new - mean_val) / stdev_val
        else
            z_score := (math.abs(x_new - mean_val) < 1e-10) ? 0.0 : na
    z_score

// Inputs
i_source = input.source(close, title="Source")
i_length = input.int(20, title="Lookback Period", minval=2, tooltip="Period for mean and standard deviation. Must be at least 2 for stdev.")

// Calculation
z_score_value = standardize(i_source, i_length) // Renamed for clarity

// Plot
plot(z_score_value, "Z-score", color=color.yellow, linewidth=2)
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed)

Overview

Standardization (Z-score) uses a sliding window array to maintain rolling sums and calculate the sample mean and sample standard deviation incrementally, accounting for missing values. The resulting normalized value is plotted as a line alongside a dashed zero baseline in a separate pane. Configurable input settings allow traders to customize the data source and lookback period.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Mean reversion, Oscillators & momentum

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

pinescriptpinescript-indicatorstechnical-analysistradingview-indicators

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosei_source
Lookback Periodint20i_length
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 calculates normalized percentage bounds around price highs and lows to anticipate local trend reversals. It oscillates within a fixed -1 to 1 channel and plots two boundary tracking curves alongside a background Karobein oscillator histogram for

Indicator v4 Mean reversionOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Mean Reversion Indicator
99 stars

This indicator calculates the statistical autocorrelation coefficient of an input series over a user-defined lookback window at a specified lag. It tracks values using an internal circular buffer, computes sample mean, variance, and autocovariance, and normali

Indicator v6 TrendMean reversion
Updated 4 weeks ago · Apache-2.0 GitHub repository of Autocorrelation Function (ACF)

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 plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]

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