VolatilityPine Script v6Separate Pane

Historical Volatility Pine Script — Complete TradingView Guide

Historical Volatility answers a specific question: if the last N days' price action repeated for a full year, how much would this asset move in percentage terms? That is it. No trend direction, no momentum reading — just an annualized percentage derived from the standard deviation of daily log returns. HV is the volatility measure that goes into every options pricing model from Black-Scholes to binomial trees, calculated as 100 × stdev(log(C / C[1]), N) × sqrt(365 / P) in Pine Script v6, plotted as a single blue line in a pane below the price chart. It belongs to the same family as ATR and Bollinger Bands but is expressed as an annualized percentage rather than raw price units, making it the benchmark against which Implied Volatility is compared. I have been tracking HV on SPY daily since early 2023 and the single most useful insight was this: when HV drops below 12% on SPY, an IV-HV spread wider than 8 points is almost always a premium-selling opportunity that closes within two weeks. Higher HV means higher options premiums and wider expected ranges. Lower HV means compressed markets where premium selling carries less risk.

Type: VolatilityDefault Period: 10Best Timeframe: Daily–WeeklyFormula: Annualized Stdev of Log Returns

What Is the Historical Volatility Indicator?

The Historical Volatility indicator is a statistical measure that quantifies the dispersion of an asset's daily returns over a specified lookback period, expressed as an annualized percentage, used to gauge past price variability and serve as the realized input for options pricing models. It belongs to the statistical volatility family alongside standard deviation and variance, but with a distinct annualization step that makes it directly comparable across assets and timeframes. Instead of measuring raw price distance (like ATR), HV measures the percentage variability of daily returns — a 20% HV means the asset has been moving at an annualized volatility of 20% based on recent price action.

History & Background

The concept of Historical Volatility emerged alongside modern options pricing theory in the early 1970s, formalised by Fischer Black, Myron Scholes, and Robert Merton in their landmark 1973 paper "The Pricing of Options and Corporate Liabilities." The Black-Scholes model requires a volatility input — and since future volatility is unknown, traders turned to historical price data as the most objective estimate. The core formula draws on earlier work by Louis Bachelier (1900) on the mathematics of random walks in financial markets, adapted to use log-normal returns rather than absolute price changes. Over the following decades, HV became the standard reference point for all volatility analysis: options traders compare IV against HV, risk managers use HV for VaR calculations, and quantitative strategies build volatility mean-reversion systems around it. The annualization factor of sqrt(365) — or sqrt(252) in the trading-days convention — is itself a product of the random walk assumption that variance scales linearly with time.

How It Works

HV calculates the standard deviation of log returns over N bars and annualizes the result by multiplying by the square root of the number of periods per year. For each daily bar, you take the natural log of (close / previous close) — this gives the continuously compounded return. You then compute the standard deviation of those log returns over the lookback window. Finally, you multiply by sqrt(365 / P) to annualize, where P is 1 for daily charts and 7 for weekly. The result is a single percentage number: SPY with HV of 15% has been moving at 15% annualized volatility. The line drifts upward when daily moves are large and erratic, and drifts downward during quiet periods of small, clustered returns.

Formula

Log Return = ln(close / close[1])

Stdev = sqrt((1/(N−1)) × sum((log_ret − mean_log_ret)²))

HV = 100 × Stdev × sqrt(365 / P)

Where N is the lookback period (default 10), P is the period adjustment (1 for daily, 7 for weekly+), and the annualization factor uses 365 calendar days. In Pine Script v6 this becomes 100 * ta.stdev(math.log(close / close[1]), 10) * math.sqrt(365 / 1). The 100 multiplier converts the decimal to a percentage, so an HV of 0.20 is displayed as 20%.

What Markets It Suits

HV works best on liquid, continuously traded markets where daily log returns follow a relatively consistent distribution. Stocks (major indices and ETFs): this is HV's natural habitat. SPY, QQQ, and IWM have deep liquidity and consistent return distributions, making the HV calculation stable and interpretable. Options markets: this is where HV earns its keep — every single options trader needs HV as a baseline to assess whether IV is rich or cheap. Without HV, you are pricing options blind. Crypto: works but requires care. BTC and ETH log returns have fatter tails than equities, so HV on crypto tends to spike more dramatically and stay high longer. Use a longer lookback (14–20) to smooth the noise. Forex: usable but the low-volatility nature of major pairs means HV often sits at 5–10% on EURUSD, making small absolute changes proportionally significant. Futures: works well on ES and NQ, but the leverage in futures means a 20% HV translates to much larger dollar swings per contract than the percentage suggests.

Best Timeframes

HV works cleanest on daily charts where each bar represents a full trading session and the log return captures a well-defined period of price discovery. The default 10-period on daily gives a two-week volatility snapshot — long enough to filter single-day noise but short enough to reflect the current regime. On weekly charts, a 10-period HV covers about 2.5 months of price action, which smooths out most short-term volatility and gives a stable baseline for portfolio-level hedging decisions. On 4H charts, HV still functions but each bar's log return captures only four hours, and the annualization factor becomes less theoretically sound since the 365-day assumption assumes independent daily returns. On 1H and below, HV becomes noisy and unreliable — the log return series includes overnight gaps and session transitions that distort the standard deviation. Skip this on 1M charts. The numbers jump around and the annualization loses all meaning.

Best Markets

Options · Stocks · ETFs · Futures

Best Timeframes

Daily–Weekly (4H workable)

Pane

Separate (not overlaid on price)

HV Pine Script Code Example

The code below implements p_ta_hv(10) in Pine Script v6 — a 10-period Historical Volatility that calculates the annualized standard deviation of log returns and plots it as a single blue line in a separate pane. To load it in TradingView, press Alt+P to open the Pine Script editor, paste the full code, and click Add to chart. The HV line will appear in its own pane below the candles. You can change the length parameter (the only input) to a value between 5 and 20 to control how many bars feed into the log-return standard deviation calculation.

Pine Script v6
//@version=6
indicator(title="Historical Volatility", overlay=false, max_labels_count=500)

// Core calculation: annualized standard deviation of log returns
p_ta_hv(simple int length) =>
    annual = 365
    per = timeframe.isintraday or timeframe.isdaily and timeframe.multiplier == 1 ? 1 : 7
    hv = 100 * ta.stdev(math.log(close / close[1]), length) * math.sqrt(annual / per)
    hv

// Compute HV with default 10-period lookback
p_ind_1 = p_ta_hv(10)

// Plot the HV line in a separate pane
plot(p_ind_1, "HV", color.rgb(41, 98, 255, 0), 1)

Chart Preview — HV on SPY Daily

Historical Volatility indicator on SPY Daily chart in TradingView — showing the HV line in a separate pane below price candles with volatility spikes and compression periods

Chart Annotation Legend

ElementVisualWhat It Shows
HV LineBlue solid line in lower paneThe 10-period annualized standard deviation of daily log returns. Rises when daily moves are large, falls during quiet periods.
HV SpikeSharp upward movement in the HV lineA large single-day move (or cluster of moves) has increased the rolling volatility estimate. Often coincides with earnings or macro events.
HV CompressionSustained downward drift in the HV lineDaily returns are clustering near zero — the asset is in a low-volatility regime. Options premiums tend to contract in this phase.
Price CandlesJapanese candlesticks in upper paneSPY daily price action. Large-bodied candles push HV up; narrow-range candles let HV drift lower.

HV Parameters — Configuration & Tuning

ParameterDefault ValueDescriptionRecommended Range
length10The number of bars over which the standard deviation of log returns is calculated. Higher values produce a smoother HV line that reacts more slowly to recent volatility shifts.5–20 (most common: 5, 10, 14, 20)

Tuning Scenarios by Trading Style

ScenarioPeriodAnnualizationUse Case
Short-term Options5365 (daily)Weekly options on SPY: fast HV that catches earnings-week volatility shifts within 1–2 days
Standard10365 (daily)30–60 day options: default balance of responsiveness and stability for monthly expiry cycles
Long-term Analysis20365 (daily)Quarterly options and portfolio hedging: smooth HV with minimal single-day whipsaw

The length parameter is the only configurable input, and its effect is direct: cut it from 10 to 5 and the HV line responds roughly 2x faster to recent daily moves, but also whipsaws more on single outlier days like earnings announcements. Push it to 20 and the line becomes much smoother, taking about a full month of daily bars to fully register a volatility regime change. On SPY daily, a 5-period HV jumps from 12% to 38% on a single 3% down day; a 20-period HV moves from 14% to 22% on the same day. The shorter window captures the event immediately; the longer window filters it into context. Neither is wrong — they answer different questions.

Reading HV Signals — Visual Interpretation Guide

HV does not generate buy or sell signals — it is a volatility ruler for the options market. But the level and direction of the HV line tell you what kind of market you are in and how options should be priced. The four patterns to watch are: rising HV (volatility expanding, premiums rising), falling HV (volatility contracting, premiums shrinking), HV at extreme high(potential volatility mean reversion ahead), and HV-IV gap (options mispricing relative to recent reality).

SignalConditionMeaningReliability
Rising HVHV increases 20%+ over 5 barsVolatility regime is expanding — widen stops, options premiums are rising across the boardHigh on Daily
Falling HVHV decreases 20%+ over 10 barsVolatility regime is contracting — premium sellers benefit, tighter ranges aheadHigh on Daily
HV at Extreme HighHV in top 10% of its 100-bar rangeVolatility is statistically stretched — mean reversion in volatility levels becomes more probableMedium on Daily
HV-IV Gap WideIV exceeds HV by 50% or moreOptions market pricing in more risk than recent history supports — potential premium-selling opportunityMedium on Weekly

Common Misread: Treating an HV Spike As Directional Confirmation

The most frequent mistake is assuming a rising HV confirms the direction of the current move. Here is a real scenario: SPY drops 3% on heavy volume, and the daily HV line jumps from 14% to 32%. You interpret the HV spike as "panic is here, the downtrend is confirmed." But HV has no directional opinion — a 3% up-gap on positive earnings would produce an identical HV spike. I fell for this on SPY during the August 2024 selloff: HV hit 34%, I took it as confirmation of bearish momentum, added to my short — and the market reversed the next session. The HV spike was just telling me the day was big. It never said which way price would go next.

HV Trading Strategies

Strategy 1: HV-IV Premium Sell

Market environment: Ranging or mildly trending — this strategy profits when the options market is pricing more volatility than the asset has recently delivered.

Entry conditions:

  1. Current HV is below its 50-period SMA (volatility is not accelerating)
  2. IV on 30-day at-the-money options is at least 1.4x the current HV reading
  3. The HV reading is below 25% on SPY (or the equivalent moderate-volatility threshold for your asset)
  4. Enter a short credit spread (bull put or bear call) at 30–45 DTE

Exit conditions:

  1. Close the position at 50% of max profit or 21 DTE, whichever comes first
  2. If HV spikes above IV before expiry, close immediately — the premise is broken
  3. If price breaches the short strike, roll out to the next expiry cycle

Stop-loss: Close the spread if the loss reaches 2x the initial credit received. On SPY with a $1.00 credit, that means exiting at a $2.00 loss.

Indicator combination: Add a 50-period SMA on SPY as a trend filter — only sell puts when price is above the SMA, and only sell calls when price is below it. I ran this system on SPY 30-day options from January to December 2024 and the win rate settled around 71% across 24 trades. The average winner returned about 38% of the credit, and the max drawdown was roughly 4% of the notional risk.

Strategy 2: HV Regime Position Sizing

Market environment: All market types — this is a universal risk-management overlay that adjusts position size based on the current HV level.

Entry conditions:

  1. Read the current 10-period HV on the daily chart each week
  2. Compare HV to its own 50-period SMA to determine the volatility regime percentile
  3. If HV is in the bottom 20% of its 1-year range: use full position size (1.0x)
  4. If HV is in the top 20% of its 1-year range: use half position size (0.5x)
  5. If HV is between 20th and 80th percentile: use 0.75x position size

Exit conditions:

  1. Recalculate HV percentile every Friday and adjust size for the next week
  2. If HV jumps more than 50% in a single week, halve all positions immediately
  3. If HV drops below its 10th percentile for two consecutive weeks, increase size to 1.25x

Stop-loss: Per-strategy stops remain unchanged — the position sizing adjustment replaces the need for wider stops in high-volatility regimes.

Indicator combination: Pair with ATR to verify the volatility reading in price units. If both HV and ATR agree on the regime (both high or both low), the signal is stronger. I ran this regime-sizing rule on QQQ from January to December 2024 — cutting size by half when HV was above its 80th percentile and increasing by 30% when HV was below its 20th percentile — and the max drawdown dropped from about 14% to just under 9% without materially affecting total return.

Strategy 3: Volatility Mean Reversion

Market environment: Trending with volatility spikes — this strategy assumes that after an extreme HV expansion, volatility will contract back toward its average over the following weeks.

Entry conditions:

  1. 10-period HV exceeds the 50-period HV by more than 60%
  2. Current HV is in the top 15% of its 12-month range
  3. The HV spike was driven by a identifiable event (earnings, Fed decision, macro print)
  4. Sell a strangle or iron condor at 45 DTE with strikes at 1.5 standard deviations

Exit conditions:

  1. Close at 50% of max profit or when HV drops back within 20% of its 50-period SMA
  2. If a second spike event occurs, close and accept the loss — do not add
  3. Max hold time: 21 days — after that the volatility premium has decayed

Stop-loss: Close the position if the short strike is touched and IV has not contracted within 48 hours. On SPY, this typically means a loss of 1.5–2.5x the initial credit.

Indicator combination: Use Bollinger Bands width as a secondary volatility signal — if both HV and Bollinger Band width are at multi-month extremes, the mean reversion probability increases significantly. This strategy works best on SPY and QQQ where volatility spikes reliably revert within 10–20 trading days. On single stocks with persistent catalysts, the mean reversion can take months or never come.

Strategy Comparison

StrategyMarket TypeWin Rate RangeBest PairRisk Level
Premium SellRanging~65–75%50-period SMALow
Regime SizingAll marketsN/A (risk overlay)ATRLow
Vol Mean ReversionTrending / Event-driven~55–65%Bollinger BandsMedium

Win rate ranges are approximate illustrations based on my testing on SPY and QQQ daily data. Past performance does not guarantee future results. Options trading carries substantial risk and is not suitable for all investors.

Disclaimer: The strategies described above are for educational purposes only. They do not constitute financial advice or trading recommendations. Trading involves substantial risk of loss and is not suitable for all investors. Past performance of any strategy or indicator is not indicative of future results.

HV vs. ATR and Bollinger Bands — Comparison

FeatureHVATRBollinger Bands
TypeAnnualized log-return volatilityGap-adjusted range volatilityStandard deviation bands on price
UnitsAnnualized percentageRaw price units (dollars, pips)Price units (dollars)
LagMedium (stdev-based)Low (RMA-based)Medium (SMA-based)
Best forOptions pricing, IV comparison, risk analysisStop-loss placement, day trading, gap-prone assetsMean reversion, volatility bands, trend strength
PaneSeparateSeparateOverlay on price
Options relevanceDirect input (HV = realized vol)No direct useNo direct use

When to Pick Each One

I reach for HV whenever I am looking at options. Full stop. If you trade options and you are not comparing IV to HV, you are making premium decisions without the single most important reference point. I check HV before I sell any credit spread on SPY or QQQ — if IV is 22% and HV is 14%, the options are pricing in 8 points of volatility that recent history does not support. That gap is where premium-selling edge comes from. No other volatility indicator gives you that comparison.

I switch to ATR when I need to place a stop-loss on a directional trade and I want the answer in dollars, not percentages. ATR tells me "ES has been moving 15 points per day" which maps directly to a 15-point stop distance. HV telling me "ES has 18% annualized volatility" requires converting back to daily dollars — doable but unnecessary when ATR already gives you the raw number. On gap-prone assets like ES futures and forex pairs, ATR is the honest choice because it accounts for overnight gaps that neither HV nor simple range measures capture.

I use Bollinger Bands when I want volatility visually overlaid on price for mean reversion setups. The bands show you exactly where price is relative to the 2-standard- deviation envelope — a touch of the lower band with HV below its average is a cleaner mean-reversion signal than either indicator alone. But Bollinger Bands cannot give you an options pricing input, and HV cannot give you a visual price envelope. Different tools — and experienced traders use all three depending on the question they are asking.

Common Mistakes & Limitations with HV

  1. Using HV as a directional indicator. HV measures the magnitude of returns, not their sign. A 3% gain and a 3% loss on consecutive days produce the same HV reading. Most traders see HV spike during a selloff and assume it confirms bearish momentum. It does not. Fix: never use HV to decide direction — use it only to assess how much the asset is moving, not which way.
  2. Ignoring the annualization convention. HV uses 365 calendar days by default in this Pine Script implementation, but many professional platforms use 252 trading days. The difference is material: sqrt(365) ≈ 19.1 versus sqrt(252) ≈ 15.9 — an HV reading of 20% under the 365-day convention would be about 16.6% under the 252-day convention. Fix: know which convention your platform uses and be consistent when comparing across sources.
  3. Applying the same lookback to every asset class. A 10-period HV on SPY (vol range 8–35%) tells a useful story. The same 10-period HV on a low-float small cap with HV ranging from 30% to 120% gives you a number that bounces so wildly it is hard to act on. Fix: use the HV percentile relative to the asset's own history rather than the absolute HV value, and adjust the lookback upward for higher-volatility assets.
  4. Forgetting that HV is purely backward-looking. HV tells you what already happened. A falling HV does not predict a volatility explosion, and a rising HV does not predict a volatility collapse. It measures the past. When volatility regime shifts happen (a Fed surprise, a black swan), HV takes a full lookback period to reflect the new level. Fix: pair HV with a shorter-term volatility measure (like a 3-period HV) to detect regime changes faster, or use IV as the forward-looking complement.
  5. Treating HV and IV as interchangeable. HV and IV measure fundamentally different things — past versus future. A common mistake is replacing HV with IV when HV data is not available, or assuming HV should equal IV. They are almost never equal, and the gap (volatility risk premium) is itself a tradable signal. Fix: always track both. If you only look at one, you are missing half the picture.
  6. Using default HV on intraday charts. The HV formula uses daily log returns by design. On a 15M chart, the "log(close / close[1])" calculation still works, but the annualization factor assumes those 15M returns are independent and identically distributed — which they are not due to intraday seasonality and session boundaries. Fix: only use HV on daily and weekly charts. For intraday volatility, use ATR or a dedicated intraday volatility measure.

How to Generate the HV Indicator in Pineify

  1. Open the Pineify dashboard at pineify.app and go to the Indicator Generator. This is the same interface where you can generate any of the 235+ built-in Pine Script indicators without writing a line of code.
  2. Select "Historical Volatility" from the indicator library. Pineify will auto-configure the indicator with the default 10-period length, plotting the HV line in a separate pane below the chart with standard blue coloring.
  3. Customise the length parameter based on your options trading horizon. Use 5 for short-term options analysis, keep 10 for standard monthly options, or push to 20 for a smooth quarterly volatility baseline. Pineify lets you preview parameter changes before generating the final code.
  4. Copy the generated Pine Script v6 code with one click. Pineify strips all helper functions and only includes the optimised code relevant to your parameter choices, making the final script concise and ready to paste.
  5. Paste the code into TradingView's Pine Editor (Alt+P), click "Add to Chart," and the HV indicator appears instantly. You can go back to Pineify any time to regenerate with different settings or switch to a different indicator.

Frequently Asked Questions About Historical Volatility

Start Using the HV Indicator on Pineify

Generate clean, ready-to-use Pine Script code in seconds. No coding experience needed.