[Pandora] Vast Volatility Treasure TroveINTRODUCTION:
Volatility enthusiasts, prepare for VICTORY on this day of July 4th, 2024! This is my "Vast Volatility Treasure Trove," intended mostly for educational purposes, yet these functions will also exhibit versatility when combined with other algorithms to garner statistical excellence. Once again, I am now ripping the lid off of Pandora's box... of volatility. Inside this script is a 'vast' collection of volatility estimators, reflecting the indicators name. Whether you are a seasoned trader destined to navigate financial strife or an eagerly curious learner, this script offers a comprehensive toolkit for a broad spectrum of volatility analysis. Enjoy your journey through the realm of market volatility with this code!
WHAT IS MARKET VOLATILITY?:
Market volatility refers to various fluctuations in the value of a financial market or asset over a period of time, often characterized by occasional rapid and significant deviations in price. During periods of greater market volatility, evolving conditions of prices can move rapidly in either direction, creating uncertainty for investors with results of sharp declines as well as rapid gains. However, market volatility is a typical aspect expected in financial markets that can also present opportunities for informed decision-making and potential benefits from the price flux.
SCRIPT INTENTION:
Volatility is assuredly omnipresent, waxing and waning in magnitude, and some readers have every intention of studying and/or measuring it. This script serves as an all-in-one armada of volatility estimators for TradingView members. I set out to provide a diverse set of tools to analyze and interpret market volatility, offering volatile insights, and aid with the development of robust trading indicators and strategies.
In today's fast-paced financial markets, understanding and quantifying volatility is informative for both seasoned traders and novice investors. This script is designed to empower users by equipping them with a comprehensive suite of volatility estimators. Each function within this script has been meticulously crafted to address various aspects of volatility, from traditional methods like Garman-Klass and Parkinson to more advanced techniques like Yang-Zhang and my custom experimental algorithms.
Ultimately, this script is more than just a collection of functions. It is a gateway to a deeper understanding of market volatility and a valuable resource for anyone committed to mastering the complexities of financial markets.
SCRIPT CONTENTS:
This script includes a variety of functions designed to measure and analyze market volatility. Where applicable, an input checkbox option provides an unbiased/biased estimate. Below is a brief description of each function in the original order they appear as code upon first publish:
Parkinson Volatility - Estimates volatility emphasizing the high and low range movements.
Alternate Parkinson Volatility - Simpler version of the original Parkinson Volatility that I realized.
Garman-Klass Volatility - Estimates volatility based on high, low, open, and close prices using a formula that adjusts for biases in price dynamics.
Rogers-Satchell-Yoon Volatility #1 - Estimates volatility based on logarithmic differences between high, low, open, and close values.
Rogers-Satchell-Yoon Volatility #2 - Similar estimate to Rogers-Satchell with the same result via an alternate formulation of volatility.
Yang-Zhang Volatility - An advanced volatility estimate combining both strengths of the Garman-Klass and Rogers-Satchell estimators, with weights determined by an alpha parameter.
Yang-Zhang (Modified) Volatility - My experimental modification slightly different from the Yang-Zhang formula with improved computational efficiency.
Selectable Volatility - Basic customizable volatility calculation based on the logarithmic difference between selected numerator and denominator prices (e.g., open, high, low, close).
Close-to-Close Volatility - Estimates volatility using the logarithmic difference between consecutive closing prices. Specifically applicable to data sources without open, high, and low prices.
Open-to-Close Volatility - (Overnight Volatility): Estimates volatility based on the logarithmic difference between the opening price and the last closing price emphasizing overnight gaps.
Hilo Volatility - Estimates volatility using a method similar to Parkinson's method, which considers the logarithm of the high and low prices.
Vantage Volatility - My experimental custom 'vantage' method to estimate volatility similar to Yang-Zhang, which incorporates various factors (Alpha, Beta, Gamma) to generate a weighted logarithmic calculation. This may be a volatility advantage or disadvantage, hence it's name.
Schwert Volatility - Estimates volatility based on arithmetic returns.
Historical Volatility - Estimates volatility considering logarithmic returns.
Annualized Historical Volatility - Estimates annualized volatility using logarithmic returns, adjusted for the number of trading days in a year.
If I omitted any other known varieties, detailed requests for future consideration can be made below for their inclusion into this script within future versions...
BONUS ALGORITHMS:
This script also includes several experimental and bonus functions that push the boundaries of volatility analysis as I understand it. These functions are designed to provide additional insights and also are my ideal notions for traders looking to explore other methods of volatility measurement.
VOLATILITY APPLICATIONS:
Volatility estimators serve a common role across various facets of trading and financial analysis, offering insights into market behavior. These tools are already in instrumental with enhancing risk management practices by providing a deeper understanding of market dynamics and the inherent uncertainty in asset prices. With volatility estimators, traders can effectively quantifying market risk and adjust their strategies accordingly, optimizing portfolio performance and mitigating potential losses. Additionally, volatility estimations may serve as indication for detecting overbought or oversold market conditions, offering probabilistic insights that could inform strategic decisions at turning points. This script
distinctly offers a variety of volatility estimators to navigate intricate financial terrains with informed judgment to address challenges of strategic planning.
CODE REUSE:
You don't have to ask for my permission to use/reuse these functions in your published scripts, simply because I have better things to do than answer requests for the reuse of these functions.
Notice: Unfortunately, I will not provide any integration support into member's projects at all. I have my own projects that require way too much of my day already.
Yangzhang
GKYZ-Filtered, Non-Linear Regression MA [Loxx]GKYZ-Filtered, Non-Linear Regression MA is a Non-Linear Regression of price moving average. Use this as you would any other moving average. This also includes a Garman-Klass-Yang-Zhang Historical Volatility Filter to reduce noise.
What is Non-Linear Regression?
In statistics, nonlinear regression is a form of regression analysis in which observational data are modeled by a function which is a nonlinear combination of the model parameters and depends on one or more independent variables. The data are fitted by a method of successive approximations.
What is Garman-Klass-Yang-Zhang Historical Volatility?
Yang and Zhang derived an extension to the Garman Klass historical volatility estimator that allows for opening jumps. It assumes Brownian motion with zero drift. This is currently the preferred version of open-high-low-close volatility estimator for zero drift and has an efficiency of 8 times the classic close-to-close estimator. Note that when the drift is nonzero, but instead relative large to the volatility , this estimator will tend to overestimate the volatility . The Garman-Klass-Yang-Zhang Historical Volatility calculation is as follows:
GKYZHV = sqrt((Z/n) * sum((log(open(k)/close( k-1 )))^2 + (0.5*(log(high(k)/low(k)))^2) - (2*log(2) - 1)*(log(close(k)/open(2:end)))^2))
Included
Alerts
Signals
Loxx's Expanded Source Types
Bar coloring
JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]JFD-Adaptive, GKYZ-Filtered KAMA is a Kaufman Adaptive Moving Average with the option to make it Jurik Fractal Dimension Adaptive. This also includes a Garman-Klass-Yang-Zhang Historical Volatility Filter to reduce noise.
What is KAMA?
Developed by Perry Kaufman, Kaufman's Adaptive Moving Average ( KAMA ) is a moving average designed to account for market noise or volatility . KAMA will closely follow prices when the price swings are relatively small and the noise is low. KAMA will adjust when the price swings widen and follow prices from a greater distance. This trend-following indicator can be used to identify the overall trend, time turning points and filter price movements.
What is Jurik Fractal Dimension?
There is a weak and a strong way to measure the random quality of a time series.
The weak way is to use the random walk index ( RWI ). You can download it from the Omega web site. It makes the assumption that the market is moving randomly with an average distance D per move and proposes an amount the market should have changed over N bars of time. If the market has traveled less, then the action is considered random, otherwise it's considered trending.
The problem with this method is that taking the average distance is valid for a Normal (Gaussian) distribution of price activity. However, price action is rarely Normal, with large price jumps occuring much more frequently than a Normal distribution would expect. Consequently, big jumps throw the RWI way off, producing invalid results.
The strong way is to not make any assumption regarding the distribution of price changes and, instead, measure the fractal dimension of the time series. Fractal Dimension requires a lot of data to be accurate. If you are trading 30 minute bars, use a multi-chart where this indicator is running on 5 minute bars and you are trading on 30 minute bars.
What is Garman-Klass-Yang-Zhang Historical Volatility?
Yang and Zhang derived an extension to the Garman Klass historical volatility estimator that allows for opening jumps. It assumes Brownian motion with zero drift. This is currently the preferred version of open-high-low-close volatility estimator for zero drift and has an efficiency of 8 times the classic close-to-close estimator. Note that when the drift is nonzero, but instead relative large to the volatility , this estimator will tend to overestimate the volatility . The Garman-Klass-Yang-Zhang Historical Volatility calculation is as follows:
GKYZHV = sqrt((Z/n) * sum((log(open(k)/close( k-1 )))^2 + (0.5*(log(high(k)/low(k)))^2) - (2*log(2) - 1)*(log(close(k)/open(2:end)))^2))
Included
Alerts
Signals
Loxx's Expanded Source Types
Bar coloring
RSI-Adaptive, GKYZ-Filtered DEMA [Loxx]RSI-Adaptive, GKYZ-Filtered DEMA is a Garman-Klass-Yang-Zhang Historical Volatility Filtered, RSI-Adaptive Double Exponential Moving Average. This is an experimental indicator. The way this is calculated is by turning RSI into an alpha value that is then injected into a DEMA function to output price. Price is then filtered using GKYZ Historical volatility. This process of creating an alpha out of RSI is only relevant to EMA-based moving averages that use an alpha value for it's calculation.
What is Garman-Klass-Yang-Zhang Historical Volatility?
Yang and Zhang derived an extension to the Garman Klass historical volatility estimator that allows for opening jumps. It assumes Brownian motion with zero drift. This is currently the preferred version of open-high-low-close volatility estimator for zero drift and has an efficiency of 8 times the classic close-to-close estimator. Note that when the drift is nonzero, but instead relative large to the volatility , this estimator will tend to overestimate the volatility . The Garman-Klass-Yang-Zhang Historical Volatility calculation is as follows:
GKYZHV = sqrt((Z/n) * sum((log(open(k)/close( k-1 )))^2 + (0.5*(log(high(k)/low(k)))^2) - (2*log(2) - 1)*(log(close(k)/open(2:end)))^2))
Included
Alerts
Signals
Loxx's Expanded Source Types
Bar coloring
Garman-Klass-Yang-Zhang Historical Volatility Bands [Loxx]Garman-Klass-Yang-Zhang Historical Volatility Bands are constructed using:
Average as the middle line.
Upper and lower bands using the Garman-Klass-Yang-Zhang Historical Volatility Bands for bands calculation.
What is Garman-Klass-Yang-Zhang Historical Volatility?
Yang and Zhang derived an extension to the Garman Klass historical volatility estimator that allows for opening jumps. It assumes Brownian motion with zero drift. This is currently the preferred version of open-high-low-close volatility estimator for zero drift and has an efficiency of 8 times the classic close-to-close estimator. Note that when the drift is nonzero, but instead relative large to the volatility, this estimator will tend to overestimate the volatility. The Garman-Klass-Yang-Zhang Historical Volatility calculation is as follows:
GKYZHV = sqrt((Z/n) * sum((log(open(k)/close(k-1)))^2 + (0.5*(log(high(k)/low(k)))^2) - (2*log(2) - 1)*(log(close(k)/open(2:end)))^2))
The color of the middle line, unlike the bands colors, has 3 colors. When colors of the bands are the same, then the middle line has the same color, otherwise it's white.
Included
Alerts
Signals
Loxx's Expanded Source Types
Bar coloring
Related Indicators
Garman & Klass Estimator Historical Volatility Bands
Yang & Zheng Extension of Garman & KlassFirst off, a huge thank you to the following people:
theheirophant: www.tradingview.com
alexgrover: www.tradingview.com
NGBaltic: www.tradingview.com
This is the Yang & Zhang extension of Garman & Klass. The equation was modified to include the logarithm of the open price divided by the preceding close price. As a result, this function uses the open, high, low and close prices to estimate volatility. This modification allows the volatility estimator to account for the opening jumps, but as the original function, it assumes that the underlying follows a Brownian motion with zero drift (the historical mean return should be equal to zero). This estimator tends to overestimate the volatility when the drift is different from zero, however, for a zero drift motion, this estimator has an efficiency of eight times the classic close-to-close estimator (standard deviation).
This script allows you to transform the volatility reading. The intention of this is to be able to compare volatility across different assets and timeframes. Having a relative reading of volatility also allows you to better gauge volatility within the context of current market conditions.
For the signal lie I chose a repulsion moving average to remove choppy crossovers of the estimator and the signal. This may have been a mistake, so in the near-future I might update so that the MA can be selected. Let me know if you have any opinions either way.
References
www.rdocumentation.org
www.quantshare.com
Want to Learn?
If you'd like the opportunity to learn Pine but you have difficulty finding resources to guide you, take a look at this rudimentary list: docs.google.com
The list will be updated in the future as more people share the resources that have helped, or continue to help, them. Follow me on Twitter to keep up-to-date with the growing list of resources.
Suggestions or Questions?
Don't even kinda hesitate to forward them to me. My (metaphorical) door is always open.
OHLC Volatility Estimators by @Xel_arjonaDISCLAIMER:
The Following indicator/code IS NOT intended to be a formal investment advice or recommendation by the author, nor should be construed as such. Users will be fully responsible by their use regarding their own trading vehicles/assets.
The embedded code and ideas within this work are FREELY AND PUBLICLY available on the Web for NON LUCRATIVE ACTIVITIES and must remain as is by Creative-Commons as TradingView's regulations. Any use, copy or re-use of this code should mention it's origin as it's authorship.
WARNING NOTICE!
THE INCLUDED FUNCTION MUST BE CONSIDERED AS DEBUGING CODE The models included in the function have been taken from openly sources on the web so they could have some errors as in the calculation scheme and/or in it's programatic scheme. Debugging are welcome.
WHAT'S THIS?
Here's a full collection of candle based (compressed tick) Volatility Estimators given as a function, openly available for free, it can print IMPLIED VOLATILITY by an external symbol ticker like INDEX:VIX.
Models included in the volatility calculation function:
CLOSE TO CLOSE: This is the classic estimator by rule, sometimes referred as HISTORICAL VOLATILITY and is the must common, accepted and widely used out there. Is based on traditional Standard Deviation method derived from the logarithm return of current close from yesterday's.
ELASTIC WEIGHTED MOVING AVERAGE: This estimator has been used by RiskMetriks®. It's calculation is based on an ElasticWeightedMovingAverage Standard Deviation method derived from the logarithm return of current close from yesterday's. It can be viewed or named as an EXPONENTIAL HISTORICAL VOLATILITY model.
PARKINSON'S: The Parkinson number, or High Low Range Volatility, developed by the physicist, Michael Parkinson, in 1980 aims to estimate the Volatility of returns for a random walk using the high and low in any particular period. IVolatility.com calculates daily Parkinson values. Prices are observed on a fixed time interval. n=10, 20, 30, 60, 90, 120, 150, 180 days.
ROGERS-SATCHELL: The Rogers-Satchell function is a volatility estimator that outperforms other estimators when the underlying follows a Geometric Brownian Motion (GBM) with a drift (historical data mean returns different from zero). As a result, it provides a better volatility estimation when the underlying is trending. However, this Rogers-Satchell estimator does not account for jumps in price (Gaps). It assumes no opening jump. The function uses the open, close, high, and low price series in its calculation and it has only one parameter, which is the period to use to estimate the volatility.
YANG-ZHANG: Yang and Zhang were the first to derive an historical volatility estimator that has a minimum estimation error, is independent of the drift, and independent of opening gaps. This estimator is maximally 14 times more efficient than the close-to-close estimator.
LOGARITHMIC GARMAN-KLASS: The former is a pinescript transcript of the model defined as in iVolatility . The metric used is a combination of the overnight, high/low and open/close range. Such a volatility metric is a more efficient measure of the degree of volatility during a given day. This metric is always positive.