Zero Lag Detrended Price Oscillator (ZL DPO)This indicator attempts to create a zero lag Detrended price oscillator using 2 different scripts. I actually really like the results so far. I hope you all find it useful too.
Green>Red = long
Red>Green = short
The lines on the example chart are some of the signals that the indicator gave on default settings.
The greens are wins, reds are outright losses, and blues are "scratch" trades(signal for other side before hitting stop loss).
All of the signals tested were using NNFX money management to see if they are wins or losses(1.5x atr for SL and 1 Atr for TP).
Nolag
WMA CrossoverNormally we have Moving average which is lagging indicator but in this script we have removed the lag and get signal upfront to maximize the profit and minimize the losses.
This is good for Entry purpose, for exit also it can be used but profit might be less. It is suggested to use one of the below method for exit
Target based
RSI divergence or
Price & Volume Based Analysis
VWAP (Volume for Index (Nifty & BankNifty is not available on Tradingview. Investing.com can be used for the same.)
If need more information on any of the above method, Please comment i will share more information on this either on tradingview or could be on the yourtube video.
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 !
IIR Least-Squares EstimateIntroduction
Another lsma estimate, i don't think you are surprised, the lsma is my favorite low-lag filter and i derived it so many times that our relationship became quite intimate. So i already talked about the classical method, the line-rescaling method and many others, but we did not made to many IIR estimate, the only one was made using a general filter estimator and was pretty inaccurate, this is why i wanted to retry the challenge.
Before talking about the formula lets breakdown again what IIR mean, IIR = infinite impulse response, the impulse response of an IIR filter goes on forever, this is why its infinite, such filters use recursion, this mean they use output's as input's, they are extremely efficient.
The Calculation
The calculation is made with only 1 pole, this mean we only use 1 output value with the same index as input, more poles often means a transition band closer to the cutoff frequency.
Our filter is in the form of :
y = a*x+y - a*ema(y,length/2)
where y = x when t = 1 and y(1) when t > 2 and a = 4/(length+2)
This is also an alternate form of exponential moving average but smoothing the last output terms with another exponential moving average reduce the lag.
Comparison
Lets see the accuracy of our estimate.
Sometimes our estimate follow better the trend, there isn't a clear result about the overshoot/undershoot response, sometimes the estimate have less overshoot/undershoot and sometime its the one with the highest.
The estimate behave nicely with short length periods.
Conclusion
Some surprises, the estimate can at least act as a good low-lag filter, sometimes it also behave better than the lsma by smoothing more. IIR estimate are harder to make but this one look really correct.
If you are looking for something or just want to say thanks try to pm me :)
Thank for reading !
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.
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 :)
Zero Lag - ZigZag - JDThis is a alternative version of the well known "ZigZag indicator" but it uses turning points of the Jurik ma
instead of the traditional "pivot points" that are by definition lagging by a large lookback period, the (almost-) Zero Lag ZigZag lags by about 2 bars on average (depending on the candles forming)
The ZigZag pattern can be used to draw trendlines and S/R lines
It can also be used for "wave counting" in a way that reduces interpretation.
If you find other uses, please leave your ideas in the comments!
Shoutout to Everget for the awesome Jurik code!!
JD.
#NotTradingAdvice #DYOR
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 StochasticAdapt To The Right Situation
There are already some Adaptive Stochastic scripts out there, but i didn't see the concept of using different periods highest/lowest for their calculations. What we want
for such oscillator is to be active when price is trending and silent during range periods. Like that the information we will see will be clear and easy to use.
Switching between a long term highest/lowest during range periods and a short term highest/lowest during trending periods is what will create the adaptive stochastic.
The switching is made thanks to the Efficiency Ratio , the period of the efficiency ratio is determined by the length parameter.
The period of the highest and lowest will depend on the slow and fast parameters, if our efficiency ratio is close to one (trending market) then the indicator will use highest and lowest of period fast , making the indicator more reactive, if our efficiency ratio is low (ranging market) then the indicator will use highest and lowest of period slow , making the indicator less reactive.
The source of the indicator is a running line ( lsma ) of period slow-fast .
it is also possible to switch the parameters values, making the indicator reactive during ranging market and less reactive during trending ones.
Hope you enjoy
For any questions/demands feel free to pm me, i would be happy to help you
Recursive StochasticThe Self Referencing Stochastic Oscillator
The stochastic oscillator bring values in range of (0,100). This process is called Feature scaling or Unity-Based Normalization
When a function use recursion you can highlights cycles or create smoother results depending on various factors, this is the goal of a recursive stochastic.
For example : k = s(alpha*st+(1-alpha)*nz(k )) where st is the target source.
Using inputs with different scale level can modify the result of the indicator depending on which instrument it is applied, therefore the input must be normalized, here the price is first passed through a stochastic, then this result is used for the recursion.
In order to control the level of the recursion, weights are distributed using the alpha parameter. This parameter is in a range of (0,1), if alpha = 1, then the indicator act as a normal stochastic oscillator, if alpha = 0, then the indicator return na since the initial value for k = 0. The smaller the alpha parameter, the lower the correlation between the price and the indicator, but the indicator will look more periodic.
Comparison
Recursive Stochastic oscillator with alpha = 0.1 and bellow a classic oscillator (alpha = 1)
The use of recursion can both smooth the result and make it more reactive as well.
Filter As Source
It is possible to stabilize the indicator and make it less affected by outliers using a filter as input.
Lower alpha can be used in order to recover some reactivity, this will also lead to more periodic results (which are not inevitably correlated with price)
Hope you enjoy
For any questions/demands feel free to pm me, i would be happy to help you
Kalman SmootherA derivation of the Kalman Filter.
Lower Gain values create smoother results.The ratio Smoothing/Lag is similar to any Low Lagging Filters.
The Gain parameter can be decimal numbers.
Kalman Smoothing With Gain = 20
For any questions/suggestions feel free to contact me
Adaptive Least SquaresAn adaptive filtering technique allowing permanent re-evaluation of the filter parameters according to price volatility. The construction of this filter is based on the formula of moving ordinary least squares or lsma , the period parameter is estimated by dividing the true range with its highest. The filter will react faster during high volatility periods and slower during low volatility ones.
High smooth parameter will create smoother results, values inferior to 3 are recommended.
You can easily replace the parameter estimation method as long as the one used fluctuate in a range of , for example you can use the efficiency ratio
ER = abs(change(close,length))/sum(abs(change(close)),length)
Or the Fractal Dimension Index , in fact any values will work as long as they are rescaled (stoch(value,value,value,length)/100)
For any suggestions/questions feel free to send me a message :)
Quadratic RegressionA quadratic regression is the process of finding the equation that best fits a set of data.This form of regression is mainly used for smoothing data shaped like a parabola.
Because we can use short/midterm/longterm periods we can say that we use a Quadratic Least Squares Moving Average or a Moving Quadratic Regression.
Like the Linear Regression (LSMA) a Quadratic regression attempt to minimize the sum of squares (sum of the squared difference between a set of data and an estimator), this is why
those kinds of filters have low lag .
Here the difference between a Least Squared Moving Average ( green ) and a Quadratic Regression ( red ) of both period 500
Here it look like the Quadratic Regression have a best fit than the LSMA
Double Exponential SmoothingSingle Exponential Smoothing ( ema ) does not excel in following the data when there is a trend. This situation can be improved by the introduction of a second equation with a second constant gamma .
The gamma constant cant be lower than 0 and cant be greater than 1, higher values of gamma create less lag while preserving smoothness.Higher values of length must be followed by higher values of gamma in order to keep the lag low.
The first smoothing part consist of a classic ema but we add s-s1 to the previous smoothed value, this will help decrease lag.The second smoothing part then updates the trend, which is expressed as the difference between the last two values.
Regression Line Formula
A regression line is simply a single line that best fits the data.
In the pinescript you can plot a linear regression line using the linreg function.
Here i share the entire calculation of the linear regression line, you are free to take the code and modify the functions in the script for creating your own kind of filter.
Hope you enjoy :)
ZeroLag ema + adx = trueCombined LazyBears ZeroLag EMA and CapnOscars moving average ADX. Here's the result.
I figured it could be used as a trend trendtrading system,
ADX red + ema cross downards = short.
ADX green + ema cross up = long.
ADX black + ema cross = no trade
Or something along those line. A way filter out whipsaws.
This is just something I threw together in 5 min, so din't go all in tho. Haven't had time to test.
2 ADX
3 Z-EMAs
Colors/settings can be customized.
4S4Slopes. hecate
==============
Using 4 smoothed Slopes (not lagging) and checking when they start to decrease (entering the orange zone) we can either get a general idea (although quite chaotic) view or general tendency of all together .
OR
Use them trading the equity in 4 parts. one will be trading on faster movements (faster slope), second slightly slower and the other two slower and slower. Faster ones will be more profitable but more aggressive and risky than the slower ones.