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!
Mean
level_statsThis script tells you the percentage of time an instrument's closing value is above and below a level of your choosing. The background color visually indicates periods where the instrument closed at or above the level (red) and below it (blue). For "stationary-ish" processes, you can get a loose feel for the mean, high, and low values. The historical information conveyed through the background coloring can help you plan derivatives trades. Try with your favorite pairs, commodities, or volatility indices.
Usage: pick a level of interest using the input.
[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.
MomentsLibrary "Moments"
Based on Moments (Mean,Variance,Skewness,Kurtosis) . Rewritten for Pinescript v5.
logReturns(src) Calculates log returns of a series (e.g log percentage change)
Parameters:
src : Source to use for the returns calculation (e.g. close).
Returns: Log percentage returns of a series
mean(src, length) Calculates the mean of a series using ta.sma
Parameters:
src : Source to use for the mean calculation (e.g. close).
length : Length to use mean calculation (e.g. 14).
Returns: The sma of the source over the length provided.
variance(src, length) Calculates the variance of a series
Parameters:
src : Source to use for the variance calculation (e.g. close).
length : Length to use for the variance calculation (e.g. 14).
Returns: The variance of the source over the length provided.
standardDeviation(src, length) Calculates the standard deviation of a series
Parameters:
src : Source to use for the standard deviation calculation (e.g. close).
length : Length to use for the standard deviation calculation (e.g. 14).
Returns: The standard deviation of the source over the length provided.
skewness(src, length) Calculates the skewness of a series
Parameters:
src : Source to use for the skewness calculation (e.g. close).
length : Length to use for the skewness calculation (e.g. 14).
Returns: The skewness of the source over the length provided.
kurtosis(src, length) Calculates the kurtosis of a series
Parameters:
src : Source to use for the kurtosis calculation (e.g. close).
length : Length to use for the kurtosis calculation (e.g. 14).
Returns: The kurtosis of the source over the length provided.
skewnessStandardError(sampleSize) Estimates the standard error of skewness based on sample size
Parameters:
sampleSize : The number of samples used for calculating standard error.
Returns: The standard error estimate for skewness based on the sample size provided.
kurtosisStandardError(sampleSize) Estimates the standard error of kurtosis based on sample size
Parameters:
sampleSize : The number of samples used for calculating standard error.
Returns: The standard error estimate for kurtosis based on the sample size provided.
skewnessCriticalValue(sampleSize) Estimates the critical value of skewness based on sample size
Parameters:
sampleSize : The number of samples used for calculating critical value.
Returns: The critical value estimate for skewness based on the sample size provided.
kurtosisCriticalValue(sampleSize) Estimates the critical value of kurtosis based on sample size
Parameters:
sampleSize : The number of samples used for calculating critical value.
Returns: The critical value estimate for kurtosis based on the sample size provided.
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.
Pythagorean Moving Averages (and more)When you think of the question "take the mean of this dataset", you'd normally think of using the arithmetic mean because usually the norm is equal to 1; however, there are an infinite number of other types of means depending on the function norm (p).
Pythagoras' is credited for the main types of means: his harmonic mean, his geometric mean, and his arithmetic mean:
Harmonic Average (p = -1):
- Take the reciprocal of all the numbers in the dataset, add them all together, divide by the amount of numbers added together, then take the reciprocal of the final answer.
Geometric Average (p = 0):
- Multiply all the numbers in the dataset, then take the nth root where n is equal to the amount of number you multiplied together.
Arithmetic Mean (p = 1):
- Add all the numbers in the dataset, then divide by the amount of numbers you added by.
A couple other means included in this script were the quadratic mean (p = 2) and the cubic mean (p = 3).
Quadratic Mean (p = 2):
- Square every number in the dataset, then divide by the amount of numbers your added by, then take the square root.
Cubic Mean (p = 3):
- Cube every number in the dataset, then divide by the amount of numbers you added by, then take the cube root.
There are an infinite number of means for every scenario of p, but they begin to follow a pattern after p = 3.
Read more:
www.cs.uni.edu
en.wikipedia.org
en.wikipedia.org
Note : I added the functions for the quadratic mean and cubic mean, but since market charts don't have those types of graphs, the functions don't usually work. It's the same reason why sometimes you'll see the harmonic average not working.
Disclaimer : This is not financial or mathematical advice, please look for someone certified before making any decisions.
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.
Drift Study (Inspired by Monte Carlo Simulations with BM) [KL]Inspired by the Brownian Motion ("BM") model that could be applied to conducting Monte Carlo Simulations, this indicator plots out the Drift factor contributing to BM.
Interpretation : If the Drift value is positive, then prices are possibly moving in an uptrend. Vice versa for negative drifts.
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
Coefficient of variation (standard deviation over mean)Shows the coefficient of variation defined as standard deviation over mean (for the specified window).
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.
Examples of Rolling Average Using Automated AnchoringIn this study, I present a method to expose NaN values to development environment.
This exposure allows NaN values to be used by methods in scripts.
I also show how to use values, even NaN values, as anchors from which statistics can be computed from.
I demonstrate how to do this with constants and variables in methods for computing the cumulative/rolling average of a series.
I also show how to calculate the cumulative/rolling average from the start of a ticker series using the aforementioned methods.
Each method has a description on how some of their parts work as well as their constraints.
Method #1 - Can only be used for computing the rolling average on the ticker series.
Method #2 - The simple moving average from the Pine Script reference.
- Can be used to calculate the rolling average of the ticker series and number values of a series.
- This method seems to cause an error when there are many bars in the series.
Method #3 - The most versatile method due to the use of computing the rolling average using an array.
- Timeout will occur when computing the rolling average of an entire ticker series which is long.
- Timeout has not occurred when computing a rolling average of a series from NaN or non-NaN anchor points even when the series is long.
This is an attempt to get around the constraints of the built-in sma(source, length) function in which length cannot be dynamically adjusted.
Other Pine Script functions have that constraint which we can get around by defining our own functions.
Mean ExtremeA simple script that shows the distance from a the mean, expressed as a percentage.
Simple Moving Average, in this case.
Informational only.
Z-Score 'Bollinger Bands'The following script is an application of the Z-Score (previous script).
Z-Scores can be used in place of standard deviation (sigma) in 'Bollinger Bands'.
The average of the sample (x-bar) over 21 days (N)
21 average trading days per month, fixed value
The average of the population (mu) over 63 days (n)
63 days per quarter, default is set to 63
Z-Score is calculated by formula in previous script, and the absolute value is taken of "Z".
Z-High = absolute value of Z + (x-bar).
Z-Low = absolute value of Z - (x-bar).
Will update with Z from mu and Z from avg (working on UX and visualization details).
Z-Score The z-score is a way of counting the number of standard deviations between a given data value and the mean of the data set.
Z-score = (x̄ - μ) / (σ / √ n)
x̄ = sample mean (using the array.avg function = array(a,close ), where i = 1 to 21)
μ = population mean ( = avg(close, n))
σ = standard deviation of the population ( = stdev(close,n))
n = number of 'close' or trading day closes
n = input
... Note: The previous indicator is part of a larger series of indicators
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.
Spread by//Every spread & central tendency measure in 1 script with comfortable visualization, including scrips's status line.
Spread measures:
- Standard deviation (for most cases);
- Average deviation (if there are extreme values);
- GstDev - Geometric Standard Deviation (exclusively for Geometric Mean);
- HstDev - Harmonic Deviation (exclusively for Harmonic Mean).
These modified functions will calculate everything right, they will take source, length, AND basis of your choice, unlike the ones from TW.
Central tendency measures:
- Mean (if everything's cool & equal);
- Median (values clustering towards low/high part of the rolling window);
- Trimean (3/more distinguishable clusters of data);
- Midhinhe (2 distinguishable clusters of data);
- Geometric Mean ( |low.. ... ... .. .... ... . . . . . . . . . . . .high| this kinda data); <- Exp law
- Harmonic Mean { |low. . . . . . . . . . . . . . .. . . .high| kinda data). <- Reciprocal law
Listen:
1) Don't hesitate using Standard Deviation with non-mean, like "Midhinge Standard Devition", despite what ol' stats gurus gonna say, it works when it's appropriate;
2) Don't check log space while using Geometric Mean & Geometric Standard Deviation, these 2 implement log stuff by design, I mean unless u wanna make it double xd
3) You can use this script, modify it how you want, ask me questions whatever, just make money using it;
4) Use Midrange & Midpoints in tandem when data follows ~addition law (like this . . . . . . . . . . . . . . . . . . . . .). <- just addition law
Look at the data, choose spread measure first, then choose central tendency measure, not vice versa.
!!!
Ain't gonna place ® sign on standard deviations like one B guy did in 1980s lmao, but if your wanna use Harmonic Deviations in science/write about/cite it/whatever, pls give me a lil credit at least, I've never seen it anywhere and unfortunately had to develop it by myself. it's useful when your data develops by reciprocals law (opposite to exponential).
Peace TW
Harmonic MADsNo, it's not a new saturation plugin for your fruity loops.
...
These are Mean Average Deviations calculated from Harmonic Mean.
...
In my previous research I tried to develop "Harmonic Average Deviations", since applying stdevs on Harmonic Mean calculated from reciprocals ain't make sense. Din't work out, prolly cuz by definition stdevs doesn't like negatives. So in the end I ended up using Mean Average Deviations, and turned out it works great. Generally market data doesn't distribute normally, so t's a great tool, now weird kurtosis won't be a problem.