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!
Zerolag
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!
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 :)
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.
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.
UjanjaUjanja uses Zero Lag EMA combined with Hull Moving Average for smoothing purposes. It is a less aggressive. It is only to be used with huge volume , huge momentum and high volatility to get trend analysis... It doesn't repaint at all.
Advised use :
Trades highly volatile Crypto currencies, stocks as well as Gold .
It is only to be used with huge momentum and high volatility to get trend analysis... It doesn't repaint at all.
3HMAIntroduction
The Hull smoothing method aim to reduce the lag of a moving average by using a simple calculation involving smoothing with a moving average of period √p the subtraction of a moving average of period p/2 multiplied by 2 with another moving average of period p , however it is possible to extend this calculation by introducing more terms thus reducing both the lag and overshoot of the classical HMA.
Comparison
The proposed filter add 1 more term to the classical hull moving average thus ending with : sma(sma(p/3) * 3 - sma(p/2) - sma(p),p) , this can be developed as long as every terms add to total unity, more terms will often require more smoothing, this is why i replace √p by p .
In blue a HMA and in red the proposed filter of both period 50. The third term added allow for more reactivity which sometimes allow for overshoots with lower amplitudes.
Conclusions
Adding more terms to certain filtering methods can correct certain behaviours as well as reducing lag or increasing smoothing.
Modular Filter - Spot Trends And Smooth PriceIntroduction
This indicator can have a wide variety of usages, and since it is based on exponential averaging then the whole indicator can be made adaptive, thus ending up with a really promising tool. This indicator who can both smooth price and act as a trailing stop depending on user preferences, i tried to make it as reactive, stable and efficient as possible in order to both smooth and spot trends, lets view it more in depth.
The Indicator
line 8 and 9 create two bands, one upper and one lower, then based on certain conditions the indicator will only return a certain band or an average of both with different weights, this weight is controlled by the beta parameter, values of 1 will return a simple filter while values of 0 will return a classical trailing stop.
beta = 0
The indicator can use output values as input, thus using smoother values as input, in order to do so just check "Feedback", this help the overall output to be smoother as well as giving more long terms signals
The amount of feedback is controlled by the feedback weighting parameter, lower values will weight more the output values thus creating smoother results.
Feedback weighting of 0.2
Using beta = 0 thus having the indicator act as a trailing stop while having the feedback option activated return more long terms signals. Notes that the colors are based on the initial conditions of the indicator.
Conclusion
You can replace length and change alpha for any smoothing variable such as the efficiency ratio or anything with scale (1,0), same goes for beta and the feedback weighting parameter, this is why the indicator is "Modular" in addition of providing different usages. This indicator can look like cluster filters (smooth price monarch, forexguru) , filters with the ability to follow the price quite fine while being stables. I really hope you find an use to it.
Thanks for reading !
Turbo TriggerSome Words
This indicator is a collaboration between me and Himeyuri, i encourage you to check her profile and follow her www.tradingview.com
Introduction
A lot of indicators include a "trigger" line, it can be a smoothed version of another input, in this case the trigger will generate signals from his crosses with the input. The purpose of this indicator is to provide a fast trigger line to generate earlier signals as well as avoiding some whipsaw.
The Indicator
There are two lines, a bull line (blue) and the trigger (orange) , when the trigger cross over the bull line a buy signal is generated, when the trigger cross under the bull line a sell signal is generated. The trigger is made from the smoothed difference between the bull and bear line.
smooth control the smoothness of the output. The Bull/Bear Mode is an idea proposed by Himeyuri that involve plotting the bear line instead of the trigger.
Bull/Bear Mode, the lines are somewhat asymmetrical from each others.
Conclusion
We have showcased a new indicator who use a really fast trigger line to generate earlier signals, if some are way to earlier you can still increase smooth in order to correct reactivity. I hope you find a use to it.
Thanks for reading !
A big thanks to Himeyuri who is a great student and great pinescripter.
Well Rounded Moving AverageIntroduction
There are tons of filters, way to many, and some of them are redundant in the sense they produce the same results as others. The task to find an optimal filter is still a big challenge among technical analysis and engineering, a good filter is the Kalman filter who is one of the more precise filters out there. The optimal filter theorem state that : The optimal estimator has the form of a linear observer , this in short mean that an optimal filter must use measurements of the inputs and outputs, and this is what does the Kalman filter. I have tried myself to Kalman filters with more or less success as well as understanding optimality by studying Linear–quadratic–Gaussian control, i failed to get a complete understanding of those subjects but today i present a moving average filter (WRMA) constructed with all the knowledge i have in control theory and who aim to provide a very well response to market price, this mean low lag for fast decision timing and low overshoots for better precision.
Construction
An good filter must use information about its output, this is what exponential smoothing is about, simple exponential smoothing (EMA) is close to a simple moving average and can be defined as :
output = output(1) + α(input - output(1))
where α (alpha) is a smoothing constant, typically equal to 2/(Period+1) for the EMA.
This approach can be further developed by introducing more smoothing constants and output control (See double/triple exponential smoothing - alpha-beta filter) .
The moving average i propose will use only one smoothing constant, and is described as follow :
a = nz(a ) + alpha*nz(A )
b = nz(b ) + alpha*nz(B )
y = ema(a + b,p1)
A = src - y
B = src - ema(y,p2)
The filter is divided into two components a and b (more terms can add more control/effects if chosen well) , a adjust itself to the output error and is responsive while b is independent of the output and is mainly smoother, adding those components together create an output y , A is the output error and B is the error of an exponential moving average.
Comparison
There are a lot of low-lag filters out there, but the overshoots they induce in order to reduce lag is not a great effect. The first comparison is with a least square moving average, a moving average who fit a line in a price window of period length .
Lsma in blue and WRMA in red with both length = 100 . The lsma is a bit smoother but induce terrible overshoots
ZLMA in blue and WRMA in red with both length = 100 . The lag difference between each moving average is really low while VWRMA is way more precise.
Hull MA in blue and WRMA in red with both length = 100 . The Hull MA have similar overshoots than the LSMA.
Reduced overshoots moving average (ROMA) in blue and WRMA in red with both length = 100 . ROMA is an indicator i have made to reduce the overshoots of a LSMA, but at the end WRMA still reduce way more the overshoots while being smoother and having similar lag.
I have added a smoother version, just activate the extra smooth option in the indicator settings window. Here the result with length = 200 :
This result is a little bit similar to a 2 order Butterworth filter. Our filter have more overshoots which in this case could be useful to reduce the error with edges since other low pass filters tend to smooth their amplitude thus reducing edge estimation precision.
Conclusions
I have presented a well rounded filter in term of smoothness/stability and reactivity. Try to add more terms to have different results, you could maybe end up with interesting results, if its the case share them with the community :)
As for control theory i have seen neural networks integrated to Kalman flters which leaded to great accuracy, AI is everywhere and promise to be a game a changer in real time data smoothing. So i asked myself if it was possible for a neural networks to develop pinescript indicators, if yes then i could be replaced by AI ? Brrr how frightening.
Thanks for reading :)
Linear Quadratic Convergence Divergence OscillatorIntroduction
I inspired myself from the MACD to present a different oscillator aiming to show more reactive/predictive information. The MACD originally show the relationship between two moving averages by subtracting one of fast period and another one of slow period. In my indicator i will use a similar concept, i will subtract a quadratic least squares moving average with a linear least squares moving average of same period, since the quadratic least squares moving average is faster than the linear one and both methods have low-lag this will result in a reactive oscillator.
LQCD In Details
A quadratic least squares moving average try to fit a quadratic function (parabola) to the price by using the method of least squares, the linear least squares moving average try to fit a line. Non-linear fit tend to minimize the sum of squares in non-linear data, this is why a quadratic method is more reactive. The difference of both filters give us an oscillator, then we apply a simple moving average to this oscillator to provide the signal line, subtracting the oscillator and its signal line give us the histogram, those two last steps are the same used in the MACD.
Length control the period of the quadratic/linear moving average. While the MACD use a signal line for plotting the histogram i also added the option to plot the momentum of the quadratic moving average instead, the result is smoother and reduce irregularities, in order to do so just check the differential option in the parameter box.
The period of the signal line and the momentum are both controlled by the signal parameter.
A predictive approach can be made by subtracting the histogram with the signal line, this process make the histogram way more predictive, in order to do so just check the predictive histogram option in the parameter box.
Predictive histogram with simple histogram option. The differential mode can also be used with the predictive parameter, this result in a smoother but less reactive prediction.
Information Interpretation
The amount of information the MACD can give us is high. We can use the histogram as signal generator, or the if the oscillator is over/under 0, combine the oscillator/signal line with histogram, combinations can provide various systems. Some traders use the histogram as signal generator and use the cross between the histogram and the signal line as a stop signal, this method can avoid some whipsaw trades. The study of divergences with the price is also another method.
Conclusion
This oscillator aim to show the same amount of information as the MACD with a similar calculation method but using different kind of filters as well as eliminating the need to use two separates periods for the moving averages calculation, its still possible to use different periods for the quadratic/linear moving average but the results can be less accurate. This indicator can be used like the MACD.
Least Squares Moving Average With Overshoot ReductionIntroduction
The ability to reduce lag while keeping a good level of stability has been a major challenge for smoothing filters in technical analysis. Stability involve many parameters, one of them being overshoots. Overshoots are a common effect induced by low-lagging filters, they are defined as the ability of a signal output to exceed a target input. This effect can lead to major drawbacks such as whipsaw and reduction of precision. I propose a modification of the least squares moving average "Reduced Overshoots Moving Average" (ROMA) to reduce overshoots induced by the lsma by using a scaled recursive dispersion coefficient with the purpose of reducing overshoots.
Overshoots - Causes and Effects
Control theory and electronic engineering use step response to measure overshoots, the target signal is defined as an heaviside step function which will be used as input signal for our filter.
In white an input signal, in blue a least squares moving average with the input signal as source, the circle show the overshoot induced by the lsma, the filter exceed drastically the target input. But why low lag filters often induce overshoots ? This is because in order to reduce lag those filter will increase certain frequencies of the input signal, this reduce lag but induce overshoots because the amplitude of those frequencies have been increased, so its normal for the filter to exceed the input target. The increase of frequencies is not a bad process but when those frequencies are already of large amplitudes (high volatility periods) the overshoots can be seen.
Comparison With ROMA
Our method will use the line rescaling technique to estimate the lsma for efficiency sake. This method involve calculating the z-score of a line and multiplying it by the correlation of the line and the target input (price). Then we rescale this result by adding this z-score multiplied by the dispersion coefficient to a simple moving average. Lets compare the step response of our filer and the lsma.
ROMA (in red) need more data to be computed but reduce the mean absolute error in comparison with the classic lsma, it is seen that instead of following increasing, ROMA decrease thus ending with an undershoot.
ROMA in (red) and an lsma (in blue) with both length = 14, ROMA decrease overshoots with the cost of less smoothing, both filter match when there are no overshoots situations.
Both filters with length = 200, large periods increase the amplitude of overshoots, ROMA stabilize early at the cost of some smoothness.
The running Mean Absolute Error of both filters with length = 100, ROMA (in red) is on average closer to the price than the lsma (in blue)
Conclusion
I presented a modification of the least squares moving average with the goal to provide both stability and rapidity, the statistics show that ROMA do a better job when it comes to reduce the mean absolute error. Alternatives methods can involve decreasing the period it take for the filter to be on a steady state (reducing filter period during high volatility periods) , various filters already exploit this method.
Side Project
I'am not that good when it come to make my post easy to read, this is why i'am currently making an article explaining the basis of digital signal processing. This post will help you to understand signals and things such as lag, frequency transform, cycles, overshoots, ringing, FIR/IIR filters, impulse response, convolution, filter topology and many more. I love to post indicators but also making more educational content as well, so stay tuned :)
Thanks for reading, let me know if you need help with something, i would be happy to assist you.
please be kind to notify me if you find errors about the indicator in order for me to update it as fast as possible.
Multi Poles Zero-Lag Exponential Moving AverageIntroduction
Based on the exponential averaging method with lag reduction, this filter allow for smoother results thanks to a multi-poles approach. Translated and modified from the Non-Linear Kalman Filter from Mladen Rakic 01/07/19 www.mql5.com
The Indicator
length control the amount of smoothing, the poles can be from 1 to 3, higher values create smoother results.
Difference With Classic Exponential Smoothing
A classic 1 depth recursion (Single smoothing) exponential moving average is defined as y = αx + (1 - α)y which can be derived into y = y + α(x - y )
2 depth recursion (Double smoothing) exponential moving average sum y with b in order to reduce the error with x , this method is calculated as follow :
y = αx + (1 - α)(y + b)
b = β(y - y ) + (1-β)b
The initial value for y is x while its 0 for b with α generally equal to 2/(length + 1)
The filter use a different approach, from the estimation of α/β/γ to the filter construction.The formula is similar to the one used in the double exponential smoothing method with a difference in y and b
y = αx + (1 - α)y
d = x - y
b = (1-β)b + d
output = y + b
instead of updating y with b the two components are directly added in a separated variable. Poles help the transition band of the frequency response to get closer to the cutoff point, the cutoff of an exponential moving average is defined as :
Cf = F/2π acos(1 - α*α/(2(1 - α)))
Also in order to minimize the overshoot of the filter a correction has been added to the output now being output = y + 1/poles * b
While this information is far being helpful to you it simply say that poles help you filter a great amount of noise thus removing irregularities of the filter.
Conclusion
The filter is interesting and while being similar to multi-depth recursion smoothing allow for more varied results thanks to its 3 poles.
Feel free to send suggestions :)
Thanks for reading
Fibo Guppy Multi MA RevisedThis is Guppy MA i customized for myself based on two scripts of GMMA from JustUncleL and NeoButane.
Its features are:
1. Besides standard EMA you can chose all kinds of exotic moving average types ike ALMA (my favorite), HullMA, ZeroLag EMA, VWMA, KAMA etc...
2. Two types of coloring scheme - depends on volatility try one that's best fit.
3. Multiple sets of predefined lengths: standard Guppy 3-60, Fibonacci based lengths 3-610, Fibo 5-987 and Custom (user defined lengths)
General Filter Estimator-An Experiment on Estimating EverythingIntroduction
The last indicators i posted where about estimating the least squares moving average, the task of estimating a filter is a funny one because its always a challenge and it require to be really creative. After the last publication of the 1LC-LSMA , who estimate the lsma with 1 line of code and only 3 functions i felt like i could maybe make something more flexible and less complex with the ability to approximate any filter output. Its possible, but the methods to do so are not something that pinescript can do, we have to use another base for our estimation using coefficients, so i inspired myself from the alpha-beta filter and i started writing the code.
Calculation and The Estimation Coefficients
Simplicity is the key word, its also my signature style, if i want something good it should be simple enough, so my code look like that :
p = length/beta
a = close - nz(b ,close)
b = nz(b ,close) + a/p*gamma
3 line, 2 function, its a good start, we could put everything in one line of code but its easier to see it this way. length control the smoothing amount of the filter, for any filter f(Period) Period should be equal to length and f(Period) = p , it would be inconvenient to have to use a different length period than the one used in the filter we want to estimate (imagine our estimation with length = 50 estimating an ema with period = 100) , this is where the first coefficients beta will be useful, it will allow us to leave length as it is. In general beta will be greater than 1, the greater it will be the less lag the filter will have, this coefficient will be useful to estimate low lagging filters, gamma however is the coefficient who will estimate lagging filters, in general it will range around .
We can get loose easily with those coefficients estimation but i will leave a coefficients table in the code for estimating popular filters, and some comparison below.
Estimating a Simple Moving Average
Of course, the boxcar filter, the running mean, the simple moving average, its an easy filter to use and calculate.
For an SMA use the following coefficients :
beta = 2
gamma = 0.5
Our filter is in red and the moving average in white with both length at 50 (This goes for every comparison we will do)
Its a bit imprecise but its a simple moving average, not the most interesting thing to estimate.
Estimating an Exponential Moving Average
The ema is a great filter because its length times more computing efficient than a simple moving average. For the EMA use the following coefficients :
beta = 3
gamma = 0.4
N.B : The EMA is rougher than the SMA, so it filter less, this is why its faster and closer to the price
Estimating The Hull Moving Average
Its a good filter for technical analysis with tons of use, lets try to estimate it ! For the HMA use the following coefficients :
beta = 4
gamma = 0.85
Looks ok, of course if you find better coefficients i will test them and actualize the coefficient table, i will also put a thank message.
Estimating a LSMA
Of course i was gonna estimate it, but this time this estimation does not have anything a lsma have, no moving average, no standard deviation, no correlation coefficient, lets do it.
For the LSMA use the following coefficients :
beta = 3.5
gamma = 0.9
Its far from being the best estimation, but its more efficient than any other i previously made.
Estimating the Quadratic Least Square Moving Average
I doubted about this one but it can be approximated as well. For the QLSMA use the following coefficients :
beta = 5.25
gamma = 1
Another ok estimate, the estimate filter a bit more than needed but its ok.
Jurik Moving Average
Its far from being a filter that i like and its a bit old. For the comparison i will use the JMA provided by @everget described in this article : c.mql5.com
For the JMA use the following coefficients :
for phase = 0
beta = pow*2 (pow is a parameter in the Jma)
gamma = 0.5
Here length = 50, phase = 0, pow = 5 so beta = 10
Looks pretty good considering the fact that the Jma use an adaptive architecture.
Discussion
I let you the task to judge if the estimation is good or not, my motivation was to estimate such filters using the less amount of calculations as possible, in itself i think that the code is quite elegant like all the codes of IIR filters (IIR Filters = Infinite Impulse Response : Filters using recursion) .
It could be possible to have a better estimate of the coefficients using optimization methods like the gradient descent. This is not feasible in pinescript but i could think about it using python or R.
Coefficients should be dependant of length but this would lead to a massive work, the variation of the estimation using fixed coefficients when using different length periods is just ok if we can allow some errors of precision.
I dont think it should be possible to estimate adaptive filter relying a lot on their adaptive parameter/smoothing constant except by making our coefficients adaptive (gamma could be)
So at the end ? What make a filter truly unique ? From my point of sight the architecture of a filter and the problem he is trying to solve is what make him unique rather than its output result. If you become a signal, hide yourself into noise, then look at the filters trying to find you, what a challenging game, this is why we need filters.
Conclusion
I wanted to give a simple filter estimator relying on two coefficients in order to estimate both lagging and low-lagging filters. I will try to give more precise estimate and update the indicator with new coefficients.
Thanks for reading !
1LC-LSMA (1 line code lsma with 3 functions)Even Shorter Estimation
I know that i'am insistent with the lsma but i really like it and i'm happy to deconstruct it like a mad pinescript user. But if you have an idea about some kind of indicator then dont hesitate to contact me, i would be happy to help you if its feasible.
My motivation for such indicator was to use back the correlation function (that i had putted aside in the ligh-lsma code) and provide a shorter code than the estimation using the line rescaling method (see : Approximating A Least Square Moving Average In Pine) .
The Method
Fairly simple, lets name y our estimation, we calculate it as follow:
y = x̄ + r*o*1.7
where x̄ is the price moving average, r the correlation between the price and a line (or n) and o the standard deviation. If plotted against a classic lsma the difference would be meaningless at first glance so lets plot the absolute value between the difference of the lsma and our estimation of both period 100.
The difference is under 0.0000 on eurusd, its really low.
In general the longer the period of the estimation, the lower the difference between a normal lsma, but when using shorter period they can differ a little bit.
Why 1.7 ?
We need to multiply the standard deviation by a constant in order to match the overshoot and the rise-time of the original lsma. The constant 1.7 is one that work well but actually this constant should be dependant of the length period of the filter to make the estimation more accurate.
More About Step-Response
Most of the time when a filter have less lag, it mean that he induce overshoot in order to decrease the rise-time . Rise-time is the time the output take to match the target input, its related to the lag. Overshoot mean that the output exceed the target input, you can clearly see those concept in the image above.
Conclusion
I've showed that its possible to be even more concise about the code it take to estimate an lsma. I've also briefly explained the concept of rise-time and overshoot, concepts really important to signal processing and particularly in filter design. I'm sure that it can be even more simplified and i have some ideas for such estimate.
Thanks for reading !
Adaptive Zero Lag EMA [STUDY]A user has asked for the Study/Indicator version of this Strategy .
If you encounter the error "loop....>100ms" simply toggle the eye icon to hide and unhide the indicator
The following is simply quoted from my previous post for your convenience: (obviously there won't be risk, Stop Loss, or Take profit parameters!)
OPERATING PRINCIPLE
The strategy is based on Ehlers idea that any indicator can be turned into a signal-producing trade system through smoothing and other filtering processes.
In fact, I'm using his Zero Lag EMA ( ZLEMA ) as a baseline indicator as well as some code snippets he has made public (1). God bless open source!
Next, I've provided the option to use an Instantaneous Frequency Measurement (IFM) method, which will adaptively choose the best period for the ZLEMA (2)
I've written other studies that use the differential calculus approximations for IFM, so it was only natural to include them in this strategy.
The primary two are Cosine IFM (3) and In-phase Quadrature IFM (4). You can also find an indicator with both plotted and the ability to average them together, as one IFM prefers long periods and the other short. (5)
BEFORE WE BEGIN
1. This strategy only runs on "normal" FX pairs ( EURUSD , GBPJPY , AUDUSD ...) and will fail on Metals or Commodities.
Cryptos are largely untested.
2. Please run it on these time frames: M15 to D.
Anything outside this range will likely fail.
HOW TO USE AND SUCCEED
1. If the Default settings don't produce good results right off the bat, then lower gain limit to 1 or 2 and threshold to 0.01.
2. Test each setting under adaptive method. If you want to leave it Off, then I'd recommend using some kind of IFM (see my links below) to
discover the most efficient period to use.
3. Once you have the best adaptive method chosen, begin incrementing gain limit until you find a nice balance between profit factor ( PF ) and drawdown.
4. Now, begin incrementing threshold. The goal is to have PF above 2 and a drawdown as low as possible.
5. Finally, change the source! Typically, close is the best option, but I have run into cases where high
yielded the highest returns and win rate.
6. Sit back, relax, and tweak the risk until you're happy with the return and drawdown amounts.
ADVANCED
You may need to adjust take profit (TP) points and stop loss (SL) points to create the best entry possible. Don't be greedy! You'll likely have poor
results if the TP is set to 300 and SL is 50.
If you are trading a pair that has a long Dominant Cycle Period, then you may increase Max Period to allow the IFM
to accept longer periods. Any period above the Max Period will be rejected. This may increase lag time!
Cheers and good luck trading!
-DasanC
(1)www.mesasoftware.com
(2)www.jamesgoulding.com
(3) Cosine IFM
(4) I-Q IFM
(5) Averaging IFM
IFM stands for Instantaneous frequency measurement