Keltner Channels BandsKeltner Channel Bands
Great indicator for mean reversion strategies.
Alerts you can set:
Crossover EMA
Crossunder EMA
Crossover upper band
Crossunder upper band
Crossover lower band
Crossunder lower band
Have fun!
Reversion
conditional_returnsThis script attempts to contextualize the instrument's latest return. It asks, "when a return of the same or greater magnitude occurred in the past, in the same direction, what was the following period's return?"
By default, the latest return is used. For example, on a daily chart, that would mean "today's" return. However, you can select any return you want using the "override" input.
The output table shows:
- The latest/override return, as a percentage. This is in the top left, fuchsia cell.
The first three, blue columns, show:
- The count of up and down (or positive and negative) next period returns. This shows you the sample size.
- The percentage of up/down next period returns.
- The average next-period return return, up and down, as percentages.
The next three, green columns show these same statistics, but for all returns--every period in the active date range is used. This data serves as a basis for comparison.
Note that you can select a custom date range with the "start" and "end" inputs. The corresponding area on the chart is shaded light grey, to show which data is used in the computations.
[cache_that_pass] 1m 15m Function - Weighted Standard DeviationTradingview Community,
As I progress through my journey, I have come to the realization that it is time to give back. This script isn't a life changer, but it has the building blocks for a motivated individual to optimize the parameters and have a production script ready to go.
Credit for the indicator is due to @rumpypumpydumpy
I adapted this indicator to a strategy for crypto markets. 15 minute time frame has worked best for me.
It is a standard deviation script that has 3 important user configured parameters. These 3 things are what the end user should tweak for optimum returns. They are....
1) Lookback Length - I have had luck with it set to 20, but any value from 1-1000 it will accept.
2) stopPer - Stop Loss percentage of each trade
3) takePer - Take Profit percentage of each trade
2 and 3 above are where you will see significant changes in returns by altering them and trying different percentages. An experienced pinescript programmer can take this and build on it even more. If you do, I ask that you please share the script with the community in an open-source fashion.
It also already accounts for the commission percentage of 0.075% that Binance.US uses for people who pay fees with BNB.
How it works...
It calculates a weighted standard deviation of the price for the lookback period set (so 20 candles is default). It recalculates each time a new candle is printed. It trades when price lows crossunder the bottom of that deviation channel, and sells when price highs crossover the top of that deviation channel. It works best in mid to long term sideways channels / Wyckoff accumulation periods.
Augmented Dickey–Fuller (ADF) mean reversion testThe augmented Dickey-Fuller test (ADF) is a statistical test for the tendency of a price series sample to mean revert .
The current price of a mean-reverting series may tell us something about the next move (as opposed, for example, to a geometric Brownian motion). Thus, the ADF test allows us to spot market inefficiencies and potentially exploit this information in a trading strategy.
Mathematically, the mean reversion property means that the price change in the next time period is proportional to the difference between the average price and the current price. The purpose of the ADF test is to check if this proportionality constant is zero. Accordingly, the ADF test statistic is defined as the estimated proportionality constant divided by the corresponding standard error.
In this script, the ADF test is applied in a rolling window with a user-defined lookback length. The calculated values of the ADF test statistic are plotted as a time series. The more negative the test statistic, the stronger the rejection of the hypothesis that there is no mean reversion. If the calculated test statistic is less than the critical value calculated at a certain confidence level (90%, 95%, or 99%), then the hypothesis of a mean reversion is accepted (strictly speaking, the opposite hypothesis is rejected).
Input parameters:
Source - The source of the time series being tested.
Length - The number of points in the rolling lookback window. The larger sample length makes the ADF test results more reliable.
Maximum lag - The maximum lag included in the test, that defines the order of an autoregressive process being implied in the model. Generally, a non-zero lag allows taking into account the serial correlation of price changes. When dealing with price data, a good starting point is lag 0 or lag 1.
Confidence level - The probability level at which the critical value of the ADF test statistic is calculated. If the test statistic is below the critical value, it is concluded that the sample of the price series is mean-reverting. Confidence level is calculated based on MacKinnon (2010) .
Show Infobox - If True, the results calculated for the last price bar are displayed in a table on the left.
More formal background:
Formally, the ADF test is a test for a unit root in an autoregressive process. The model implemented in this script involves a non-zero constant and zero time trend. The zero lag corresponds to the simple case of the AR(1) process, while higher order autoregressive processes AR(p) can be approached by setting the maximum lag of p. The null hypothesis is that there is a unit root, with the alternative that there is no unit root. The presence of unit roots in an autoregressive time series is characteristic for a non-stationary process. Thus, if there is no unit root, the time series sample can be concluded to be stationary, i.e., manifesting the mean-reverting property.
A few more comments:
It should be noted that the ADF test tells us only about the properties of the price series now and in the past. It does not directly say whether the mean-reverting behavior will retain in the future.
The ADF test results don't directly reveal the direction of the next price move. It only tells wether or not a mean-reverting trading strategy can be potentially applicable at the given moment of time.
The ADF test is related to another statistical test, the Hurst exponent. The latter is available on TradingView as implemented by balipour , QuantNomad and DonovanWall .
The ADF test statistics is a negative number. However, it can take positive values, which usually corresponds to trending markets (even though there is no statistical test for this case).
Rigorously, the hypothesis about the mean reversion is accepted at a given confidence level when the value of the test statistic is below the critical value. However, for practical trading applications, the values which are low enough - but still a bit higher than the critical one - can be still used in making decisions.
Examples:
The VIX volatility index is known to exhibit mean reversion properties (volatility spikes tend to fade out quickly). Accordingly, the statistics of the ADF test tend to stay below the critical value of 90% for long time periods.
The opposite case is presented by BTCUSD. During the same time range, the bitcoin price showed strong momentum - the moves away from the mean did not follow by the counter-move immediately, even vice versa. This is reflected by the ADF test statistic that consistently stayed above the critical value (and even above 0). Thus, using a mean reversion strategy would likely lead to losses.
Roc Mean Reversion (ValueRay)This Indicator shows the Absolute Rate of Change in correlation to its Moving Average.
Values over 3 (gray dotted line) can savely be considered as a breakout; values over 4.5 got a high mean-reverting chance (red dotted line).
This Indicator can be used in all timeframes, however, i recommend to use it <30m, when you want search for meaningful Mean-Reverting Signals.
Please like, share and subscribe. With your love, im encouraged to write and publish more Indicators.
% Divergence of RSIA simple script that plots the difference between the %ROC of price vs the %ROC of RSI, AKA the % of divergence. A simple way to analyze how strong a potential divergence is. Top reversals are above 0, bottom reversals are below. A value of 0 means price and RSI are changing by the same % value. So, if oscillator is moving up as price moves up, it means divergence is increasing. If oscillator moves down as price moves up, it means divergence is decreasing.
Res/Sup With Concavity & Increasing / Decreasing Trend AnalysisPurple means the concavity is down blue means concavity is up which is good.
Yellow means increasing, Red means decreasing.
Sup = Green
Res = Red
Jaws Mean Reversion [Strategy]This very simple strategy is an implementation of PJ Sutherlands' Jaws Mean reversion algorithm. It simply buys when a small moving average period (e.g. 2) is below
a longer moving average period (e.g. 5) by a certain percentage and closes when the small period average crosses over the longer moving average.
If you are going to use this, you may wish to apply this to a range of investment assets using a screener for setups, as the amount signals are low. Alternatively, you may wish to tweak the settings to provide more signals.
Context can be found here:
LINK
Hurst ExponentMy first try to implement Full Hurst Exponent.
The Hurst exponent is used as a measure of long-term memory of time series. It relates to the autocorrelations of the time series and the rate at which these decrease as the lag between pairs of values increases
The Hurst exponent is referred to as the "index of dependence" or "index of long-range dependence". It quantifies the relative tendency of a time series either to regress strongly to the mean or to cluster in a direction.
In short, depending on the value you can spot the trending / reversing market.
Values 0.5 to 1 - market trending
Values 0 to 0.5 - market tend to mean revert
Hurst Exponent is computed using Rescaled range (R/S) analysis.
I split the lookback period (N) in the number of shorter samples (for ex. N/2, N/4, N/8, etc.). Then I calculate rescaled range for each sample size.
The Hurst exponent is estimated by fitting the power law. Basically finding the slope of log(samples_size) to log(RS).
You can choose lookback and sample sizes yourself. Max 8 possible at the moment, if you want to use less use 0 in inputs.
It's pretty computational intensive, so I added an input so you can limit from what date you want it to be calculated. If you hit the time limit in PineScript - limit the history you're using for calculations.
####################
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Simple Hurst Exponent [QuantNomad]This is a simplified version of the Hurst Exponent indicator.
In the meantime, I'm working on the full version. It's computationally intensive, so it's a challenge to squeeze it to PineScript limits. It will require some time to optimize it, so I decided to publish a simplified version for now.
The Hurst exponent is used as a measure of long-term memory of time series. It relates to the autocorrelations of the time series, and the rate at which these decrease as the lag between pairs of values increases
The Hurst exponent is referred to as the "index of dependence" or "index of long-range dependence". It quantifies the relative tendency of a time series either to regress strongly to the mean or to cluster in a direction.
In short depend on value you can spot trending / reversing market.
Values 0.5 to 1 - market trending
Values 0 to 0.5 - market tend to mean revert
####################
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Mean ExtremeA simple script that shows the distance from a the mean, expressed as a percentage.
Simple Moving Average, in this case.
Informational only.
Logarithmic regressionLogarithmic regression (or known as Tseng's tunnels), is used to model data where growth or decay accelerates rapidly at first and then slows over time.
This model is for the long term series data (such as 10 years time span).
The user can consider entering the market when the price below 25% or 5% confidence and consider take profit when the price goes above 75% or 95% confidence line.
Technical issues
*The user have to pan over the chart from the beginning to the end of the study range (such as 10 years of bars) so the pine script could generate those regression lines on the chart.
*If on the chart the number of bar is less than the lookback period, it won't generate any lines as well
Mean recursion envelopeFree for public consumption
There is very little original here, the idea is discussed in the underground traders alliance, (google em), and was apparently the basis of what was at one time myfxbooks most profitable strategy.
I can't find the original video that was floating around on youtube, but if i find it again, i'll link it here.
This is bascially just the TV default envelope code copied and modified.
The idea is to have an envelope based on a low length, exponential basis. Then to manually "tune" the percent input so that the envelopes engulf most bars. Whenever price goes outside the envelopes (especially at key levels), look for a change to enter a reversion back to the ema.
This manual tuning when switching between time-frames and symbols of the percentage input, becomes arduous.
Instead this script uses the TV envelope code, but gets a setting based on the average of true range and "autotunes" with this.
Anything that protrudes beyond that level, especially at key levels, is likely to revert back to the ema. Bear in mind, a run away trend will also push past the envelopes and continue running for several (3-5) bars so, use it mindfully and thoughtfully with all the usual cautions about risk management.
Mean Reversion w/ Bollinger BandsThis is a more advanced version of my original mean reversion script.
It employs the famous Bollinger Bands.
This robot will buy when price falls below the lower Bollinger Band, and sell when price moves above the upper Bollinger Band.
I've only tested it on the S&P 500, though you could try it out on other assets to see the backtest performance.
During the recent COVID-19 bear market drop, it produced several buy signals on the S&P which I followed, and made some nice gains so far.
I still think this would make a better investing strategy (buy undervalued / sell over-valued), rather than a trading strategy.
I use this robot for my long term portfolio.
Bars above/below EMACount of previous bars above or below a chosen Exponential Moving Average. Typically price reconnects with well defined EMAs regularly. If the price has been above/below an EMA for too long, you can expect a reconnect in a short order and bet on mean reversion strategies.
YJ Mean ReversionMean reversion strategy, based upon the price deviation (%) from a chosen moving average (bars). Do note that the "gains" are always relative to your starting capital, so if you set a smaller starting capital (e.g. $10000) your gains will look bigger. Also when the strategy tester has finished calculating, check the "Open P/L", as there could still be open trades.
Some Tips:
- Was designed firstly to work on an index like the S&P 500 , which over time tends to go up in value.
- Avoid trading too frequently (e.g. Daily, Weekly), to avoid getting eaten by fees.
- If you change the underlying asset, or time frame, tweaking the moving average may be necessary.
- Can work with a starting capital of just $1000, optimise the settings as necessary.
- Accepts floating point values for the amount of units to purchase (e.g. Bitcoin ).
- If price of units exceeds available capital, script will cancel the buy.
- Adjusted the input parameters to be more intuitive.
Mean Street V1script for mean reversion conditions - tweak-able based on the volatility of the asset its used on, and the time frame
Mean Reversion IndicatorThis is a mean reversion indicator that anticipates a local trend reversion. Basically, it is a channel with the mid-line serving as a moving mean baseline. Each of the two curves run up and down within this channel bouncing off from the top and bottom bounds. Touching the bounds serves as an indication of a local trend reversal. The reversal signal is stronger when there exists a resonance (symmetry) in the two curves. The background histogram shows a Karobein oscillator that contributes support or resistance for the signal.
Bollinger Band Strategy (Basic) Version 1 This strategy is for learning purposes only. Pay special attention to these strategies on longer aggregation periods (like 1 hr chart or more). Don't expect accurate results when you set a limit to 10 cents above your entry to be accurate. For example if you set the chart to 1 day, the price may move down and hit a stop 10 times then tag your limit. If this doesn't make sense, just don't use strategies here. Learn more first. That being said, I don't have specific recommendations for each aggregation period, backtesting isn't always perfect.
Now then, this strategy can be used as the traditional BB method by setting the "Stop" and "Limit Out" to like 10000, check "Reversal Entry" and uncheck "Limit Time of Day" This will keep the strategy running just reverse your position when price crosses outside each band.
INPUTS:
Length - length of WMA that I used for mean of Bollinger Band (this may suppose to be SMA, too bad)
Source - O-H-L-C basis for WMA
Deviation - normal Standard deviation that would be set when using Bollinger Band
Trailing stop check box - your stop value will be either a hard stop or trailing stop for an exit
Stop - the stop value - remember you can set this really high and it won't stop out
Limit Out - the limit value for exit
Reversal Entry check box - This changes each entry from a reversal (traditional idea of BB) to enter a trend trade - hopefully version 2 will have choice to trend one direction and reversal in the other.
Limit Time of Day - Especially when trading futures, you may want to only trade a specific time of day, when this box is checked, you can set the entry times below, exit will still only occur based on limit/stop or a flip entry order (the opposite entry condition is met)
Tips:
when I don't know a thing about a price range, like gold. I can set the limit out to 10000 and play with a trailing stop to get a better idea of what is even possible before tuning further.
VIX reversion-Buschi
English:
A significant intraday reversion (commonly used: 3 points) on a high (over 20 points) S&P 500 Volatility Index (VIX) can be a sign of a market bottom, because there is the assumption that some of the "big guys" liquidated their options / insurances because the worst is over.
This indicator shows these reversions (3 points as default) when the VIX was over 20 points. The character "R" is then shown directly over the daily column, the VIX need not to be loaded explicitly.
Deutsch:
Eine deutliche Intraday-Umkehr (3 Punkte im Normalfall) bei einem hohen (über 20 Punkte) S&P 500 Volatility Index (VIX) kann ein Zeichen für eine Bodenbildung im Markt sein, weil möglicherweise einige "große Jungs" ihre Optionen / Versicherungen auflösen, weil das schlimmste vorbei ist.
Dieser Indikator zeigt diese Umkehr (Standardwert: 3 Punkte), wenn der VIX vorher über 20 Punkte lag. Der Buchstabe "R" wird dabei direkt über dem Tagesbalken angezeigt, wobei der VIX nicht explizit geladen werden muss.
Mean Reversion and Momentum - Updated with gaussiana smoothingMean Reversion and Momentum
Interpretation:
- Divergence means trend reversal
- Parallel movement means trend continuation
Squares above serve as a confirming signal
Mean Reversion and Momentum - Indicator versionMean Reversion and Momentum
Interpretation:
- Divergence means trend reversal
- Parallel movement means trend continuation
Squares above serve as a confirming signal