OPEN-SOURCE SCRIPT

[GYTS] Volatility Toolkit

201
[GYTS] Volatility Toolkit
🌸 Part of GoemonYae Trading System (GYTS) 🌸


🌸 --------- INTRODUCTION --------- 🌸

💮 What is Volatility Toolkit?
Volatility Toolkit is a comprehensive volatility analysis indicator featuring academically-grounded range-based estimators. Unlike simplistic measures like ATR, these estimators extract maximum information from OHLC data — resulting in estimates that are 5-14× more statistically efficient than traditional close-to-close methods.

The indicator provides two configurable estimator slots, weighted aggregation, adaptive threshold detection, and regime identification — all with flexible smoothing options via
GYTS FiltersToolkit integration.

💮 Why Use This Indicator?
Standard volatility measures (like simple standard deviation) are highly inefficient, requiring large amounts of data to produce stable estimates. Academic research has shown that range-based estimators extract far more information from the same price data:

Statistical Efficiency — Yang-Zhang achieves up to 14× the efficiency of close-to-close variance, meaning you can achieve the same estimation accuracy with far fewer bars
Drift Independence — Rogers-Satchell and Yang-Zhang correctly isolate variance even in strongly trending markets where simpler estimators become biased
Gap Handling — Yang-Zhang properly accounts for overnight gaps, critical for equity markets
Regime Detection — Built-in threshold modes identify when volatility enters elevated or suppressed states

снимок↑ Overview showing Yang-Zhang volatility with dynamic threshold bands and regime background colouring


🌸 --------- HOW IT WORKS --------- 🌸

💮 Core Concept
The toolkit groups volatility estimators by their output scale to ensure valid comparisons and aggregations:

Log-Return Scale (σ) — Close-to-Close, Parkinson, Garman-Klass, Rogers-Satchell, Yang-Zhang. These are comparable and can be aggregated. Annualisable via √(periods_per_year) scaling.
Price Unit Scale ($) — ATR. Measures volatility in absolute price terms, directly usable for stop-loss placement.
Percentage Scale (%) — Chaikin Volatility. Measures the rate of change of the trading range — whether volatility is expanding or contracting.

Only estimators with the same scale can be meaningfully compared or aggregated. The indicator enforces this and warns when mixing incompatible scales.

💮 Range-Based Estimator Overview
Range-based estimators utilise High, Low, Open, and Close prices to extract significantly more information about the underlying diffusion process than close-only methods:

Parkinson (1980) — Uses High-Low range. ~5× more efficient than close-to-close. Assumes zero drift.
Garman-Klass (1980) — Incorporates Open and Close. ~7.4× more efficient. Assumes zero drift, no gaps.
Rogers-Satchell (1991) — Drift-independent. Superior in trending markets where Parkinson/GK become biased.
Yang-Zhang (2000) — Composite estimator handling both drift and overnight gaps. Up to 14× more efficient.

💮 Theoretical Background
• Parkinson, M. (1980). The Extreme Value Method for Estimating the Variance of the Rate of Return. Journal of Business, 53(1), 61–65. DOI
• Garman, M.B. & Klass, M.J. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business, 53(1), 67–78. DOI
• Rogers, L.C.G. & Satchell, S.E. (1991). Estimating Variance from High, Low and Closing Prices. Annals of Applied Probability, 1(4), 504–512. DOI
• Yang, D. & Zhang, Q. (2000). Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices. Journal of Business, 73(3), 477–491. DOI


🌸 --------- KEY FEATURES --------- 🌸

💮 Feature Reference

Estimators (8 options across 3 scale groups):
Close-to-Close — Classical benchmark using closing prices only. Least efficient but useful as baseline. Log-return scale.
Parkinson — Range-based (High-Low), ~5× more efficient than close-to-close. Assumes zero drift. Log-return scale.
Garman-Klass — OHLC-optimised, ~7.4× more efficient. Assumes zero drift, no gaps. Log-return scale.
Rogers-Satchell — Drift-independent, handles trending markets where Parkinson/GK become biased. Log-return scale.
Yang-Zhang — Gap-aware composite, most comprehensive (up to 14× efficient). Uses internal rolling variance (unsmoothed). Log-return scale.
Std Dev — Standard deviation of log returns. Log-return scale.
ATR — Average True Range in absolute price units. Useful for stop-loss placement. Price unit scale.
Chaikin — Rate of change of range. Measures volatility expansion/contraction, not level. Percentage scale.

Smoothing Filters (10 options via FiltersToolkit):
SMA / EMA — Classical moving averages
Super Smoother (2-Pole / 3-Pole) — Ehlers IIR filter with excellent noise reduction
Ultimate Smoother (2-Pole / 3-Pole) — Near-zero lag in passband
BiQuad — Second-order IIR with configurable Q factor
ADXvma — Adaptive smoothing, flat during ranging periods
MAMA — MESA Adaptive Moving Average (cycle-adaptive)
A2RMA — Adaptive Autonomous Recursive MA

Threshold Modes:
Static — Fixed threshold values you define (e.g., 0.025 annualised)
Dynamic — Adaptive bands: baseline ± (standard deviation × multiplier)
Percentile — Threshold at Nth percentile of recent history (e.g., 80th percentile for high)

Visual Features:
Level-based colour gradient — Line colour shifts with percentile rank (warm = high vol, cool = low vol)
Fill to zero — Gradient fill intensity proportional to volatility level
Threshold fills — Intensity-scaled fills when thresholds are breached
Regime background — Chart background indicates HIGH/NORMAL/LOW volatility state
Legend table — Displays estimator names, parameters, current values with percentile ranks (P##)


💮 Dual Estimator Slots
Compare two volatility estimators side-by-side. Each slot independently configures:
• Estimator type (8 options across three scale groups)
• Lookback period and smoothing filter
• Colour palette and visual style

This enables direct comparison between estimators (e.g., Yang-Zhang vs Rogers-Satchell) or between different parameterisations of the same estimator.

снимок↑ Yang-Zhang (reddish) and Rogers-Satchell (greenish)

💮 Flexible Smoothing via FiltersToolkit
All estimators (except Yang-Zhang, which uses internal rolling variance) support configurable smoothing through 10 filter types. Using Infinite Impulse Response (IIR) filters instead of SMA avoids the "drop-off artefact" where volatility readings crash when old spikes exit the window.

Example: Same estimator (Parkinson) with different smoothing filters
Add two instances of Volatility Toolkit to your chart:
• Instance 1: Parkinson with SMA smoothing (lookback 14)
• Instance 2: Parkinson with Super Smoother 2-Pole (lookback 14)

Notice how SMA creates sharp drops when volatile bars exit the window, while Super Smoother maintains a gradual transition.

снимок↑ Two Parkinson estimators — SMA (red mono-colour, showing drop-off artefacts) vs Super Smoother (turquoise mono colour, with smooth transitions)

снимок↑ Garman-Klass with BiQuad (orangy) and 2-pole SuperSmoother filters (greenish)

💮 Weighted Aggregation
Combine multiple estimators into a single weighted average. The indicator automatically:
• Validates scale compatibility (only same-scale estimators can be aggregated)
• Normalises weights (so 2:1 means 67%:33%)
• Displays clear warnings when scales differ

Example: Robust volatility estimate
Combine Yang-Zhang (handles gaps) with Rogers-Satchell (handles drift) using equal weights:
• E1: Yang-Zhang (14)
• E2: Rogers-Satchell (14)
• Aggregation: Enabled, weights 1:1

The aggregated line (with "fill to zero" enabled) provides a more robust estimate by averaging two complementary methodologies.

снимок↑ Yang-Zhang + Rogers-Satchell with aggregation line (thicker) showing combined estimate (notice how opening gaps are handled differently)

Example: Trend-weighted aggregation
In strongly trending markets, weight Rogers-Satchell more heavily since it's drift-independent:
• Estimator 1: Garman-Klass (faster, higher weight in ranging)
• Estimator 2: Rogers-Satchell (drift-independent, higher weight in trends)
• Aggregation: weights 1:2 (favours RS during trends)

💮 Adaptive Threshold Detection
Three threshold modes for identifying volatility regime shifts. Threshold breaches are visualised with intensity-scaled fills that grow stronger the further volatility exceeds the threshold.

Example: Dynamic thresholds for regime detection
Configure dynamic thresholds to automatically adapt to market conditions:
• High Threshold Mode: Dynamic (baseline + 2× std dev)
• Low Threshold Mode: Dynamic (baseline - 2× std dev)
• Show threshold fills: Enabled

This creates adaptive bands that widen during volatile periods and narrow during calm periods.

Example: Percentile-based thresholds
Use percentile mode for context-aware regime detection:
• High Threshold Mode: Percentile (96th)
• Low Threshold Mode: Percentile (4th)
• Percentile Lookback: 500

This identifies when volatility enters the top/bottom 4% of its recent distribution.

снимок↑ Different threshold settings, where the dynamic and percentile methods show adaptive bands that widen during volatile periods, with fill intensity varying by breach magnitude. Regime detection (see next) is enabled too.

💮 Regime Background Colouring
Optional background colouring indicates the current volatility regime:
High Volatility — Warm/alert background colour
Normal — No background (neutral)
Low Volatility — Cool/calm background colour

Select which source (Estimator 1, Estimator 2, or Aggregation) drives the regime display.

Example: Regime filtering for trade decisions
Use regime background to filter trading signals from other indicators:
• Regime Source: Aggregation
• Background Transparency: 90 (subtle)

When the background shows HIGH volatility (warm), consider tighter stops. When LOW (cool), watch for breakout setups.

снимок↑ Regime background emphasis for breakout strategies. Note the interesting A2RMA smoothing for this case.


🌸 --------- USAGE GUIDE --------- 🌸

💮 Getting Started
1. Add the indicator to your chart
2. Estimator 1 defaults to Yang-Zhang (14) — the most comprehensive estimator for gapped markets
3. Keep "Annualise Volatility" enabled to express values in standard annualised form
4. Observe the legend table for current values and percentile ranks (P##). Hover over the table cells to see a little more info in the tooltip.

💮 Choosing an Estimator
Trending equities with gaps — Yang-Zhang. Handles both drift and overnight gaps optimally.
Crypto (24/7 trading) — Rogers-Satchell. Drift-independent without Yang-Zhang's multi-period lag.
Ranging markets — Garman-Klass or Parkinson. Simpler, no drift adjustment needed.
Price-based stops — ATR. Output in price units, directly usable for stop distances.
Regime detection — Combine any estimator with threshold modes enabled.

💮 Interpreting Output
Value (P##) — The volatility reading with percentile rank. "0.1523 (P75)" means 0.1523 annualised volatility at the 75th percentile of recent history.
Colour gradient — Warmer colours = higher percentile (elevated volatility), cooler colours = lower percentile.
Threshold fills — Intensity indicates how far beyond the threshold the current reading is.
⚠️ HIGH / 🔻 LOW — Table indicators when thresholds are breached.


🌸 --------- ALERTS --------- 🌸

💮 Direction Change Alerts
Estimator 1/2 direction change — Triggers when volatility inflects (rising to falling or vice versa)

💮 Cross Alerts
E1 crossed E2 — Triggers when the two estimator lines cross

💮 Threshold Alerts
E1/E2/Aggr High Volatility — Triggers when volatility breaches the high threshold
E1/E2/Aggr Low Volatility — Triggers when volatility falls below the low threshold

💮 Regime Change Alerts
E1/E2/Aggr Regime Change — Triggers when the volatility regime transitions (High ↔ Normal ↔ Low)


🌸 --------- LIMITATIONS --------- 🌸

Drift bias in Parkinson/GK — These estimators overestimate variance in trending conditions. Switch to Rogers-Satchell or Yang-Zhang for trending markets.
Yang-Zhang minimum lookback — Requires at least 2 bars (enforced internally). Cannot produce instantaneous readings like other estimators.
Flat candles — Single-tick bars produce near-zero variance readings. Use higher timeframes for illiquid assets.
Discretisation bias — Estimates degrade when ticks-per-bar is very small. Consider higher timeframes for thinly traded instruments.
Scale mixing — Different scale groups (log-return, price unit, percentage) cannot be meaningfully compared or aggregated. The indicator warns but does not prevent display.


🌸 --------- CREDITS --------- 🌸

💮 Academic Sources
• Parkinson, M. (1980). The Extreme Value Method for Estimating the Variance of the Rate of Return. Journal of Business, 53(1), 61–65. DOI
• Garman, M.B. & Klass, M.J. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business, 53(1), 67–78. DOI
• Rogers, L.C.G. & Satchell, S.E. (1991). Estimating Variance from High, Low and Closing Prices. Annals of Applied Probability, 1(4), 504–512. DOI
• Yang, D. & Zhang, Q. (2000). Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices. Journal of Business, 73(3), 477–491. DOI
• Wilder, J.W. (1978). New Concepts in Technical Trading Systems. Trend Research.

💮 Libraries Used
VolatilityToolkit Library — Range-based estimators, smoothing, and aggregation functions
FiltersToolkit Library — Advanced smoothing filters (Super Smoother, Ultimate Smoother, BiQuad, etc.)
ColourUtilities Library — Colour palette management and gradient calculations

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.