Drawdown Dynamics IndicatorDescription :
The Drawdown Dynamics Indicator is a straightforward tool that offers insights into three critical aspects of an asset’s financial performance: Total Max Drawdown, Rolling Period Max Drawdown, and Current Max Drawdown. Inside of the indicator, you can select to view either the rolling period max drawdown or the all-time max drawdown. This is represented by the gray line. The blue line represents the asset's current drawdown.
Rolling Period Max Drawdown is more about a snapshot view, highlighting the maximum loss from a peak to a trough for an adjustable rolling time frame. This is a feature not available with other indicators that exist on TradingView.
Total Max Drawdown gives a broad view, showcasing the all-time deepest decline in an asset’s value.
Current Max Drawdown offers a live update, focusing on the asset's present phase and how it's performing in real-time.
Practical Uses :
The utility of this indicator becomes evident when you start exploring the risks and performance metrics of assets. A notable use of this indicator is in comparing the drawdowns of a trading strategy against the inherent drawdowns of an asset. It helps in painting a clearer picture of risk and performance of both the asset and the strategy.
Risk Understanding : By comparing the strategy drawdown to the asset drawdown, traders get to understand if the risk they’re taking aligns with the asset’s natural risk behavior.
Evaluating Strategy’s Strength : If a strategy can weather the storms of the asset's natural drawdown phases and come out relatively unscathed, it can speak to its strength.
Performance Comparison : It also acts as a benchmark tool. Traders can pit different strategies against each other, using the asset’s drawdown as a baseline, to see which one manages risks better.
Disclaimer : This is not financial advice. Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Tradeautomation
S&P 500 Quandl Data & RatiosTradingView has a little-known integration that allows you to pull in 3rd party data-sets from Nasdaq Data Link, also known as Quandl. Today, I am open-sourcing for the community an indicator that uses the Quandl integration to pull in historical data and ratios on the S&P500. I originally coded this to study macro P/E ratios during peaks and troughs of boom/bust cycles.
The indicator pulls in each of the following datasets, as defined and provided by Quandl. The user can select which datasets to pull in using the indicator settings:
Dividend Yield : S&P 500 dividend yield (12 month dividend per share)/price. Yields following June 2022 (including the current yield) are estimated based on 12 month dividends through June 2022, as reported by S&P. Sources: Standard & Poor's for current S&P 500 Dividend Yield. Robert Shiller and his book Irrational Exuberance for historic S&P 500 Dividend Yields.
Price Earning Ratio : Price to earnings ratio, based on trailing twelve month as reported earnings. Current PE is estimated from latest reported earnings and current market price. Source: Robert Shiller and his book Irrational Exuberance for historic S&P 500 PE Ratio.
CAPE/Shiller PE Ratio : Shiller PE ratio for the S&P 500. Price earnings ratio is based on average inflation-adjusted earnings from the previous 10 years, known as the Cyclically Adjusted PE Ratio (CAPE Ratio), Shiller PE Ratio, or PE 10 FAQ. Data courtesy of Robert Shiller from his book, Irrational Exuberance.
Earnings Yield : S&P 500 Earnings Yield. Earnings Yield = trailing 12 month earnings divided by index price (or inverse PE) Yields following March, 2022 (including current yield) are estimated based on 12 month earnings through March, 2022 the latest reported by S&P. Source: Standard & Poor's
Price Book Ratio : S&P 500 price to book value ratio. Current price to book ratio is estimated based on current market price and S&P 500 book value as of March, 2022 the latest reported by S&P. Source: Standard & Poor's
Price Sales Ratio : S&P 500 Price to Sales Ratio (P/S or Price to Revenue). Current price to sales ratio is estimated based on current market price and 12 month sales ending March, 2022 the latest reported by S&P. Source: Standard & Poor's
Inflation Adjusted SP500 : Inflation adjusted SP500. Other than the current price, all prices are monthly average closing prices. Sources: Standard & Poor's Robert Shiller and his book Irrational Exuberance for historic S&P 500 prices, and historic CPIs.
Revenue Per Share : Trailing twelve month S&P 500 Sales Per Share (S&P 500 Revenue Per Share) non-inflation adjusted current dollars. Source: Standard & Poor's
Earnings Per Share : S&P 500 Earnings Per Share. 12-month real earnings per share inflation adjusted, constant August, 2022 dollars. Sources: Standard & Poor's for current S&P 500 Earnings. Robert Shiller and his book Irrational Exuberance for historic S&P 500 Earnings.
Disclaimer: This is not financial advice. Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Multi Asset + Correlation OverlayFrom time to time, you may want to overlay multiple assets on the same chart instead of using multi-chart views. This can be a much cleaner way of viewing and comparing multiple assets. There is some functionality built into TradingView that lets you do this to a certain extent, but I wanted additional options, correlation labeling and ways to adjust the overlay location. So, today I am releasing to the community my Multi-Asset + Correlation Overlay script / indicator.
What is does: This script allows you to overlay the price of any ticker onto your chart. It also labels the line with the ticker name, and calculates / labels the correlation coefficient of your newly overlayed asset.
How to use it: Add the indicator to your chart. Then, go into the indicator settings to set the ticker of the asset you want to pull in along with how you want to "offset" it. Your 2 tickers may not be priced near each-other, so the offset setting allows you to pull the ticker you added up/down to better visually align with your chart's price range/layout. For instance, if the asset you added is priced $400 higher than the underlying chart price, you may want to set the offset to -400.
If you would like to add multiple tickers and multiple overlays, you can do that by just adding the indicator to your chart more than once. The color is adjustable, and the ticker of the asset will print to the right of the line representing the asset price. The script also calculates the correlation coefficient between the ticker overlay and the underlying chart asset. The correlation coefficient prints to the right of the ticker.
Inflation Rate of ChangeInflation and the Fed interest rate impacts all corners of the economy. Today I am releasing to the community an indicator that measures the rate of change of inflation with historical data back to ~1950. I built this to study the historical market impacts of inflation and changes to the Fed rate (see separate indicator I published for Fed Funds Rate here ).
What this indicator does:
This indicator pulls in Consumer Price Index data and applies a rate of change formula to it. The output is measured as a percentage. I.e. 7 would mean a 7% rate of change over the look-back period.
Options in the indicator:
You can change the amount of bars back it uses to calculate rate of change. By default it is set to 253, which would be looking 1 year back on a normal stock market day chart. If you are on a month chart, you would input 12 there to look 1 year back, etc.
There are also different versions of the CPI that you can select with a drop-down input to pull in different inflation measures:
FRED:CPIAUCSL = Urban Consumers, All Items (this is the default data it pulls, and is a common way to measure inflation)
FRED:CPIUFDNS = Food
FRED:CPIHOSNS = Housing
FRED:CPIENGSL = Energy
Disclaimer: Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Fed Funds Rate IndicatorWith the current level of inflation and the Fed outlook on interest rates, it inspired some studying on the relationship between Fed rate increases and stock market performance over periods of inflation. Today I am releasing to the community an indicator that will show you the Fed Funds Rate historically. You can add it to any chart or index to study the impact of Fed Funds Rate changes.
There are 2 options for the indicator data source you can select in the indicator settings. FRED:EFFR data updates daily but only goes back ~20 years. FRED:FEDFUNDS data only updates monthly but goes back to 1947.
Disclaimer: Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Relative Standard DeviationStandard Deviation is a common measure of volatility (the dispersion of data relative to its mean). However, when using it as an indicator, it can be more useful at times to know the deviation relative to the price as a percentage versus the hard value. This normalizes the data so that it is easier to compare the deviation of different assets. By definition, standard deviation is the square root of the variance, and it is how far the price is from the mean 68.2% of the time when there is normative distribution.
What it does : This indicator will tell you the standard deviation of the asset relative to its price (as a %), but also has the option to plot the normal (population) standard deviation.
Example use case : The regular standard deviation of Asset A is $12 and Asset B is $10. Which one is more volatile? Well, it depends on the asset price. If asset A just closed at $900 and asset B just closed at $30, that makes a big difference. In this instance Asset A $12/$900=1.33% (standard deviation relative to the asset price). Asset B $10/$30=33.33% (standard deviation relative to the asset price). Using a normal standard deviation indicator, you would just see that the standard deviation of Asset A is higher as a hard dollar value, when the reality is that Asset A is much less volatile.
How to use it : This indicator plots a blue line by default that is the Relative Standard Deviation of the asset compared to the asset price (a %). There is also an option to turn on / plot regular (population) Standard Deviation, which will plot as a purple line. The mean length used for the average, and the lookback period that the indicator uses to calculate, are both adjustable with inputs.
Nasdaq VXN Volatility Warning IndicatorToday I am sharing with the community a volatility indicator that uses the Nasdaq VXN Volatility Index to help you or your algorithms avoid black swan events. This is a similar the indicator I published last week that uses the SP500 VIX, but this indicator uses the Nasdaq VXN and can help inform strategies on the Nasdaq index or Nasdaq derivative instruments.
Variance is most commonly used in statistics to derive standard deviation (with its square root). It does have another practical application, and that is to identify outliers in a sample of data. Variance is defined as the squared difference between a value and its mean. Calculating that squared difference means that the farther away the value is from the mean, the more the variance will grow (exponentially). This exponential difference makes outliers in the variance data more apparent.
Why does this matter?
There are assets or indices that exist in the stock market that might make us adjust our trading strategy if they are behaving in an unusual way. In some instances, we can use variance to identify that behavior and inform our strategy.
Is that really possible?
Let’s look at the relationship between VXN and the Nasdaq100 as an example. If you trade a Nasdaq index with a mean reversion strategy or algorithm, you know that they typically do best in times of volatility . These strategies essentially attempt to “call bottom” on a pullback. Their downside is that sometimes a pullback turns into a regime change, or a black swan event. The other downside is that there is no logical tight stop that actually increases their performance, so when they lose they tend to lose big.
So that begs the question, how might one quantitatively identify if this dip could turn into a regime change or black swan event?
The Nasdaq Volatility Index ( VXN ) uses options data to identify, on a large scale, what investors overall expect the market to do in the near future. The Volatility Index spikes in times of uncertainty and when investors expect the market to go down. However, during a black swan event, historically the VXN has spiked a lot harder. We can use variance here to identify if a spike in the VXN exceeds our threshold for a normal market pullback, and potentially avoid entering trades for a period of time (I.e. maybe we don’t buy that dip).
Does this actually work?
In backtesting, this cut the drawdown of my index reversion strategies in half. It also cuts out some good trades (because high investor fear isn’t always indicative of a regime change or black swan event). But, I’ll happily lose out on some good trades in exchange for half the drawdown. Lets look at some examples of periods of time that trades could have been avoided using this strategy/indicator:
Example 1 – With the Volatility Warning Indicator, the mean reversion strategy could have avoided repeatedly buying this pullback that led to this asset losing over 75% of its value:
Example 2 - June 2018 to June 2019 - With the Volatility Warning Indicator, the drawdown during this period reduces from 22% to 11%, and the overall returns increase from -8% to +3%
How do you use this indicator?
This indicator determines the variance of VXN against a long term mean. If the variance of the VXN spikes over an input threshold, the indicator goes up. The indicator will remain up for a defined period of bars/time after the variance returns below the threshold. I have included default values I’ve found to be significant for a short-term mean-reversion strategy, but your inputs might depend on your risk tolerance and strategy time-horizon. The default values are for 1hr VXN data/charts. It will pull in variance data for the VXN regardless of which chart the indicator is applied to.
Disclaimer: Open-source scripts I publish in the community are largely meant to spark ideas or be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
S&P500 VIX Volatility Warning IndicatorToday I am sharing with the community a volatility indicator that can help you or your algorithms avoid black swan events. Variance is most commonly used in statistics to derive standard deviation (with its square root). It does have another practical application, and that is to identify outliers in a sample of data. Variance in statistics is defined as the squared difference between a value and its mean. Calculating that squared difference means that the farther away the value is from the mean, the more the variance will grow (exponentially). This exponential difference makes outliers in the variance data more apparent.
Why does this matter?
There are assets or indices that exist in the stock market that might make us adjust our trading strategy if they are behaving in an unusual way. In some instances, we can use variance to identify that behavior and inform our strategy.
Is that really possible?
Let’s look at the relationship between VIX and the S&P500 as an example. If you trade an S&P500 index with a mean reversion strategy or algorithm, you know that they typically do best in times of volatility. These strategies essentially attempt to “call bottom” on a pullback. Their downside is that sometimes a pullback turns into a regime change, or a black swan event. The other downside is that there is no logical tight stop that actually increases their performance, so when they lose they tend to lose big.
So that begs the question, how might one quantitatively identify if this dip could turn into a regime change or black swan event?
The CBOE Volatility Index (VIX) uses options data to identify, on a large scale, what investors overall expect the market to do in the near future. The Volatility Index spikes in times of uncertainty and when investors expect the market to go down. However, during a black swan event, the VIX spikes a lot harder. We can use variance here to identify if a spike in the VIX exceeds our threshold for a normal market pullback, and potentially avoid entering trades for a period of time (I.e. maybe we don’t buy that dip).
Does this actually work?
In backtesting, this cut the drawdown of my index reversion strategies in half. It also cuts out some good trades (because high investor fear isn’t always indicative of a regime change or black swan event). But, I’ll happily lose out on some good trades in exchange for half the drawdown. Lets look at some examples of periods of time that trades could have been avoided using this strategy/indicator:
Example 1 – With the Volatility Warning Indicator, the mean reversion strategy could have avoided repeatedly buying this pullback that led to SPXL losing over 75% of its value:
Example 2 - June 2018 to June 2019 - With the Volatility Warning Indicator, the drawdown during this period reduces from 22% to 11%, and the overall returns increase from -8% to +3%
How do you use this indicator?
This indicator determines the variance of the VIX against a long term mean. If the variance of the VIX spikes over an input threshold, the indicator goes up. The indicator will remain up for a defined period of bars/time after the variance returns below the threshold. I have included default values I’ve found to be significant for a short-term mean-reversion strategy, but your inputs might depend on your risk tolerance and strategy time-horizon. The default values are for 1hr VIX data. It will pull in variance data for the VIX regardless of which chart the indicator is applied to.
Disclaimer : Open-source scripts I publish in the community are largely meant to spark ideas or be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
ATR Trailing Stop v5 One of my favorite stops is the ATR Trailing Stop-loss. With the implementation of PineScript v5, a code update was needed in order to use this stop/exit-strategy with newer strategy scripts. A timeframe selector that was not featured on earlier versions is also included. This new version can be plugged into PineScript v5 strategies, and also has a simpler/cleaner code that makes the code logic easier to follow than prior versions.
For those that are unfamiliar with the ATR Trailing Stop exit strategy; it is a trailing stop that takes into account the volatility of the underlying asset by trailing the price series using a multiple of the Average True Range (ATR). In practice I’ve found that this exit can be more effective than traditional trailing stops, depending on the volatility of the asset you are trading. More detailed information can be found at www.stockopedia.com
How do I use it? Add it to your chart as an indicator to visualize where the ATR stop would be with your settings. Or, copy and add it to your v5 strategy with the addition of a ta.crossunder(close, ATRTrailingStop) or ta.crossover(close, ATRTrailingStop) function. Special thanks and credit to HPotter who coded an earlier version of this in pine!
Yield Curve Inversion IndicatorIntroduction
The last time (as of this publishing) that this indicator detected an inverted interest rate yield curve was on February 20th, 2020 at 12:30pm EST, the afternoon before the S&P500 began one of its largest crashes in US history. The vast majority of major economic recessions since the 1950's have been preceded by an interest rate yield curve inversion. I created this indicator originally as an input to study the impacts of more conservative risk management on quantitative trading strategies following a yield curve inversion event. It is being shared with the community as a quick indicator to check to see the comparative status of short term and long term interest rates, and as an indicator where you can easily check to see if we are experiencing an inverted yield curve in real-time.
Background of the significance of an inverted yield curve:
"What an inverted yield curve really means is that most investors believe that short-term interest rates are going to fall sharply at some point in the future. As a practical matter, recessions usually cause interest rates to fall. Historically, inversions of the yield curve have preceded recessions in the U.S. Due to this historical correlation, the yield curve is often seen as a way to predict the turning points of the business cycle. When the yield curve inverts, short-term interest rates become higher than long-term rates. This type of yield curve is the rarest of the three main curve types and is considered to be a predictor of economic recession. Because of the rarity of yield curve inversions, they typically draw attention from all parts of the financial world." (www.investopedia.com)
Settings and Usage
This indicator pulls in pricing data from tickers that represent short term and long term interest rates, and compares them. The red line represents short term interest rates, and the green line represents long term interest rates. When the red line is above the green line, it indicates that we are experiencing a yield curve inversion. Small blue crosses also appear on the bottom of the indicator during an inversion to further highlight the event visually. This indicator pulls in the same information on the same two interest rate tickers regardless of what chart it is applied to.
Other Thoughts
This script uses the f_secureSecurity function as a best practice. For those that are versed in PineScript, code from this indicator could be adapted to be applied to an interest rate chart that allows custom alerts to be created the moment that there is an inverted interest rate yield curve.