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 Trend Cross Strategy TemplateToday I am sharing with the community trend cross strategy template that incorporates any combination of over 20 built in indicators. Some of these indicators are in the Pine library, and some have been custom coded and contributed over time by the beloved Pine Coder community. Identifying a trend cross is a common trend following strategy and a common custom-code request from the community. Using this template, users can now select from over 400 different potential trend combinations and setup alerts without any custom coding required. This Multi-Trend cross template has a very inclusive library of trend calculations/indicators built-in, and will plot any of the 20+ indicators/trends that you can select in the settings.
How it works : Simple trend cross strategies go long when the fast trend crosses over the slow trend, and/or go short when the fast trend crosses under the slow trend. Options for either trend direction are built-in to this strategy template. The script is also coded in a way that allows you to enable/modify pyramid settings and scale into a position over time after a trend has crossed.
Use cases : These types of strategies can reduce the volatility of returns and can help avoid large market downswings. For instance, those running a longer term trend-cross strategy may have not realized half the down swing of the bear markets or crashes in 02', 08', 20', etc. However, in other years, they may have exited the market from time to time at unfavorable points that didn't end up being a down turn, or at times the market was ranging sideways. Some also use them to reduce volatility and then add leverage to attempt to beat buy/hold of the underlying asset within an acceptable drawdown threshold.
Special thanks to @Duyck, @everget, @KivancOzbilgic and @LazyBear for coding and contributing earlier versions of some of these custom indicators in Pine.
This script incorporates all of the following indicators. Each of them can be selected and modified from within the indicator settings:
ALMA - Arnaud Legoux Moving Average
DEMA - Double Exponential Moving Average
DSMA - Deviation Scaled Moving Average - Contributed by Everget
EMA - Exponential Moving Average
HMA - Hull Moving Average
JMA - Jurik Moving Average - Contributed by Everget
KAMA - Kaufman's Adaptive Moving Average - Contributed by Everget
LSMA - Linear Regression , Least Squares Moving Average
RMA - Relative Moving Average
SMA - Simple Moving Average
SMMA - Smoothed Moving Average
Price Source - Plotted based on source selection
TEMA - Triple Exponential Moving Average
TMA - Triangular Moving Average
VAMA - Volume Adjusted Moving Average - Contributed by Duyck
VIDYA - Variable Index Dynamic Average - Contributed by KivancOzbilgic
VMA - Variable Moving Average - Contributed by LazyBear
VWMA - Volume Weighted Moving Average
WMA - Weighted Moving Average
WWMA - Welles Wilder's Moving Average
ZLEMA - Zero Lag Exponential Moving Average - Contributed by KivancOzbilgic
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!
VIDYA Trend StrategyOne of the most common messages I get is people reaching out asking for quantitative strategies that trade cryptocurrency. This has compelled me to write this script and article, to help provide a quantitative/technical perspective on why I believe most strategies people write for crypto fail catastrophically, and how one might build measures within their strategies that help reduce the risk of that happening. For those that don't trade crypto, know that these approaches are applicable to any market.
I will start off by qualifying up that I mainly trade stocks and ETFs, and I believe that if you trade crypto, you should only be playing with money you are okay with losing. Most published crypto strategies I have seen "work" when the market is going up, and fail catastrophically when it is not. There are far more people trying to sell you a strategy than there are people providing 5-10+ year backtest results on their strategies, with slippage and commissions included, showing how they generated alpha and beat buy/hold. I understand that this community has some really talented people that can create some really awesome things, but I am saying that the vast majority of what you find on the internet will not be strategies that create alpha over the long term.
So, why do so many of these strategies fail?
There is an assumption many people make that cryptocurrency will act just like stocks and ETFs, and it does not. ETF returns have more of a Gaussian probability distribution. Because of this, ETFs have a short term mean reverting behavior that can be capitalized on consistently. Many technical indicators are built to take advantage of this on the equities market. Many people apply them to crypto. Many of those people are drawn down 60-70% right now while there are mean reversion strategies up YTD on equities, even though the equities market is down. Crypto has many more "tail events" that occur 3-4+ standard deviations from the mean.
There is a correlation in many equities and ETF markets for how long an asset continues to do well when it is currently doing well. This is known as momentum, and that correlation and time-horizon is different for different assets. Many technical indicators are built based on this behavior, and then people apply them to cryptocurrency with little risk management assuming they behave the same and and on the same time horizon, without pulling in the statistics to verify if that is actually the case. They do not.
People do not take into account the brokerage commissions and slippage. Brokerage commissions are particularly high with cryptocurrency. The irony here isn't lost to me. When you factor in trading costs, it blows up most short-term trading strategies that might otherwise look profitable.
There is an assumption that it will "always come back" and that you "HODL" through the crash and "buy more." This is why Three Arrows Capital, a $10 billion dollar crypto hedge fund is now in bankruptcy, and no one can find the owners. This is also why many that trade crypto are drawn down 60-70% right now. There are bad risk practices in place, like thinking the martingale gambling strategy is the same as dollar cost averaging while also using those terms interchangeably. They are not the same. The 1st will blow up your trade account, and the 2nd will reduce timing risk. Many people are systematically blowing up their trade accounts/strategies by using martingale and calling it dollar cost averaging. The more risk you are exposing yourself too, the more important your risk management strategy is.
There is an odd assumption some have that you can buy anything and win with technical/quantitative analysis. Technical analysis does not tell you what you should buy, it just tells you when. If you are running a strategy that is going long on an asset that lost 80% of its value in the last year, then your strategy is probably down. That same strategy might be up on a different asset. One might consider a different methodology on choosing assets to trade.
Lastly, most strategies are over-fit, or curve-fit. The more complicated and more parameters/settings you have in your model, the more likely it is just fit to historical data and will not perform similar in live trading. This is one of the reasons why I like simple models with few parameters. They are less likely to be over-fit to historical data. If the strategy only works with 1 set of parameters, and there isn't a range of parameters around it that create alpha, then your strategy is over-fit and is probably not suitable for live trading.
So, what can I do about all of this!?
I created the VIDYA Trend Strategy to provide an example of how one might create a basic model with a basic risk management strategy that might generate long term alpha on a volatile asset, like cryptocurrency. This is one (of many) risk management strategies that can reduce the volatility of your returns when trading any asset. I chose the Variable Index Dynamic Average (VIDYA) for this example because it's calculation filters out some market noise by taking into account the volatility of the underlying asset. I chose a trend following strategy because regressions are capturing behaviors that are not just specific to the equities market.
The more volatile an asset, the more you have to back-off the short term price movement to effectively trend-follow it. Otherwise, you are constantly buying into short term trends that don't represent the trend of the asset, then they reverse and loose money. This is why I am applying a trend following strategy to a 4 hour chart and not a 4 minute chart. It is also important to note that following these long term trends on a volatile asset exposes you to additional risk. So, how might one mitigate some of that risk?
One of the ways of reducing timing risk is scaling into a trade. This is different from "doubling down" or "trippling down." It is really a basic application of dollar cost averaging to reduce timing risk, although DCA would typically happen over a longer time period. If it is really a trend you are following, it will probably still be a trend tomorrow. Trend following strategies have lower win rates because the beginning of a trend often reverses. The more volatile the asset, the more likely that is to happen. However, we can reduce risk of buying into a reversal by slowly scaling into the trend with a small % of equity per trade.
Our example "VIDYA Trend Strategy" executes this by looking at a medium-term, volatility adjusted trend on a 4 hour chart. The script scales into it with 4% of the account equity every 4-hours that the trend is still up. This means you become fully invested after 25 trades/bars. It also means that early in the trade, when you might be more likely to experience a reversal, most of your account equity is not invested and those losses are much smaller. The script sells 100% of the position when it detects a trend reversal. The slower you scale into a trade, the less volatile your equity curve will be. This model also includes slippage and commissions that you can adjust under the "settings" menu.
This fundamental concept of reducing timing risk by scaling into a trade can be applied to any market.
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!
Gap Reversion StrategyToday I am releasing to the community an original short-term, high-probability gap trading strategy, backed by a 20 year backtest. This strategy capitalizes on the mean reverting behavior of equity ETFs, which is largely driven by fear in the market. The strategy buys into that fear at a level that has historically mean reverted within ~5 days. Larry Connors has published useful research and variations of strategies based on this behavior that I would recommend any quantitative trader read.
What it does:
This strategy, for 1 day charts on equity ETFs, looks for an overnight gap down when the RSI is also in/near an oversold position. Then, it places a limit order further below the opening of the gapped-down day. It then exits the position based on a higher RSI level. The limit buy order is cancelled if the price doesn't reach your limit price that day. So, the larger you make the gap and limit %, the less signals you will have.
Features:
Inputs to allow the adjustment of the limit order %, the gap %, and the RSI entry/exit levels.
An option to have the limit order be based on a % of ATR instead of a % of asset price.
An optional filter that can turn-off trades when the VIX is unusually high.
A built in stop.
Built in alerts.
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!
Overnight Gap AnalysisThere is a wide range of opinion on holding positions overnight due to gap risk. So, out of curiosity, I coded this analysis as a strategy to see what the result of only holding a position overnight on an asset would be. The results really surprised me. The script backtests 10+ years, and here are the findings:
Holding a position for 1 hour bar overnight on QQQ since January 2010 results in a 545% return. QQQ's entire return holding through the same period is 643%
The max equity drawdown on holding that position overnight is lower then the buy/hold drawdown on the underlying asset.
It doesn't matter if the last bar of the day is green or red, the results are similar.
It doesn't matter if it is a bull or bear market. Filtering the script to only trade when the price is above the 200-day moving average actually reduces its return from 545% to 301%, though it does also reduce drawdown.
I see similar patterns when applying the script to other index ETFs. Applying it to leveraged index ETFs can end up beating buy/hold of the underlying index.
Since this script holds through the 1st bar of the day, this could also speak to a day-opening price pattern
The default inputs are for the script to be applied to 1 hour charts only that have 7 bars on the chart per day. You can apply it to other chart types, but must follow the instructions below for it to work properly.
What the script is doing :
This script is buying the close of the last bar of the day and closing the trade at the close of the next bar. So, all trades are being held for 1 bar. By default, the script is setup for use on a 1hr chart that has 7 bars per day. If you try to apply it to a different timeframe, you will need to adjust the count of the last bar of the day with the script input. I.e. There are 7 bars per day on an hour chart on US Stocks/ETFs, so the input is set to 7 by default.
Other ways this script can be used :
This script can also test the result of holding a position over any 1 bar in the day using that same input. For instance, on an hour chart you can input 6 on the script input, and it will model buying the close of the 6th bar of the day while selling on the close of the next bar. I used this out of curiosity to model what only holding the last bar of the day would result in. On average, you lose money on the last bar every day.
The irony here is that the root cause of this last bar of the day losing may be people selling their positions at the end of day so that they aren't exposed to overnight gap risk.
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!
R3 ETF StrategyThis strategy is a modification of the “R3 Strategy” from the book "High Probability ETF Trading" by Larry Connors and Cesar Alvarez. This RSI strategy is for a 1-day time-frame and has these 3 simple rules:
Criteria:
The price must be above the 200 day moving average.
The 2-period (day) RSI drops 3 days in a row.
The 2-period RSI must have been below 60 3 days ago and below 10 today.
Entry and Exit:
If the 3 rules above are true, then buy on the close of the current day.
Exit on the day's close when the RSI crosses above 70.
How it works :
The Strategy will buy when the buy conditions above are true. The strategy will sell when the RSI crosses above 70. The RSI period/length, and RSI entry/exit criteria thresholds have all been coded to be adjustable with inputs.
Plots :
Blue line = 200 Day EMA (Used as Entry Criteria)
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!
ETF 3-Day Reversion StrategyIntroduction: This strategy is a modification of the “3-day Mean Reversion Strategy” from the book "High Probability ETF Trading" by Larry Connors and Cesar Alvarez. In the book, the authors discuss a high-probability ETF mean reversion strategy for a 1-day time-frame with these simple rules:
The price must be above the 200 day SMA and below the 5 day SMA.
The low of today must be lower than the low of yesterday (must be true for 3 consecutive days)
The high of today must be lower than the high of yesterday (must be true for 3 consecutive days)
If the 3 rules above are true, then buy on the close of the current day.
Exit when the closing price crosses above the 5 day SMA.
In practice and in backtesting, I’ve found that the strategy consistently works better when using an EMA for the trend-line instead of an SMA. So, this script uses an EMA for the trend-line. I’ve also made the length of the exit EMA adjustable.
How it works:
The Strategy will buy when the buy conditions above are true. The strategy will sell when the closing price crosses over the Exit Moving Average
Plots:
Green line = Exit Moving Average (Default 5 Day EMA)
Blue line = 5 Day EMA (Used as Entry Criteria)
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!
Multi MA Trend Following Strategy TemplateTrend following is one of the better known technical trading strategies. But, which trend should you follow? Today I am sharing with the community a trend following template script that includes a selection of over 20 different trends / regressions. Some of these are in the Pine library, and some have been custom coded and contributed over time by the beloved Pine Coder community.
How it works:
This template will plot any of the 20+ trends that you can select in the settings. The strategy component will buy if the trend line is moving up, and will sell if it moves down. If the line is green that indicates that the trend is higher than the prior bar. If the line is red that indicates that the trend is lower than the prior bar. This script is different from many moving average scripts in that it follows the trend itself and doesn't look for a cross of multiple trends.
How to use it:
When wanting to trend follow an instrument, you can use this template to help identify what approach you might want to take and/or which indicator you might want to use. You can also modify the strategy as you see fit and make use of the 20+ incorporated indicators. Incorporate your trade and risk management strategy, or use it as an indicator.
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. Even though this example script might beat buy and hold over the back-test time-frame, I wouldn't advise using it as a stand-alone strategy without significant additions/modifications to the strategy and risk management functions.
Low-High-Trend StrategyWhen asked what the key to successful investing was, Warren Buffet famously said “buy low, sell high.” Was he onto something? Today I am sharing with the community a simple “buy low, sell high” strategy with an optional trend filter and take-profit target. I’ve found that this strategy works well in a variety of markets but has a higher tendency to out-perform buy & hold in markets that are ranging sideways.
How it works:
The strategy tracks the highest and lowest price over the last X number of bars (you select the look-back period). The highest price line is plotted in green and the lowest price line is potted in red. If the price crosses over the lowest price in the last X number of bars, then a buy signal is generated. Exit options include a take-profit % or selling when the price crosses over the highest price in the last X amount of bars. I.e. “Buy low, sell high.” An EMA is also plotted as a blue trend line, and there is an option to only trade if the price is above the EMA trend line.
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. Even though this example script beats buy and hold over the back-test time-frame, I wouldn't advise using it as a stand-alone strategy without significant additions/modifications to the strategy and risk management functions. In this example the script is being used as a medium-term strategy with just 10% leverage over account equity, a $25k start balance, and back-testing 10+ years. Modifiable slippage and commissions are included in the model.
Green line = Highest price in the look-back period
Red line = Lowest price in the look-back period
Blue line = EMA Trend
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.