TradingView price statistics

Price Z-score indicator: measure deviation from a rolling mean

A price Z-score indicator measures how far the current price is from its rolling average in standard-deviation units: Z = (price − mean) / standard deviation. A positive value means price is above that mean; it does not establish a sell signal or a reversal probability. This page uses closing prices and a window that includes the current bar. It covers price statistics, not the Altman Z-Score used in company financial analysis.

See the decision guide

Define the price, window, and denominator

For N consecutive chart bars, let x be each closing price, m their arithmetic mean, and Q the sum of (x − m)². The population convention describes the selected window using divisor N. The sample convention uses N − 1. Both are usable conventions for a descriptive rolling indicator, but switching between them changes the score. Require N ≥ 2.

  • With the same nonconstant window, sample Z = population Z × sqrt((N − 1) / N). The larger sample denominator reduces the absolute score.
  • A price Z-score and a return Z-score answer different questions. Replacing closes with percentage changes measures an unusual return, not distance of the price level from its average.
  • Including the current close lets that observation move both the mean and the deviation. Comparing it with the previous N closes instead creates a different, prior-window score. Label that change explicitly.
QuantityPopulation conventionSample convention
Mean mSum of closes / NSame mean
VarianceQ / NQ / (N − 1)
Standard deviationsqrt(Q / N)sqrt(Q / (N − 1))
Current price score(current close − m) / population SD(current close − m) / sample SD

Reproduce a five-close calculation

Assume hypothetical completed closes of 98, 99, 100, 101, and 102 in the same price units. Their mean is 100. Squared deviations are 4, 1, 0, 1, and 4, so Q = 10. The current close is 102 and its deviation is +2. These small windows demonstrate arithmetic, not recommended trading settings.

  • Keep full precision internally and round only the display. Rounding standard deviation before division can change a threshold decision.
  • Adding a constant to every price, or multiplying every price by the same positive factor, leaves Z unchanged. A changing adjustment convention within the series can still alter it.
  • For five equal closes of 100, Q and standard deviation are zero. The expression is 0/0, so this page returns unavailable rather than fabricating a neutral score of zero.
CalculationPopulationSample
Variance10 / 5 = 210 / 4 = 2.5
Standard deviation1.4142141.581139
Z at close 1022 / 1.414214 = 1.4142142 / 1.581139 = 1.264911

Compare a continuing trend with a move back toward the mean

Start both hypothetical paths with 98, 99, 100, 101, 102 and use the population convention with N = 5. One path then closes at 103; the other at 100. The oldest close drops out when the new close enters. A positive score at the shared starting point does not distinguish which path comes next.

  • If price keeps rising by one unit per bar, the five-bar mean rises by one too. Z stays near +1.414214 even as price keeps making new highs. Selling solely because Z is positive fights that constructed trend.
  • In the second path, price declines while the rolling mean also changes. A move of Z toward zero can also occur because the mean catches up or standard deviation expands; it need not mean price returned to an earlier fixed level.
  • To evaluate a mean-reversion rule, define the entry crossing, exit, maximum holding time, stop, and execution costs. Compare separate trending and ranging periods, then test untouched data. These two paths are calculation examples, not backtest evidence.
Path and latest windowMeanSDLatest Z
Shared start: 98, 99, 100, 101, 1021001.414214+1.414214
Trend continues: 99, 100, 101, 102, 1031011.414214+1.414214
Price falls back: 99, 100, 101, 102, 100100.41.019804-0.392232

Choose the window without importing a probability claim

N counts chart bars, so 20 bars on a five-minute chart and 20 daily bars measure different histories. Compare candidate windows while holding the symbol, feed, session, source, and completed timestamp fixed. Short windows replace old observations quickly; longer windows retain more past price levels and may span several market conditions. There is no universally best length.

  • A current-inclusive population score has a finite-sample bound: |Z| ≤ sqrt(N − 1). For the sample convention the bound is (N − 1)/sqrt(N). This follows because all N centered deviations sum to zero; it is an algebraic constraint, not a distribution assumption.
  • At N = 5, closes 100, 100, 100, 100, 110 give mean 102, population SD 4, and Z = +2 exactly. A strict crossing above +2 cannot occur mathematically in that five-point population definition. A touch at +2 and a crossing above +2 are different rules; floating-point noise near the bound is not evidence of a valid excess.
  • For an exact linear rise, population Z at the newest point is sqrt(3 × (N − 1)/(N + 1)). Thus N = 5 gives 1.414214 and N = 20 gives 1.647509, despite the same steady trend mechanism.
  • Z = +2 does not mean a 97.7% probability of falling, and ±2 does not establish a 95% price forecast interval. Standardizing observations does not make their distribution normal or their rolling windows independent. NIST cautions that outlier labels depend on the distribution and that small-sample Z-scores can mislead.

Inspect a Pine Script v6 price Z-score

This indicator uses an arithmetic mean, an explicit standard-deviation convention, and the latest N consecutive chart closes. It rejects a window containing a missing close. The displayed score and alerts wait for chart-bar confirmation; no other timeframe is requested. The default N = 20 and threshold 2 are demonstration inputs.

  • In TradingView, use standard candles and compare the Data Window mean, standard deviation, and Z on the same completed bar. Check N and the population checkbox before comparing a different public script.
  • The first valid Z needs N consecutive valid closes with positive deviation. Crossing alerts additionally require a valid preceding Z. A return from an unavailable value does not count as a crossing.
  • Zero deviation returns na and suppresses alerts. A very small positive deviation is retained, not replaced by a tick-size floor. A tolerance or denominator floor would change the definition and must be documented if added.
  • Select Once Per Bar Close when creating an alert. Recreate it after changing script code or inputs because a running TradingView alert uses its saved snapshot. Chart confirmation does not solve confirmation for a future higher-timeframe extension.
A price-statistics indicator with intermediate values and confirmed chart-bar crossings. It places no orders and does not implement Altman Z-Score.pine
//@version=6
indicator("Price Z-score window audit", overlay = false, precision = 6)
length = input.int(20, "Window bars", minval = 2, maxval = 1000)
population = input.bool(true, "Population standard deviation")
threshold = input.float(2.0, "Absolute threshold", minval = 0.1)
mean = ta.sma(close, length)
deviation = ta.stdev(close, length, population)
missingCount = math.sum(na(close) ? 1.0 : 0.0, length)
ready = bar_index >= length - 1 and missingCount == 0 and not na(deviation)
z = ready and deviation > 0 ? (close - mean) / deviation : na
crossAbove = ta.crossover(z, threshold)
crossBelow = ta.crossunder(z, -threshold)
validPair = not na(z) and not na(z[1])
confirmed = barstate.isconfirmed
plot(confirmed ? z : na, "Price Z-score", color = color.blue, linewidth = 2, style = plot.style_linebr)
hline(0, "Rolling mean")
hline(threshold, "Upper threshold")
hline(-threshold, "Lower threshold")
plot(confirmed and ready ? mean : na, "Window mean", display = display.data_window)
plot(confirmed and ready ? deviation : na, "Window standard deviation", display = display.data_window)
alertcondition(confirmed and validPair and crossAbove, "Cross above upper threshold", "Confirmed price Z-score crossed above its upper threshold.")
alertcondition(confirmed and validPair and crossBelow, "Cross below lower threshold", "Confirmed price Z-score crossed below its lower threshold.")

Give Pineify the calculation and its acceptance checks

Use the Pine Script AI Coding Agent to draft or revise the disclosed calculation. Specify close prices, a current-inclusive window, the variance divisor, missing-data and zero-variance policies, and confirmed crossings. Request syntax checking, then compare TradingView output against the numerical examples before creating alerts.

  • Keep the mean and deviation visible during validation. Ask for an explanation whenever a proposed modification changes the source, smoothing, window endpoints, or denominator.
  • An oscillator with smoothing, adaptive thresholds, or return inputs can share the Z-score name while producing different values. Reproduce the documented formula you intend to use; a name alone cannot reveal a protected script.
Where Pineify fits

Pine Script AI Coding Agent

Draft a price Z-score indicator with explicit window and variance rules, then request syntax checking and verify its numerical output in TradingView.

Draft a price Z-score indicator

Frequently asked questions

Educational information, not investment advice. All price sequences are hypothetical arithmetic examples, not trading results. Statistical deviation and valid syntax do not establish future price direction or profitability.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.