You wrote a volatility band, plotted it next to the built-in Bollinger Bands, and the two do not quite match. Or you copied a formula from a statistics textbook into Pine Script and the numbers are a few percent off from what ta.stdev returns. Nothing is broken. The function has a third parameter called biased, it defaults to the one most traders never expect, and it decides whether you are measuring a population or a sample.
This guide covers the full signature of ta.stdev, the arithmetic behind it, what the biased flag changes and when the change matters, and a few ways to use standard deviation that go past Bollinger Bands. Every code block is complete Pine Script v6, so you can paste it into the TradingView Pine Editor and read the result on a chart.
The signature of ta.stdev
The function takes a source series, a length, and an optional flag:
ta.stdev(source, length, biased) -> series floatThe source is any series of numbers, most often close, but it can be a return series, an oscillator, or the output of another calculation. The length is the number of bars in the rolling window. The biased argument is a bool that defaults to true.
On every bar the function looks at the last length values of the source, measures how far they scatter around their own average, and returns that scatter as a single number in the same units as the source. If you run it on close for a stock quoted in dollars, the result is in dollars. Run it on a percentage return and the result is in percentage points. That unit matching is the reason standard deviation is so convenient: it can be added to and subtracted from the thing it measures, which is exactly what a band does.
Until the window is full the function returns na, so a 20 bar standard deviation starts plotting on the twentieth bar of the chart history. The Pine Script manual describes the same behaviour for most ta.* functions, and it is why plots that depend on a long lookback appear to start late.
What it actually computes
Standard deviation is the square root of variance, and variance is the average squared distance from the mean. For a window of N values, the steps are: find the mean, subtract it from every value, square each difference, add the squares up, divide, and take the square root. The only open question is what you divide by.
Take eight numbers: 2, 4, 4, 4, 5, 5, 7 and 9. Their mean is 5. The squared distances from 5 are 9, 1, 1, 1, 0, 0, 4 and 16, which add up to 32. Dividing by N, which is 8, gives a variance of 4 and a standard deviation of exactly 2. Dividing by N minus 1, which is 7, gives a variance of about 4.571 and a standard deviation of about 2.138. Same data, two defensible answers.
The first version is the population standard deviation. You use it when the numbers in the window are the whole group you care about. The second is the sample standard deviation, which you use when the numbers are a sample drawn from a larger group and you want to estimate the spread of that larger group. Dividing by N minus 1 corrects for the fact that a sample's own mean sits closer to its values than the true mean would.
You can check this inside Pine Script itself with array.stdev, which takes the same biased argument:
//@version=6
indicator("Stdev check", overlay = true)
if barstate.islast
values = array.from(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
popSd = array.stdev(values, true)
sampleSd = array.stdev(values, false)
label.new(bar_index, high, str.format("population {0,number,0.000}\nsample {1,number,0.000}", popSd, sampleSd))The label on the last bar shows 2.000 for the population version and 2.138 for the sample version. If you have ever wondered which number a spreadsheet gave you, this is the question: Excel's STDEV.P matches biased = true and STDEV.S matches biased = false.
Sample versus population: which one should you use
The default is biased = true, the population version. That choice is not an accident. Bollinger's original bands were defined with the population formula, and ta.bb uses it too. If you want a band that lines up with the built-in indicator, leave the flag alone.
The size of the gap between the two versions is a fixed ratio. The sample result equals the population result multiplied by the square root of N divided by N minus 1. For a window of 20 that factor is about 1.026, so the sample number is roughly 2.6 percent larger. For a window of 5 it is about 1.118, which is 11.8 percent larger, and for a window of 2 it is about 1.414. The longer the window, the less the flag matters.
That gives a practical rule. With a lookback of 20 or more, the difference is a rounding-level detail for most visual work, and the default is fine. With very short windows, say 2 to 10 bars, the flag changes the answer enough to move a threshold, so pick one on purpose and write it down. And if you are comparing your Pine Script output to a statistics library or a spreadsheet, match the flag first, because that is the most common reason the numbers disagree.
The honest argument for biased = false is when you treat a window of bars as a sample from the market's underlying behaviour and want an unbiased estimate of its spread. The honest argument for the default is that you are describing the window itself and nothing more. Both are fine. What matters is that the same choice is used everywhere in a script, including in any z-score or threshold logic that depends on it.
Standard deviation of price versus standard deviation of returns
Most examples feed close straight into ta.stdev. That works for bands, because bands live in price units. It works poorly for comparing volatility between markets or across time, because the number scales with the price level. A standard deviation of 500 on a market trading at 60,000 is calmer than a standard deviation of 5 on a market trading at 100, and the raw numbers hide that.
The usual fix is to measure the spread of returns instead. A simple version uses the percentage change from bar to bar, and a common one uses the log return, which is the natural logarithm of this close divided by the previous close:
//@version=6
indicator("Return volatility", overlay = false)
length = input.int(20, "Length", minval = 2)
useSample = input.bool(false, "Sample standard deviation")
logReturn = math.log(close / close[1])
vol = ta.stdev(logReturn, length, not useSample) * 100
plot(vol, "Stdev of log returns (%)", color = color.new(color.orange, 0))Because biased is the opposite of "use sample", the script passes not useSample. The plot is the per-bar volatility in percent, and it is comparable across markets and across years of the same market. Note the minval = 2 on the length. A window of 1 has no spread to measure, and the sample version would divide by zero.
If you want the result on a longer time scale, you scale it by the square root of the number of bars in that scale. That is a modelling assumption, not a law, and it only holds if bar-to-bar returns are roughly independent. State the assumption wherever you show the number.
For a different view of the same idea, the ATR guide covers a volatility measure built from the true range, which responds to gaps and wide bars in a way standard deviation of closes does not.
Building bands with ta.stdev
Bands are the classic use. Take a moving average, add and subtract a multiple of the standard deviation, and you get an envelope that widens when price scatters and narrows when it calms down. Here is a version built by hand so every part is visible:
//@version=6
indicator("Stdev bands", overlay = true)
length = input.int(20, "Length", minval = 2)
mult = input.float(2.0, "Multiplier", minval = 0.1, step = 0.1)
useSample = input.bool(false, "Sample standard deviation")
basis = ta.sma(close, length)
dev = mult * ta.stdev(close, length, not useSample)
upper = basis + dev
lower = basis - dev
plot(basis, "Basis", color = color.new(color.gray, 0))
p1 = plot(upper, "Upper", color = color.new(color.blue, 0))
p2 = plot(lower, "Lower", color = color.new(color.blue, 0))
fill(p1, p2, color = color.new(color.blue, 90))With the defaults, the bands should sit on top of the built-in ta.bb(close, 20, 2) output, because both use a 20 bar simple moving average and the population formula. Switch the sample option on and the bands widen by that 2.6 percent. That is a quick way to see the flag working.
The Bollinger Bands guide goes deeper on reading the bands, including how width relates to squeezes. The Keltner Channels guide builds the same envelope from ATR instead of standard deviation, and comparing the two on one chart is a good way to see how the choice of volatility measure changes the shape.
One point trips up readers who build their first band: the standard deviation is measured around its own window's mean. Here that mean is the same simple moving average used as the basis, so the pieces agree. If you swap the basis for an EMA but keep ta.stdev, the deviation is still measured around the simple mean of the window, and the band is no longer centred on the line you drew. That is allowed, but it is a different indicator. The moving average types guide explains how each average weights the window.
Z-scores: how far from normal is this bar
Once you have a mean and a standard deviation, a z-score is one division away. It expresses how many standard deviations a value sits from the window's average, which turns raw price or an oscillator into a unit-free number you can compare over time.
//@version=6
indicator("Close z-score", overlay = false)
length = input.int(50, "Length", minval = 2)
mean = ta.sma(close, length)
sd = ta.stdev(close, length)
z = sd > 0 ? (close - mean) / sd : na
plot(z, "Z-score", color = color.new(color.teal, 0))
hline(0, "Mean")
hline(2, "+2", color = color.gray, linestyle = hline.style_dashed)
hline(-2, "-2", color = color.gray, linestyle = hline.style_dashed)The sd > 0 guard matters. On a perfectly flat stretch of data, which can happen on thinly traded markets or on a derived series that is constant for a while, the standard deviation is zero and the division would produce a meaningless value. Returning na is the honest result there. The Pine Script na guide explains how a missing value moves through a script and how to stop it spreading.
A z-score is a description of where the latest value sits against recent history. It does not say what happens next. Many price series have fat tails, which means moves beyond two standard deviations occur more often than a bell curve suggests, so treat the dashed lines as reference marks, not as thresholds with any special meaning. The percentrank guide shows a rank-based alternative that makes no assumption about the shape of the distribution.
Common mistakes
The first mistake is forgetting that the result is na until the window fills. A script that tests sd < threshold on early bars gets false for the wrong reason, because comparing with na yields false. If a condition has to hold from the first bar, handle the warm-up explicitly with bar_index >= length.
The second is picking a window without thinking about it. A short window reacts fast and is noisy, and a long one is smooth and slow, so the length is a real design choice, not a default to accept. Try two or three values on the same chart before settling.
The third is treating a standard deviation of price as a measure of risk on its own. Price levels trend, so a rising market has a large standard deviation of close even when day-to-day moves are small. That is why the return version is usually the better measure of how rough the ride is.
The fourth is mixing the two flags between functions. If one part of a script uses ta.stdev with the default and another uses ta.variance or array.stdev with the opposite setting, the results disagree by the factor from earlier and the script is wrong in a way that is hard to spot. ta.variance takes the same biased argument, and variance is the square of the standard deviation computed with the same flag.
The fifth is expecting ta.dev to match. That function returns the mean absolute deviation, which averages the absolute distances from the mean instead of squaring them. It is smaller than the standard deviation for the same data and it reacts less to a single extreme bar. The two are related, but they are different statistics, and they are not interchangeable in a band.
Describing a volatility band to PineScripter
If you would rather start from the description than from the code, you can ask for it in plain English at PineScripter. A request such as "Plot a 20 bar moving average with bands at 2 standard deviations of the log returns, and add an option to use the sample standard deviation" is enough to get a Pine Script v6 draft. The editor checks the script for compile errors the same way TradingView does and fixes them itself, and a follow-up like "make the multiplier 1.5 and shade the area between the bands" changes only the lines that are affected.
You can then run the script on its Chart against real market data, from its 308 crypto spot markets, and see the plots before you paste anything into TradingView. Read what comes back the way you would read any code you did not type yourself: check the biased flag, check that the bands match ta.bb when the settings match, and step through a few bars by hand. The free standard deviation calculator is a quick way to confirm the arithmetic for a short series.
Putting it together
The ta.stdev function is small, but three decisions sit inside it: the source you measure, the window you measure it over, and the divisor you use. Measure price when you want bands in price units, measure returns when you want to compare volatility between markets, keep the default population formula when you want to match Bollinger Bands, and switch to the sample formula when your window is short and you are estimating a wider group. Write the choice into the script's inputs so the next person, who might be you in six months, can see it.
When two numbers disagree, check the flag before you check anything else. It is almost always the reason.
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.
Frequently asked questions
What is the default for biased in ta.stdev?
The default is true, which gives the population standard deviation (divide by N). Set biased to false for the sample version (divide by N minus 1).
Does ta.stdev match Bollinger Bands?
Yes, with the default flag. Bollinger Bands use a simple moving average and the population standard deviation, so a band built from ta.sma and ta.stdev with the same length and multiplier matches ta.bb.
How much does the sample flag change the result?
The sample result is the population result times the square root of N divided by N minus 1. That is about 1.026 for a 20 bar window and about 1.118 for a 5 bar window.
What is the difference between ta.stdev and ta.dev?
ta.stdev squares the distances from the mean before averaging, while ta.dev averages the absolute distances. ta.dev is usually smaller and reacts less to one extreme bar.
Why is ta.stdev na at the start of the chart?
The function needs a full window of values, so it returns na until the chart has at least length bars of data.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.