Skip to content
GetProfitable
Search
Volatility

Historical Volatility

The standard deviation of log returns over a lookback, annualised and shown as a percentage, plotted against its own longer average so periods of expansion and compression separate clearly.

indicator
//@version=6
indicator("Historical Volatility", "Hist Vol")

length = input.int(20, "Lookback bars", minval = 2, group = "Settings")
avgLen = input.int(50, "Average length", minval = 2, group = "Settings")
perYear = input.int(252, "Bars per year", minval = 1, group = "Settings")
highCol = input.color(#EF5350, "Above average", group = "Style")
lowCol = input.color(#26A69A, "Below average", group = "Style")
lineCol = input.color(#787B86, "Average", group = "Style")

logReturn = math.log(close / nz(close[1], close))
hv = ta.stdev(logReturn, length) * math.sqrt(perYear) * 100
hvAvg = ta.sma(hv, avgLen)

plot(hv, "Annualised volatility percent", color = hv > hvAvg ? highCol : lowCol, linewidth = 2)
plot(hvAvg, "Average", color = color.new(lineCol, 20))

expanding = ta.crossover(hv, hvAvg)
contracting = ta.crossunder(hv, hvAvg)
plotshape(expanding, "Expanding", location = location.bottom, style = shape.triangleup, color = highCol, size = size.tiny)
plotshape(contracting, "Contracting", location = location.top, style = shape.triangledown, color = lowCol, size = size.tiny)
alertcondition(expanding, "Volatility above its average", "Annualised volatility crossed above its own average")
alertcondition(contracting, "Volatility below its average", "Annualised volatility crossed below its own average")
This runs in TradingView, not here
Pine Script only executes inside TradingView. Paste the source into the Pine Editor and add it to a chart to see it plotted.

What it will not do

  • This is realised volatility, measured from bars that have already printed. It is not the implied volatility an option is priced from and the two often disagree.
  • The annualisation factor must match the chart. The 252 default is trading days, so an intraday or weekly chart needs a different number or the percentage is meaningless.
  • Volatility clusters, which means a high reading tends to be followed by another high reading. That is a statement about volatility, not about direction.
  • A single outsized bar dominates the window for the whole lookback and then drops out of it abruptly.

Written from this description

Compute the standard deviation of log returns over N bars, annualise it with a configurable number of bars per year, plot it as a percentage with its own moving average, and mark the crossings of that average.

Educational only, not financial advice. The maths is simple arithmetic on the numbers you enter; it knows nothing about your broker, fees, slippage or the market. Something wrong with it? Say so in Site Feedback.