Forward Backward EMA [Repaint]Perform forward-backward filtering using exponential averaging, thus providing a zero-phase exponential moving average. The output repaint and cannot be used as input for other indicators.
Settings
Length : moving average period
Src : data input of the moving average
Plot Color : the color of the displayed plot
Line Width : width of the plotted line
Usages
The main usage of moving averages is to provide an estimate of the underlying trend in the price by removing higher term variations from it. Non-causal (repainting) indicators are limited to offline applications, as such, they are most useful for summary analyses, note that it is still possible to infer from the output of repainting indicators, however since past outputs are subject to changes, it is extremely difficult to track the effectiveness of such indicators, and in online applications they only track the price, making them equally useful for predictive applications than following the direction of an individual candle.
Non-causal filters can be useful in order to have a better view of symbols with a relatively uninformative evolution.
Details
Causal filters have lag, this is the cost of using past observations as inputs, the more past observations you use, the more lag you will obtain (assuming these past observations have non-zero weights). There are various solutions to reduce the lag of a moving average, the most simple one relying on giving higher weights to more recent observations, another one relies on introducing gain in the filter passband, that is amplifying certain variations in the input signal while attenuating/removing higher term ones, finally, we can use adaptive moving averages to avoid excessive lag.
All these previous solutions can be used causally, but they are far from being perfect, as the lag reduction is often done at the cost of smoothness, if we were to keep the original smoothness of the filter while having no lag we would need to use non-causal solutions. The most common solution is to directly use future values as inputs, such moving averages are called "two-sided" moving averages since they use past values as input (left side) as well as future input values (right side), this is equivalent to shifting the results of a moving average backward.
The advantages of two-sided moving averages is that they conserve the original amplitude response of the moving average, however, it won't be possible to compute the most recent values of the moving average (since we won't have access to future values at a certain point), an alternative method heavily used in digital signal processing is forward-backward filtering.
The method consists of applying a filter forward in time, then we apply it once again backward. In order for you to have an easier understanding of this process think about applying a moving average normally starting at time t = 0 , then apply that moving average once again using the previous results as input but start from t = N-1 , that is from the most recent point, and proceed backward, plotting the result from left to right until you get back to t = 0 .
From this, it follows that forward-backward filtering applies a filter twice, the resulting filter is thus a two-passes filter, this results in an even smoother output (more precisely the filter amplitude response is squared).
Forward-backward filtering can be done in Pinescript by using the function "line.new" inside a loop, an exponential moving average is applied forward first, then once again backward inside the loop, "line.new" is used to plot the results backward.
Notes
It is important to note that forward-backward filtering is a repainting process, all the results of the indicator you see on the chart are subject to change over time. Since the method make use of line.new you will have around only 54 visible observations, with the impossibility of using them as input for other indicators. If you see indicators in the future with the same characteristics be aware that they will repaint.
Never purchase/rent filters that appear as having no lag, they are either repainting or the results are coming from a lucky shot or from an overfitted model, it is impossible to make both zero-lag and causal moving averages with pinescript, if you have doubt don't test your luck, better safe than sorry.
Zerolag
Trendflex - Another new Ehlers indicatorSource: Stocks and Commodities V38
Hooray! Another new John Ehlers indicator!
John claims this indicator is lag-less and uses the SPY on the Daily as an example.
This indicator is a slight modification of Reflex, which I have posted here
I think it's better for Stocks and ETFs than Reflex since it factors in long trends. It tends to keep you in winning trades for a long time.
I believe this indicator can be used for entries or exits, potentially both.
Entry
1. Entering Long positions at the pivot low points (Stocks and ETFs)
2. Entering Long when the Reflex crosses above the zero lines (Stocks, ETFs, Commodities )
Exit
1. Exiting Long positions at a new pivot high point (Stocks and ETFs)
2. Exiting Long when the Reflex crosses below the zero lines (Stocks, ETFs, Commodities )
In this example, I place a Long order on the SPY every time the Reflex crosses above the zero level and exit when it crosses below or pops my stop loss, set at 1.5 * Daily ATR.
2/3 Wins
+16.05%
Let me know in the comment section if you're able to use this in a strategy.
Reflex - A new Ehlers indicatorSource: Stocks and Commodities V38
Hooray! A new John Ehlers indicator!
John claims this indicator is lag-less and uses the SPY on the Daily as an example.
He states that drawing a line from peak to peak (or trough to trough) will correspond perfectly with the Asset.
I have to say I agree! There is typically one bar of lag or no lag at all!
I believe this indicator can be used for either entries or exits, but not both.
Entry
1. Entering Long positions at the pivot low points (Stocks and ETFs)
2. Entering Long when the Reflex crosses above the zero lines (Stocks, ETFs, Commodities)
Exit
1. Exiting Long positions at a new pivot high point (Stocks and ETFs)
2. Exiting Long when the Reflex crosses below the zero lines (Stocks, ETFs, Commodities)
In this example, I place a Long order on the SPY every time the Reflex crosses above the zero level and exit when it crosses below or pops my stop loss, set at 1.5 * Daily ATR.
4/6 Wins
+10.76%
For me, that's good enough to create a strategy and backtest on several Indices and ETFs, which is what I have a hunch this will work on.
I think there is a lot of promise from a single Indicator!
Let me know in the comment section if you're able to use this in a strategy.
ZLMA - Low-Lag Moving Average Based On An Alternative SMA DesignThere can be many ways to make a simple moving average, you can either sum the current and the n-1 previous data points and divide the result by n , or you can do it more efficiently by first taking the cumulative sum of your data points, and subtracting the current cumulative sum result with the cumulative sum results n bars ago, then divide the result by n . This can be described by the following formulas:
a(t) = a(t-1) + price(t)
b(t) = (a(t) - a(t-n))/n
This method is the one used in order to allow the user to use a series as SMA period, more info here:
Today we use this design in order to provide a pretty efficient low-lag moving average where the amount of lag of the moving average can be increased/decreased by the user.
THE INDICATOR
length control the period of the moving average, with larger value of length returning larger filtering amount. The lag setting in the other hand control the amount of lag of the moving average, with larger value of lag returning a moving average with less lag. The lag setting can't be lower than 1 or greater than 2, but values lower than 1 and greater than 0 would just return a moving average with larger filtering amount while values greater than 2 would create crazy wild overshoots.
In blue lag = 1.8, in red lag = 1.4, when lag = 1 the moving average is equal to a simple moving average of period length. Remember that larger values of lag will return greater over/undershoots.
Approximate amplitude response of the moving average, like all low-lag moving averages you can see frequencies amplified (the ones on the left greater than 1) .
SUMMARY
We proposed a low-lag moving average based on the cumulative/change SMA design where the lag of the moving average can be controlled by the user. There are tons of low-lag moving averages already, and they don't necessarily provide different results from each others, however this one is still relatively interesting as you can switch from a simple MA from a low-lagging one, other indicators are ready using this design and will be posted soon.
Shapeshifting Moving Average - Switching From Low-Lag To SmoothThe term "shapeshifting" is more appropriate when used with something with a shape that isn't supposed to change, this is not the case of a moving average whose shape can be altered by the length setting or even by an external factor in the case of adaptive moving averages, but i'll stick with it since it describe the purpose of the proposed moving average pretty well.
In the case of moving averages based on convolution, their properties are fully described by the moving average kernel ( set of weights ), smooth moving averages tend to have a symmetrical bell shaped kernel, while low lag moving averages have negative weights. One of the few moving averages that would let the user alter the shape of its kernel is the Arnaud Legoux moving average, which convolve the input signal with a parametric gaussian function in which the center and width can be changed by the user, however this moving average is not a low-lagging one, as the weights don't include negative values.
Other moving averages where the user can change the kernel from user settings where already presented, i posted a lot of them, but they only focused on letting the user decrease or increase the lag of the moving average, and didn't included specific parameters controlling its smoothness. This is why the shapeshifting moving average is proposed, this parametric moving average will let the user switch from a smooth moving average to a low-lagging one while controlling the amount of lag of the moving average.
Settings/Kernel Interaction
Note that it could be possible to design a specific kernel function in order to provide a more efficient approach to today goal, but the original indicator was a simple low-lag moving average based on a modification of the second derivative of the arc tangent function and because i judged the indicator a bit boring i decided to include this parametric particularity.
As said the moving average "kernel", who refer to the set of weights used by the moving average, is based on a modification of the second derivative of the arc tangent function, the arc tangent function has a "S" shaped curve, "S" shaped functions are called sigmoid functions, the first derivative of a sigmoid function is bell shaped, which is extremely nice in order to design smooth moving averages, the second derivative of a sigmoid function produce a "sinusoid" like shape ( i don't have english words to describe such shape, let me know if you have an idea ) and is great to design bandpass filters.
We modify this 2nd derivative in order to have a decreasing function with negative values near the end, and we end up with:
The function is parametric, and the user can change it ( thus changing the properties of the moving average ) by using the settings, for example an higher power value would reduce the lag of the moving average while increasing overshoots. When power < 3 the moving average can act as a slow moving average in a moving average crossover system, as weights would not include negative values.
Here power = 0 and length = 50. The shapeshifting moving average can approximate a simple moving average with very low power values, as this would make the kernel approximate a rectangular function, however this is only a curiosity and not something you should do.
As A Smooth Moving Average
“So smooth, and so tranquil. It doesn't get any quieter than this”
A smooth moving average kernel should be : symmetrical, not to width and not to sharp, bell shaped curve are often appropriates, the proposed moving average kernel can be symmetrical and can return extremely smooth results. I will use the Blackman filter as comparison.
The smooth version of the moving average can be used when the "smooth" setting is selected. Here power can only be an even number, if power is odd, power will be equal to the nearest lowest even number. When power = 0, the kernel is simply a parabola:
More smoothness can be achieved by using power = 2
In red the shapeshifting moving average, in green a Blackman filter of both length = 100. Higher values of power will create lower negative values near the border of the kernel shape, this often allow to retain information about the peaks and valleys in the input signal. Power = 6 approximate the Blackman filter pretty well.
Conclusion
A moving average using a modification of the 2nd derivative of the arc tangent function as kernel has been presented, the kernel is parametric and allow the user to switch from a low-lag moving average where the lag can be increased/decreased to a really smooth moving average.
As you can see once you get familiar with a function shape, you can know what would be the characteristics of a moving average using it as kernel, this is where you start getting intimate with moving averages.
On a side note, have you noticed that the views counter in posted ideas/indicators has been removed ? This is truly a marvelous idea don't you think ?
Thanks for reading !
Right Sided Ricker Moving Average And The Gaussian DerivativesIn general gaussian related indicators are built by using the gaussian function in one way or another, for example a gaussian filter is built by using a truncated gaussian function as filter kernel (kernel refer to the set weights) and has many great properties, note that i say truncated because the gaussian function is not supposed to be finite. In general the gaussian function is represented by a symmetrical bell shaped curve, however the gaussian function is parametric, and the user might adjust the position of the peak as well as the width of the curve, an indicator using this parametric approach is the Arnaud Legoux moving average (ALMA) who posses a length parameter controlling the filter length, a peak parameter controlling the position of the peak of the gaussian function as well as a width parameter, those parameters can increase/decrease the lag and smoothness of the moving average output.
However what about the derivatives of the gaussian function ? We don't talk much about them and thats a pity because they are extremely interesting and have many great properties as well, therefore in this post i'll present a low lag moving average based on the modification of the 2nd order derivative of the gaussian function, i believe this post will be extremely informative and i hope you will enjoy reading it, if you are not a math person you can skip the introduction on gaussian derivatives and their properties used as filter kernel.
Gaussian Derivatives And The Ricker Wavelet
The notion of derivative is continuous, so we will stick with the term discrete derivative instead, which just refer to the rate of change in the function, we have a change function in pinescript, and we will be using it to show an approximation of the gaussian function derivatives.
Earlier i used the term 2nd order derivative, here the derivative order refer to the order of differentiation, that is the number of time we apply the change function. For example the 0 (zeroth) order derivative mean no differentiation, the 1st order derivative mean we use differentiation 1 time, that is change(f) , 2nd order mean we use differentiation 2 times, that is change(change(f)) , derivates based on multiple differentiation are called "higher derivative". It will be easier to show a graphic :
Here we can see a normal gaussian function in blue, its scaled 1st order derivative in orange, and its scaled 2nd derivative in green, note that i use scaled because i used multiplication in order for you to see each curve, else it would have been less easy to observe them. The number of time a gaussian function derivative cross 0 is based on the order of differentiation, that is 2nd order = the function crossing 0 two times.
Now we can explain what is the Ricker wavelet, the Ricker wavelet is just the normalized 2nd order derivative of a gaussian function with inverted sign, and unlike the gaussian function the only thing you can change is the width parameter. The formula of the Ricker wavelet is show'n here en.wikipedia.org , where sigma is the width parameter.
The Ricker wavelet has this look :
Because she is shaped like a sombrero the Ricker wavelet is also called "mexican hat wavelet", now what would happen if we used a Ricker wavelet as filter kernel ? The response is that we would end-up with a bandpass filter, in fact the derivatives of the gaussian function would all give the kernel of a bandpass filter, with higher order derivatives making the frequency response of the filter approximate a symmetrical gaussian function, if i recall a filter using the first order derivative of a gaussian function would give a frequency response that is left skewed, this skewness is removed when using higher order derivatives.
The Indicator
I didn't wanted to make a bandpass filter, as lately i'am more interested in low-lag filters, so how can we use the Ricker wavelet to make a low-lag low-pass filter ? The response is by taking the right side of the Ricker wavelet, and since values of the wavelets are negatives near the border we know that the filter passband is non-monotonic, that is we know that the filter will have low-lag as frequencies in the passband will be amplified.
So taking the right side of the Ricker wavelet only mean that t has to be greater than 0 and linearly increasing, thats easy, however the width parameter can be tricky to use, this was already the case with ALMA, so how can we work with it ? First it can be seen that values of width needs to be adjusted based on the filter length.
In red width = 14, in green width = 5. We can see that an higher values of width would give really low weights, when the number of negative weights is too important the filter can have a negative group delay thus becoming predictive, this simply mean that the overshoots/undershoots will be crazy wild and that a great fit will be impossible.
Here two moving averages using the previous described kernels, they don't fit the price well at all ! In order to fix this we can simply define width as a function of the filter length, therefore the parameter "Percentage Width" was introduced, and simply set the width of the Ricker wavelet as p percent of the filter length. Lower values of percent width reduce the lag of the moving average, but lets see precisely how this parameter influence the filter output :
Here the filter length is equal to 100, and the percent width is equal to 60, the fit is quite great, lower values of percent width will increase overshoots, in fact the filter become predictive once the percent width is equal or lower to 50.
Here the percent width is equal to 50. Higher values of percent width reduce the overshoots, and a value of 100 return a filter with no overshoots that is suited to act as a lagging moving average.
Above percent width is set to 100. In order to make use of the predictive side of the filter, it would be great to introduce a forecast option, however this require to find the best forecast horizon period based on length and width, this is no easy task.
Finally lets estimate a least squares moving average with the proposed moving average, you know me...a percent width set to 63 will return a relatively good estimate of the LSMA.
LSMA in green and the proposed moving in red with percent width = 63 and both length = 100.
Conclusion
A new low-lag moving average using a right sided Ricker wavelet as filter kernel has been introduced, we have also seen some properties of gaussian derivatives. You can see that lately i published more moving averages where the user can adjust certain properties of the filter kernel such as curve width for example, if you like those moving averages you can check the Parametric Corrective Linear Moving Averages indicator published last month :
I don't exclude working with pure forms of gaussian derivatives in the future, as i didn't published much oscillators lately.
Thx for reading !
Parametric Corrective Linear Moving AveragesImpulse responses can fully describe their associated systems, for example a linearly weighted moving average (WMA) has a linearly decaying impulse response, therefore we can deduce that lag is reduced since recent values are the ones with the most weights, the Blackman moving average (or Blackman filter) has a bell shaped impulse response, that is mid term values are the ones with the most weights, we can deduce that such moving average is pretty smooth, the least squares moving average has negative weights, we can therefore deduce that it aim to heavily reduce lag, and so on. We could even estimate the lag of a moving average by looking at its impulse response (calculating the lag of a moving average is the aim of my next article with Pinescripters) .
Today a new moving average is presented, such moving average use a parametric rectified linear unit function as weighting function, we will see that such moving average can be used as a low lag moving average as well as a signal moving average, thus creating a moving average crossover system. Finally we will estimate the LSMA using the proposed moving average.
Correctivity And The Parametric Rectified Linear Unit Function
Lot of terms are used, each representing one thing, lets start with the easiest one,"corrective". In some of my posts i may have used the term "underweighting", which refer to the process of attributing negative weights to the input of a moving average, a corrective moving average is simply a moving average underweighting oldest values of the input, simply put most of the low lag moving averages you'll find are corrective. This term was used by Aistis Raudys in its paper "Optimal Negative Weight Moving Average for Stock Price Series Smoothing" and i felt like it was a more elegant term to use instead of "low-lag".
Now we will describe the parametric rectified linear unit function (PReLU), this function is the one used as weighting function and is not that complex. This function has two inputs, alpha , and x , in short if x is greater than 0, x remain unchanged, however if x is lower than 0, then the function output is alpha × x , if alpha is equal to 1 then the function is equivalent to an identity function, if alpha is equal to 0 then the function is equivalent to a rectified unit function.
PReLU is mostly used in neural network design as an activation function, i wont explain to you how neural networks works but remember that neural networks aim to mimic the neural networks in the brain, and the activation function mimic the process of neuron firing. Its a super interesting topic because activation functions regroup many functions that can be used for technical indicators, one example being the inverse fisher RSI who make use of the hyperbolic tangent function.
Finally the term parametric used here refer to the ability of the user to change the aspect of the weighting function thanks to certain settings, thinking about it, it isn't a common things for moving averages indicators to let the user modify the characteristics of the weighting function, an exception being the Arnaud Legoux moving average (ALMA) which weighting function is a gaussian function, the user can control the peak and width of the function.
The Indicator
The indicator has two moving averages displayed on the chart, a trigger moving average (in blue) and a signal moving average (in red), their crosses can generate signals. The length parameter control the filter length, with higher values of length filtering longer term price fluctuations.
The percentage of negative weights parameter aim to determine the percentage of negative weights in the weighting function, note that the signal moving average won't use the same amount and will use instead : 100 - Percentage , this allow to reverse the weighting function thus creating a more lagging output for signal. Note that this parameter is caped at 50, this is because values higher than 50 would make the trigger moving average become the signal moving average, in short it inverse the role of the moving averages, that is a percentage of 25 would be the same than 75.
In red the moving average using 25% of negative weights, in blue the same moving average using 14% percent of negative weights. In theory, more negative weights = less lag = more overshoots.
Here the trigger MA in blue has 0% of negative weights, the trigger MA in green has however 35% of negative weights, the difference in lag can be clearly seen. In the case where there is 0% of negative weights the trigger become a simple WMA while the signal one become a moving average with linearly increasing weights.
The corrective factor is the same as alpha in PReLU, and determine the steepness of the negative weights line, this parameter is constrained in a range of (0,1), lower values will create a less steep negative weights line, this parameter is extremely useful when we want to reduce overshoots, an example :
here the corrective factor is equal to 1 (so the weighting function is an identity function) and we use 45% of negative weights, this create lot of overshoots, however a corrective factor of 0.5 reduce them drastically :
Center Of Linearity
The impulse response of the signal moving average is inverse to the impulse response of the trigger moving average, if we where to show them together we would see that they would crosses at a point, denoted center of linearity, therefore the crosses of each moving averages correspond to the cross of the center of linearity oscillator and 0 of same period.
This is also true with the center of gravity oscillator, linear covariance oscillator and linear correlation oscillator. Of course the center of linearity oscillator is way more efficient than the proposed indicator, and if a moving average crossover system is required, then the wma/sma pair is equivalent and way more efficient, who would know that i would propose something with more efficient alternatives ? xD
Estimating A Least Squares Moving Average
I guess...yeah...but its not my fault you know !!! Its a linear weighting function ! What can i do about it ?
The least squares moving average is corrective, its weighting function is linearly decreasing and posses negative weights with an amount of negative weights inferior to 50%, now we only need to find the exact percentage amount of negative weights. How to do it ? Well its not complicated if we recall the estimation with the WMA/SMA combination.
So, an LSMA of period p is equal to : 3WMA(p) - 2SMA(p) , each coefficient of the combination can give us this percentage, that is 2/3*100 = 33.333 , so there are 33.33% percent of negative weights in the weighting function of the least squares moving average.
In blue the trigger moving average with percentage of negative values et to 33.33, and in green the lsma of both period 50.
Conclusion
Altho inefficient, the proposed moving averages remain extremely interesting. They make use of the PReLU function as weighting function and allow the user to have a more accurate control over the characteristics of the moving averages output such as lag and overshoot amount, such parameters could even be made adaptive.
We have also seen how to estimate the least squares moving average, we have seen that the lsma posses 33.333...% of negative weights in its weighting function, another useful information.
The lsma is always behind me, not letting me focus on cryptobot super profit indicators using massive amount of labels, its like each time i make an indicator, the lsma come back, like a jealous creature, she want the center of attention, but you know well that the proposed indicator is inefficient ! Inefficient elegance (effect of the meds) .
Thanks for reading !
HEMA - A Fast And Efficient Estimate Of The Hull Moving AverageIntroduction
The Hull moving average (HMA) developed by Alan Hull is one of the many moving averages that aim to reduce lag while providing effective smoothing. The HMA make use of 3 linearly weighted (WMA) moving averages, with respective periods p/2 , p and √p , this involve three convolutions, which affect computation time, a more efficient version exist under the name of exponential Hull moving average (EHMA), this version make use of exponential moving averages instead of linearly weighted ones, which dramatically decrease the computation time, however the difference with the original version is clearly noticeable.
In this post an efficient and simple estimate is proposed, the estimation process will be fully described and some comparison with the original HMA will be presented.
This post and indicator is dedicated to LucF
Estimation Process
Estimating a moving average is easier when we look at its weights (represented by the impulse response), we basically want to find a similar set of weights via more efficient calculations, the estimation process is therefore based on fully understanding the weighting architecture of the moving average we want to estimate.
The impulse response of an HMA of period 20 is as follows :
We can see that the first weights increases a bit before decaying, the weights then decay, cross under 0 and increase again. More recent closing price values benefits of the highest weights, while the oldest values have negatives ones, negative weighting is what allow to drastically reduce the lag of the HMA. Based on this information we know that our estimate will be a linear combination of two moving averages with unknown coefficients :
a × MA1 + b × MA2
With a > 0 and b < 0 , the lag of MA1 is lower than the lag of MA2 . We first need to capture the general envelope of the weights, which has an overall non-linearly decaying shape, therefore the use of an exponential moving average might seem appropriate.
In orange the impulse response of an exponential moving average of period p/2 , that is 10. We can see that such impulse response is not a bad estimate of the overall shape of the HMA impulse response, based on this information we might perform our linear combination with a simple moving average :
2EMA(p/2) + -1SMA(p)
this gives the following impulse response :
As we can see there is a clear lack of accuracy, but because the impulse response of a simple moving is a constant we can't have the short increasing weights of the HMA, we therefore need a non-constant impulse response for our linear combination, a WMA might be appropriate. Therefore we will use :
2WMA(p/2) + -1EMA(p/2)
Note that the lag a WMA is inferior to the lag of an EMA of same period, this is why the period of the WMA is p/2 . We obtain :
The shape has improved, but the fit is poor, which mean we should change our coefficients, more precisely increasing the coefficient of the WMA (thus decreasing the one of the EMA). We will try :
3WMA(p/2) + -2EMA(p/2)
We then obtain :
This estimate seems to have a decent fit, and this linear combination is therefore used.
Comparison
HMA in blue and the estimate in fuchsia with both period 50, the difference can be noted, however the estimate is relatively accurate.
In the image above the period has been set to 200.
Conclusion
In this post an efficient estimate of the HMA has been proposed, we have seen that the HMA can be estimated via the linear combinations of a WMA and an EMA of each period p/2 , this isn't important for the EMA who is based on recursion but is however a big deal for the WMA who use recursion, and therefore p indicate the number of data points to be used in the convolution, knowing that we use only convolution and that this convolution use twice less data points then one of the WMA used in the HMA is a pretty great thing.
Subtle tweaking of the coefficients/moving averages length's might help have an even more accurate estimate, the fact that the WMA make use of a period of √p is certainly the most disturbing aspect when it comes to estimating the HMA. I also described more in depth the process of estimating a moving average.
I hope you learned something in this post, it took me quite a lot of time to prepare, maybe 2 hours, some pinescripters pass an enormous amount of time providing content and helping the community, one of them being LucF, without him i don't think you'll be seeing this indicator as well as many ones i previously posted, I encourage you to thank him and check his work for Pinecoders as well as following him.
Thanks for reading !
Reflex Oscillator - Dr. John EhlersHot off the press, I present this NEW "Reflex Oscillator" employing PSv4.0, originally formulated by Dr. John Ehlers for TASC - February 2020 Traders Tips. John Ehlers might describe it's novel characteristics as being a reversal sensitive near zero-lag averaging indicator retaining the CYCLE component. Also, I would add that irregardless of the sampling interval, this indicator has a bound range between +/-2.0 on "1 second" candles all the way up to "1 month" candle durations. This indicator also has a companion indicator entitled "TrendFlex Oscillator". I have published it in tandem with this one in my scripts profile.
One notable difference between this and the original formulation is that I have added an independent control for the Super Smoother. This "tweak" is enabled by applying the override and adjusting it's period. There is a "Post Smooth" input() that "tweaks" the internal Reflex EMA too. Keep in mind that my intention of adding tweaks is solely for experimentation with the original formulation.
I also added adjustable levels for those of you that may wish to employ alertcondition()s to this indicator somehow. Providing a more utilitarian approach, I created this with an easy to use reusable function named reflex(). As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette". Being this is one of John Ehlers' first two simultaneously released indicators for 2020, I felt a few more bells and whistles were appropriate as a proper contribution to the Tradingview community.
Features List Includes:
Dark Background - Easily disabled in indicator Settings->Style for "Light" charts or with Pine commenting
AND much, much more... You have the source!
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
TrendFlex Oscillator - Dr. John EhlersHot off the press, I present this NEW "TrendFlex Oscillator" employing PSv4.0, originally formulated by Dr. John Ehlers for TASC - February 2020 Traders Tips. John Ehlers might describe it's novel characteristics as being a reversal sensitive near zero-lag averaging indicator retaining the TREND component. Also, I would add that irregardless of the sampling interval, this indicator has a bound range between +/-2.0 on "1 second" candles all the way up to "1 month" candle durations. This indicator also has a companion indicator entitled "Reflex Oscillator". I have published it in tandem with this one in my scripts profile.
One notable difference between this and the original formulation is that I have added an independent control for the Super Smoother. This "tweak" is enabled by applying the override and adjusting it's period. There is a "Post Smooth" input() that "tweaks" the internal TrendFlex EMA too. Keep in mind that my intention of adding tweaks is solely for experimentation with the original formulation.
I also added adjustable levels for those of you that may wish to employ alertcondition()s to this indicator somehow. Providing a more utilitarian approach, I created this with an easy to use reusable function named trendflex(). As always, I have included advanced Pine programming techniques that conform to proper "Pine Ettiquette". Being this is one of John Ehlers' first two simultaneously released indicators for 2020, I felt a few more bells and whistles were appropriate as a proper contribution to the Tradingview community.
Features List Includes:
Dark Background - Easily disabled in indicator Settings->Style for "Light" charts or with Pine commenting
AND much, much more... You have the source!
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
LSMA - A Fast And Simple Alternative CalculationIntroduction
At the start of 2019 i published my first post "Approximating A Least Square Moving Average In Pine", who aimed to provide alternatives calculation of the least squares moving average (LSMA), a moving average who aim to estimate the underlying trend in the price without excessive lag.
The LSMA has the form of a linear regression ax + b where x is a linear sequence 1.2.3..N and with time varying a and b , the exact formula of the LSMA is as follows :
a = stdev(close,length)/stdev(bar_index,length) * correlation(close,bar_index,length)
b = sma(close,length) - a*sma(bar_index,length)
lsma = a*bar_index + b
Such calculation allow to forecast future values however such forecast is rarely accurate and the LSMA is mostly used as a smoother. In this post an alternative calculation is proposed, such calculation is incredibly simple and allow for an extremely efficient computation of the LSMA.
Rationale
The LSMA is a FIR low-pass filter with the following impulse response :
The impulse response of a FIR filter gives us the weight of the filter, as we can see the weights of the LSMA are a linearly decreasing sequence of values, however unlike the linearly weighted moving average (WMA) the weights of the LSMA take on negative values, this is necessary in order to provide a better fit to the data. Based on such impulse response we know that the WMA can help calculate the LSMA, since both have weights representing a linearly decreasing sequence of values, however the WMA doesn't have negative weights, so the process here is to fit the WMA impulse response to the impulse response of the LSMA.
Based on such negative values we know that we must subtract the impulse response of the WMA by a constant value and multiply the result, such constant value can be given by the impulse response of a simple moving average, we must now make sure that the impulse response of the WMA and SMA cross at a precise point, the point where the impulse response of the LSMA is equal to 0.
We can see that 3WMA and 2SMA are equal at a certain point, and that the impulse response of the LSMA is equal to 0 at that point, if we proceed to subtraction we obtain :
Therefore :
LSMA = 3WMA - 2SMA = WMA + 2(WMA - SMA)
Comparison
On a graph the difference isn't visible, subtracting the proposed calculation with a regular LSMA of the same period gives :
the error is 0.0000000...and certainly go on even further, therefore we can assume that the error is due to rounding errors.
Conclusion
This post provided a different calculation of the LSMA, it is shown that the LSMA can be made from the linear combination of a WMA and a SMA : 3WMA + -2SMA. I encourage peoples to use impulse responses in order to estimate other moving averages, since some are extremely heavy to compute.
Thanks for reading !
Time Series Lag Reduction Filter by CryptorhythmsTime Series Lag Reduction Filter by Cryptorhythms
Description
A little filter to reduce lag on any time series data. Here we use an EMA to demonstrate how it works, but you could use it in many different ways/appications.
This method can cause overshoot if you get too aggressive with the "lagReduce" setting. In this case lower the lagReduce variable.
👍 We hope you enjoyed this indicator and find it useful! We post free crypto analysis, strategies and indicators regularly. This is our 76th script on Tradingview!
Colored Moving Averages with Zero Lag and ATR BandsEnglish description:
- You can choose from 6 different Moving Averages: SMA , EMA , WMA , VWMA , RMA, SWMA
- Turn ON/OFF the Zero Lag alghorithm
- Make it 2 colors for better visibility of a trend
- Turn ON/OFF the ATR Bands up to 5 multiplicator
- Set the offset on the time axis
Polski opis:
- Możesz wybierać z 6 różnych średnich kroczących: SMA , EMA , WMA , VWMA , RMA, SWMA
- Włączyć/Wyłączyć algorytm Zero Lag
- Włączyć opcję 2 kolorowej średniej żeby lepiej widzieć trendy
- Włączyć/Wyłączyć wstęgi ATR z maksymalnym mnożnikiem x5
- Ustawić przesunięcie względem osi czasu
Damped Sine Wave Weighted FilterIntroduction
Remember that we can make filters by using convolution, that is summing the product between the input and the filter coefficients, the set of filter coefficients is sometime denoted "kernel", those coefficients can be a same value (simple moving average), a linear function (linearly weighted moving average), a gaussian function (gaussian filter), a polynomial function (lsma of degree p with p = order of the polynomial), you can make many types of kernels, note however that it is easy to fall into the redundancy trap.
Today a low-lag filter who weight the price with a damped sine wave is proposed, the filter characteristics are discussed below.
A Damped Sine Wave
A damped sine wave is a like a sine wave with the difference that the sine wave peak amplitude decay over time.
A damped sine wave
Used Kernel
We use a damped sine wave of period length as kernel.
The coefficients underweight older values which allow the filter to reduce lag.
Step Response
Because the filter has overshoot in the step response we can conclude that there are frequencies amplified in the passband, we could have reached to this conclusion by simply seeing the negative values in the kernel or the "zero-lag" effect on the closing price.
Enough ! We Want To See The Filter !
I should indeed stop bothering you with transient responses but its always good to see how the filter act on simpler signals before seeing it on the closing price. The filter has low-lag and can be used as input for other indicators
Filter with length = 100 as input for the rsi.
The bands trailing stop utility using rolling squared mean average error with length 500 using the filter of length 500 as input.
Approximating A Least Squares Moving Average
A least squares moving average has a linear kernel with certain values under 0, a lsma of length k can be approximated using the proposed filter using period p where p = k + k/4 .
Proposed filter (red) with length = 250 and lsma (blue) with length = 200.
Conclusions
The use of damping in filter design can provide extremely useful filters, in fact the ideal kernel, the sinc function, is also a damped sine wave.
Zero Lag MACD [ChuckBanger]This is an MACD indicator with the ability to use zeror lag moving average instead of exponential moving average. I also added different background color when histogram is over or under center line, MACD Leader, Laguerre filter and dots to indicate when Leader line crosses macd line. Good luck traders!
Kaufman Adaptive Least Squares Moving AverageIntroduction
It is possible to use a wide variety of filters for the estimation of a least squares moving average, one of the them being the Kaufman adaptive moving average (KAMA) which adapt to the market trend strength, by using KAMA in an lsma we therefore allow for an adaptive low lag filter which might provide a smarter way to remove noise while preserving reactivity.
The Indicator
The lsma aim to minimize the sum of the squared residuals, paired with KAMA we obtain a great adaptive solution for smoothing while conserving reactivity. Length control the period of the efficiency ratio used in KAMA, higher values of length allow for overall smoother results. The pre-filtering option allow for even smoother results by using KAMA as input instead of the raw price.
The proposed indicator without pre-filtering in green, a simple moving average in orange, and a lsma with all of them length = 200. The proposed filter allow for fast and precise crosses with the moving average while eliminating major whipsaws.
Same setup with the pre-filtering option, the result are overall smoother.
Conclusion
The provided code allow for the implementation of any filter instead of KAMA, try using your own filters. Thanks for reading :)
Polynomial LSMA Estimation - Estimating An LSMA Of Any DegreeIntroduction
It was one of my most requested post, so here you have it, today i present a way to estimate an LSMA of any degree by using a kernel based on a sine wave series, note that this is originally a paper that i posted that you can find here figshare.com , in the paper you will be able to find the frequency response of the filter as well as both python and pinescript code.
The least squares moving average or LSMA is a filter that best fit a polynomial function through the price by using the method of least squares, by default the LSMA best fit a line through the input by using the following formula : ax + b where x is often a linear series 1,2,3...etc and a/b are parameters, the LSMA is made by finding a and b such that their values minimize the sum of squares between the lsma and the input.
Now a LSMA of 2nd degree (quadratic) is in the form of ax^2 + bx + c , although the first order LSMA is not hard to make the 2nd order one is way more heavy in term of codes since we must find optimal values for a , b and c , therefore we may want to find alternatives if the goal is simply data smoothing.
Estimation By Convolution
The LSMA is a FIR filter which posses various characteristics, the impulse response of an LSMA of degree n is a polynomial of the same degree, and its step response is a polynomial of degree n+1, estimating those step response is done by the described sine wave series :
f(x) =>
sum = 0.
b = 0.
pi = atan(1)*4
a = x*x
for i = 1 to d
b := 1/i * sin(x*i*pi)
sum := sum + b
pol = a + iff(d == 0,0,sum)
which is simple the sum of multiple sine waves of different frequency and amplitude + the square of a linear function. We then differentiate this result and apply convolution.
The Indicator
length control the filter period while degree control the degree of the filter, higher degree's create better fit with the input as seen below :
Now lets compare our estimate with actual LSMA's, below a lsma in blue and our estimate in orange of both degree 1 and period 100 :
Below a LSMA of degree 2 (quadratic) and our estimate with degree 2 with both period 100 :
It can be seen that the estimate is doing a pretty decent job.
Now we can't make comparisons with higher degrees of lsma's but thats not a real necessity.
Conclusion
This indicator wasn't intended as a direct estimate of the lsma but it was originally based on the estimation of polynomials using sine wave series, which led to the proposed filter showcased in the article. So i think we can agree that this is not a bad estimate although i could have showcased more statistics but thats to many work, but its not that interesting to use higher degree's anyways so sticking with degree 1, 2 and 3 might be for the best.
Hope you like and thanks for reading !
Turbo Scaler - The Art Of Being (too) EarlyIntroduction
Fast smooth indicators that produce early signals can sound utopic but mathematically its not a huge deal, the effect of early outputs based on smooth inputs can be seen on differentiators crosses, this is why i propose this indicator that aim to return extra fast signals based on a slightly modified max-min normalization method. The indicator introduce inherent smoothing without having an huge impact on the indicator reactivity.
The Indicator
The indicator is based on max-min normalization (like the stochastic oscillator) however instead of using the highest/lowest of the input we use the highest and lowest of the moving average of the input. This process using as input the closing price and the moving average closing price will return two lines, and because of the nature of max-min normalization we can see that the trigger line (in orange) produce earlier crosses. length control the highest/lowest period while smooth control the output lines smoothness (50 by default).
alpha control the scaling amount, with higher values of alpha creating more constrained scale, when alpha = 1 the scale is in a range of (0,1) while lower values of alpha can make the output move more freely.
alpha = 0.25
alpha = 1
Higher values of alpha create earlier signals.
Downsides Of Early Crosses
Of course such indicator make us exposed to the trend as seen below.
We can nonetheless protect ourselves against such cases scenarios by lowering alpha.
lowering alpha allow to catch movements of the trend without loosing much reactivity at the cost of an increased umber of trades.
Possible Uses
The proposed indicator allow for an high number of uses because of its scale, reactive nature...etc. A method that allow us to go with the main trend is by taking into account the crosses between the lines and the sign of the lines, for example :
The first signal (green) happen when the main line (in blue) crossover the trigger (orange) while both are > 0, the same happen with the second signal however both lines are < 0. This method can use certain levels instead of the sign (main line crossover trigger while both > 0.7...etc).
This method is great for the indicator because such cases scenarios does not happen a lot with ranging markets, we can clearly that when trending the trigger can have the tendency to be flat and higher than 0 thus allowing for the main line to produce those signals.
Conclusion
I have presented a super reactive crosses indicator based on max-min normalization with the ability to both be smooth and produce early entries/exits signals, different methods have been presented in order to allow for different setups using this indicator.
The introduction of the alpha parameter allow for more control which is what those kind of indicators needs. I hope you find an use to it :)
Support Me
Making indicators sure is hard, it takes time and it can be quite lonely to, so i would love talking with you guys while making them :) There isn't better support than the one provided by your friends so drop me a message.
ZeroLag MAsZeroLag MAs using DEMA and TEMA inside it.
Added Bollinger Bands to spot bottom and top easier too.
Enhanced Zero Lag indicator - Dr. John EhlersThis is my PSv4.0 enhanced version of Dr. John Ehlers' Zero Lag Indicator with I.P.O.C.S. that uses a novel EMA based error correcting technique. It accepts a floating point number for the critical period providing ultimate tunability in my version. What's visually appealing about this indicator is the crossover turning points are marked with highly visible circles, none of those plain old dots. Also, for the first time. I am releasing my "Neon Source" plot feature in a bright stunning yellow corona. Charts these days charts have so many plots on them, so I devised a unique way to resolve any confusion by emulating neon light. You may still easily use candles with this neon line too, or just simply disable it if you wish.
I provided an assortment of vibrant color schemes for those of you who may have color blindness vision impairments. You may contact me in private if these color schemes are not suitable for your diagnosed visual impairment, and you would wish to contribute to seeing the color schemes improved along with other future indicators I shall release. This also displays that color scheming is VERY possible in Pine.
Features List Includes:
I.P.O.C.S.(Initial Public Offering Clean Start) Technology - plotting from day one, minute one of IPO
Enable/disable dark background for enhanced visibility
"Source" selection
"Period" adjustment that accepts any floating point number
"Gain Limit" adjustment to reduce latency/lag
Multiple color schemes
"Neon Source" has a brightness control with an enable/disable capability
This is not a freely available indicator, FYI. To witness my Pine poetry in action, properly negotiated requests for unlimited access, per indicator, may ONLY be obtained by direct contact with me using TV's "Private Chats" or by "Message" hidden in my member name above. The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. If you do have any questions or comments regarding this indicator, I will consider your inquiries, thoughts, and ideas presented below in the comments section, when time provides it. When my indicators achieve more prevalent use by TV members, I will implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
Fisher Least Squares Moving AverageIntroduction
I already estimated the least-squares moving average numerous times, one of the most elegant ways was by rescaling a linear function to the price by using the z-score, today i will propose a new smoother (FLSMA) based on the line rescaling approach and the inverse fisher transform of a scaled moving average error with the goal to provide an alternative least-squares smoother, the indicator won't use the correlation coefficient and will try to adresses problems such as overshoots and lag reduction.
Line Rescaling Method
For those who did not see my least squares moving average estimation using the line rescaling method here is a resume, we want to fit a polynomial function of degree 1 to the price by reducing the sum of squares between the price and the filter, squares is a term meaning the squared difference between the price and its estimation. The line rescaling technique work as follow :
1 - get the z-score of a line.
2 - multiply this z-score with the correlation between the price and a line.
3 - multiply the precedent result with the standard deviation of the price, then sum that to a simple moving average.
This process is shorter than the classical least-squares moving average method.
Z-Score Derivation And The Inverse Fisher Transform
The FLSMA will use a similar approach to the line rescaling technique but instead of using the correlation during step 2 we will use an alternative calculated from the error between the estimate and the price.
In order to do so we must use the inverse fisher transform, the inverse fisher transform can take a z-score and scale it in a range of (1,-1), it is possible to estimate the correlation with it. First lets create our modified z-score in the form of : Z = ma((y - Y)/e) where y is the price, Y our output estimate and e the moving average absolute error between the price and Y and lets call it scaled smoothed error , then apply the inverse fisher transform : r = IFT(Z) = tanh(Z) , we then multiply the z-score of the line with it.
Performance
The FLSMA greatly reduce the overshoots, this mean that the maximas of abs(r) are lower than the maxima's of the absolute correlation, such case is not "bad" but we can see that the filter is not closer to the price than the LSMA during trending periods, we can assume the filter don't reduce least-squares as well as the LSMA.
The image above is the running mean of the absolute error of each the FLSMA (in red) and the LSMA (in blue), we could fix this problem by multiplying the smooth scaled error by p where p can be any number, for example :
z = sma(src - nz(b ,src),length)/e * p where p = 2
In red the FLSMA and in blue the FLSMA with p = 2 , the greater p is the less lag the FLSMA will have.
Conclusion
It could be possible to get better results than the LSMA with such design, the presented indicator use its own correlation replacement but it is possible to use anything in a range of (1,-1) to multiply the line z-score. Although the proposed filter only reduce overshoots without keeping the accuracy of the LSMA i believe the code can be useful for others.
Thanks for reading.
Engulfing + MACD/MACD ZL + MAHi everyone
This is a simple algorithm that I used on timeframe > m30 to detect strong reversal signals based on :
- Engulfing pattern
- MACD ZL 12, 26, 9
- Price vs SMA 7
Last two parameters are optional but gives more security. Otherwise, waiting for confirmation gives later entry.
Up to you to find the right balance between too much security (and taking the trade too late) and not enough confirmation (taking the trade too early and it will go the opposite way)
I recommend the novice traders (less than 2 years trading), to stick with the 3 parameters above .
It's to be used after a strong moment and as we're talking about reversals, I mean trade against the current trend.
Meaning they're more risky, so... you know the drill :) :
- Tight SL
- Protect the position quickly when going in the way you want
- Don't aim for very high TP. Have a few laddered obviously in any case
- Use a trailing stop to protect your gains
Hope you'll like it
Enjoy
Dave