Zero-Lag MA Trend Levels [ChartPrime] The Zero-Lag MA Trend Levels indicator combines a Zero-Lag Moving Average (ZLMA) with a standard Exponential Moving Average (EMA) to provide a dynamic view of the market trend. This indicator uses a color-changing cloud to represent shifts in trend momentum and plots key levels when trend reversals are detected. The addition of trend level boxes helps identify significant price zones where market shifts occur, with retest signals aiding in spotting potential continuation or reversal points.
⯁ KEY FEATURES & HOW TO USE
⯌ Zero-Lag Moving Average (ZLMA) with EMA Cloud :
The indicator employs a Zero-Lag Moving Average (ZLMA) alongside a standard EMA.
series float emaValue = ta.ema(close, length) // EMA of the closing price
series float correction = close + (close - emaValue) // Correction factor for zero-lag calculation
series float zlma = ta.ema(correction, length) // Zero-Lag Moving Average (ZLMA)
The cloud between these averages changes color depending on the trend direction. During a downtrend, if the ZLMA begins to increase, the cloud partially turns green, signaling potential strength. Conversely, during an uptrend, if the ZLMA decreases, the cloud partially turns to the downtrend color (blue by default), indicating potential weakness.
Use : Traders can monitor the cloud's color shifts for early signs of changing momentum. A fully colored cloud aligning with the current trend indicates a strong directional move, while mixed colors suggest a potential trend change.
⯌ Trend Shift and Level Boxes :
Each time a crossover between the EMA and the ZLMA occurs, indicating a trend shift, the indicator plots a box around the price level where the shift occurred. This box remains on the chart to mark the price zone of the trend change.
Use : The boxes provide clear visual markers of where market sentiment shifted. These levels can act as support and resistance zones. Traders can use these boxes to identify potential entry or exit points when the market retests these key levels.
⯌ Retest Detection with Labels :
If the price action crosses a previously plotted trend level box, the indicator marks this event with triangle labels. An upward triangle (▲) appears when the price retests the top of a box during a bullish crossover, and a downward triangle (▼) appears when the price retests the bottom of a box during a bearish crossunder.
Use : These labels help traders identify potential continuation or reversal points at critical price levels, offering additional confirmation for trading decisions.
⯌ Dynamic Color-Coding :
The color of the ZLMA and the EMA is adjusted according to their current trend direction, with the ZLMA adopting green for upward trends and blue for downward trends. This visual representation makes it easier to quickly gauge the market's momentum at a glance.
Use : Traders can use the color-coding to quickly assess the strength and direction of the current trend, allowing for more informed decision-making.
⯁ USER INPUTS
Length : Sets the period for both the ZLMA and EMA calculations.
Trend Levels : Toggle to display the trend level boxes on the chart.
Colors (+ / -) : Define the colors for bullish and bearish trends.
⯁ CONCLUSION
The Zero-Lag MA Trend Levels - ChartPrime indicator offers a nuanced approach to trend detection by combining the ZLMA with a traditional EMA. Its dynamic cloud color changes, trend level boxes, and retest labels make it a versatile tool for traders seeking to identify trend shifts and key price zones effectively. By incorporating elements of support and resistance along with trend momentum, this indicator provides a comprehensive view of market dynamics for both trend-following and counter-trend trading strategies.
Lag
TASC 2024.04 The Ultimate Smoother█ OVERVIEW
This script presents an implementation of the digital smoothing filter introduced by John Ehlers in his article "The Ultimate Smoother" from the April 2024 edition of TASC's Traders' Tips .
█ CONCEPTS
The UltimateSmoother preserves low-frequency swings in the input time series while attenuating high-frequency variations and noise. The defining input parameter of the UltimateSmoother is the critical period , which represents the minimum wavelength (highest frequency) in the filter's pass band. In other words, the filter attenuates or removes the amplitudes of oscillations at shorter periods than the critical period.
According to Ehlers, one primary advantage of the UltimateSmoother is that it maintains zero lag in its pass band and minimal lag in its transition band, distinguishing it from other conventional digital filters (e.g., moving averages ). One can apply this smoother to various input data series, including other indicators.
█ CALCULATIONS
Ehlers derived the UltimateSmoother using inspiration from the design principles he learned from his experience with analog filters , as described in the original publication. On a technical level, the UltimateSmoother's unique response involves subtracting a high-pass response from an all-pass response . At very low frequencies (lengthy periods), where the high-pass filter response has virtually no amplitude, the subtraction yields a frequency and phase response practically equivalent to the input data. At other frequencies, the subtraction achieves filtration through cancellation due to the close similarities in response between the high-pass filter and the input data.
Variety MA Cluster Filter [Loxx]Variety MA Cluster Filter is one method of creating a low-lag digital filter. This is done by calculating two moving averages and then comparing their output to the past value of the combined output and then choosing the max and min between the two moving averages to then determine the combined output. I've included standard deviation filtering for smoothing.
What is a Standard Deviation Filter?
If price or output or both don't move more than the (standard deviation) * multiplier then the trend stays the previous bar trend. This will appear on the chart as "stepping" of the moving average line. This works similar to Super Trend or Parabolic SAR but is a more naive technique of filtering.
Included
Bar coloring
Signals
Alerts
Loxx's Expanded Source Types
Loxx's Moving Averages
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).
Adjustable MA & Alternating Extremities [LuxAlgo]Returns a moving average allowing the user to control the amount of lag as well as the amplitude of its overshoots thanks to a parametric kernel. The indicator displays alternating extremities and aims to provide potential points where price might reverse.
Due to user requests, we added the option to display the moving average as candles instead of a solid line.
Settings
Length: MA period, refers to the number of most recent data points to use for its calculation.
Mult: Multiplicative factor for each extremity.
As Smoothed Candles: Allows the user to show the MA as a series of candles instead of a solid line.
Show Alternating Extremities : Determines whether to display the alternating extremities or not.
Lag: Controls the amount of lag of the MA, with higher values returning a MA with more lag.
Overshoot: Controls the amplitude of the overshoots returned by the MA, with higher values increasing the amplitude of the overshoots.
Usage
Moving averages using parametric kernels allows users to have more control over characteristics such as lag or smoothness; this can greatly benefit the analyst. A moving average with reduced lag can be used as a leading moving average in a MA crossover system, while lag will benefit moving averages used as slow MA in a crossover system.
Increasing 'Lag' will increase smoothness while increasing 'overshoot' will reduce lag.
The following indicator puts more emphasis on its alternating extremities, an upper extremity will be shown once the high price crosses the upper extremity, while a low extremity will be shown once the low price crosses the lower extremity. These can be interpreted like extremities of a band indicator.
The MA using a length value of 200 with a multiplicative factor of 1.
In general, extremities will effectively return points where price might potentially bounce in ranging markets while closing prices under trending markets will often be found above an upper extremity and under a lower extremity.
Reducing the lag of the moving average allows the user to obtain a more timely estimate of the underlying trend in the price, with a better fit overall. This allows the user to obtain potentially pertinent extremities where price might reverse upon a break, even under trending markets.
In the above chart, the price initially breaks the upper extremity, however, we can observe that the upper extremity eventually reaches back the price, goes above it, provides a resistance, and effectively indicates a reversal.
Users can plot candles from the moving average, these are fairly similar to heikin-ashi candles in the sense that CandleOpen(t) ≠ CandleClose(t-1) , each point of the candle is calculated as follows for our indicator:
Open = Average between MA(t-1) and MA(t-2)
High = MA using the high price as input
Low = MA using the low price as input
Close = MA using the closing price as input
Details
Lag is defined as the effect of moving averages to reflect past price variations instead of new ones, lag can be observed by the user and is the main cause of false signals. Lag is proportional to the degree of filtering returned by the moving average.
Overshooting is a common effect encountered in non-lagging moving averages, and is defined as the tendency of a moving average to exceed a maximum level (or minimum level, which can be defined as undershooting )
MA and rolling maximum/minimum, both using a length of 50 bars. While we can think of lag as a cost of smoothness, we can think of overshooting as a cost for reduced lag on some occasions.
Explaining the kernel design behind our moving average requires understanding of the logic behind lag reduction in moving averages. This can prove to be complex for non informed users, but let's just focus on the simpler part; moving averages can be defined as a weighted sum between past prices and a set of coefficients (kernel).
MA(t) = b(0)C(t) + b(1)C(t-1) + b(2)C(t-2) + ... + b(n-1)C(t-n-1)
Where n is the period of the moving average. Lag is (non optimally) reduced by "underweighting" past prices - that is multiplying them by negative numbers.
The kernel used in our moving average is based on a modified sinewave. A weighted sum making use of a sinewave as a kernel would return an oscillator centered at 0. We can divide this sinewave by an increasing linear function in order to obtain a kernel allowing us to obtain a low lag moving average instead of a centered oscillator. This is the main idea in the design of the kernel used by our moving average.
The kernel equation of our moving average is:
sin(2πx^α)(1 - x^β)
With 1>x>0 , and where α controls the lag, while β controls the overshoot amplitude.
Using this equation we can obtain the following kernels:
Here only α is changed, while β is equal to 1. Values to the left would represent the coefficients for the most recent prices. Notice how the most significant coefficients are given to the oldest prices in the case where α increases.
Higher overshoot would require more negative values, this is controlled by β
Here only β is changed, while α is equal to 1. Notice how higher values return lower negative coefficients. This effectively increases the overshoots amplitude in our moving average. We can decrease α in order for these negative coefficients to underweight more recent values.
Using α = 0 allows us to simplify the kernel equation to:
1 - x^β
Using this kernel we can obtain more classical moving averages, this can be seen from the following results:
Using β = 1 allows us to obtain a linearly decreasing kernel (the one of a WMA), while increasing allows the kernel to converge toward a rectangular kernel (the one of SMA).
ZLSMA - Zero Lag LSMAAn almost zero lag version of the LSMA (Least Squares Moving Average)
Gives instant linear regression of current price action.
This line works with the same rules as its "laggy" counterpart the LSMA:
When price crosses over it signals a bull trend.
When price crosses under it signals bear trend.
When price stays close or on the line sideways action is to be expected.
The direction of the line shows the direction of the trend.
[blackcat] L2 Ehlers Zero-lag SmootherLevel: 2
Background
John F. Ehlers introuced Zero-Lag Data Smoothers in Jul, 2002.
Function
John Ehlers introduced "Zero-Lag Data Smoothers", the infinite impulse response (IIR) filter and finite impulse response (FIR) filter.
In his article this issue on zero-lag smoothing, John Ehlers notes that his favorite filter is the symmetrically weighted six-bar finite impulse response (FIR) filter. This is also known as a triangular moving average, and can be conveniently implemented as a double-smoothed simple moving average. Per Ehlers, since this filter has six elements, its lag is 2.5 bars. Via further processing, this lag can be reduced to zero, but this produces too much overshoot. As a compromise, Ehlers suggests reducing the lag to one bar. To enable a user to adjust the lag easily, I provide the pine v4 code for an Adjustable Lag Filter indicator below. The first input, Price, should typically be set to OHLC, hl2, hl3, ohlc4 etc. The second input, LagReduction, should be set to a value in the zero-to-2.5 range. Setting it to zero will result in no adjustment, and the output will match that of the raw triangular average. Setting it to 2.5 will reduce the lag to zero. Setting it to 1.5 will reduce the lag to one bar.
Key Signal
Filter--> Zero-Lag Data Smoother fast line
Trigger--> Zero-Lag Data Smoother slow line
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 67th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
A Useful MA Weighting Function For Controlling Lag & SmoothnessSo far the most widely used moving average with an adjustable weighting function is the Arnaud Legoux moving average (ALMA), who uses a Gaussian function as weighting function. Adjustable weighting functions are useful since they allow us to control characteristics of the moving average such as lag and smoothness.
The following moving average has a simple adjustable weighting function that allows the user to have control over the lag and smoothness of the moving average, we will see that it can also be used to get both an SMA and WMA.
A high-resolution gradient is also used to color the moving average, makes it fun to watch, the plot transition between 200 colors, would be tedious to make but everything was made possible using a custom R script, I only needed to copy and paste the R console output in the Pine editor.
Settings
length : Period of the moving average
-Lag : Setting decreasing the lag of the moving average
+Lag : Setting increasing the lag of the moving average
Estimating Existing Moving Averages
The weighting function of this moving average is derived from the calculation of the beta distribution, advantages of such distribution is that unlike a lot of PDF, the beta distribution is defined within a specific range of values (0,1). Parameters alpha and beta controls the shape of the distribution, with alpha introducing negative skewness and beta introducing positive skewness, while higher values of alpha and beta increase kurtosis.
Here -Lag is directly associated to beta while +Lag is associated with alpha . When alpha = beta = 1 the distribution is uniform, and as such can be used to compute a simple moving average.
Moving average with -Lag = +Lag = 1 , its impulse response is shown below.
It is also possible to get a WMA by increasing -Lag , thus having -Lag = 2 and +Lag = 1 .
Using values of -Lag and +Lag equal to each other allows us to get a symmetrical impulse response, increasing these two values controls the heaviness of the tails of the impulse response.
Here -Lag = +Lag = 3 , note that when the impulse response of a moving average is symmetrical its lag is equal to (length-1)/2 .
As for the gradient, the color is determined by the value of an RSI using the moving average as input.
I don't promise anything but I will try to respond to your comments
Zalligator - Zero-Lag Alligator IndicatorI applied the zero-lag moving average theory to the Alligator Indicator. It seems like some different rules would would be required versus the traditional Alligator. Let me know what you think!
Moving Average Compendium===========
Moving Average Compendium (16 MA Types)
===========
A selection of the most popular, widely used, interesting and most powerful Moving Averages we can think of. We've compiled 16 MA's into this script, and allowed full access to the source code so you can use what you need, as you need it.
-----------
From very simple moving averages using built-in functions, all the way through to Fractal Adaptive Averages, we've tried to cover as much as we can think of! BUT, if you would like to make a suggestion or recommendation to be added to this compendium of MA's please let us know! Together we can get a complete list of many dozens of types of Moving Average.
Full List (so far)
---
SMA - Simple Moving Average
EMA - Exponential Moving Average
WMA - Weighted Moving Average
VWMA - Volume Weighted Moving Average
DEMA - Double Exponential Moving Average
TEMA - Triple Exponential Moving Average
SMMA - Smoothed Moving Average
HMA - Hull Moving Average
ZLEMA - Zero-Lag Exponential Moving Average
KAMA - Kaufman Adaptive Moving Average
JMA - Jurik Moving Average
SWMA - Sine-Weighted Moving Average
TriMA - Triangular Moving Average
MedMA - Moving Median Average
GeoMA - Geometric Mean Moving Average
FRAMA - Fractal Adaptive Moving Average
Line color changes from green (upward) to red (downward) - some of the MA types will "linger" without moving up or down and when they are in this state they should appear gray in color.
Thanks to all involved -
Good Luck and Happy Trading!
Filter Information Box - PineCoders FAQWhen designing filters it can be interesting to have information about their characteristics, which can be obtained from the set of filter coefficients (weights). The following script analyzes the impulse response of a filter in order to return the following information:
Lag
Smoothness via the Herfindahl index
Percentage Overshoot
Percentage Of Positive Weights
The script also attempts to determine the type of the analyzed filter, and will issue warnings when the filter shows signs of unwanted behavior.
DISPLAYED INFORMATION AND METHODS
The script displays one box on the chart containing two sections. The filter metrics section displays the following information:
- Lag : Measured in bars and calculated from the convolution between the filter's impulse response and a linearly increasing sequence of value 0,1,2,3... . This sequence resets when the impulse response crosses under/over 0.
- Herfindahl index : A measure of the filter's smoothness described by Valeriy Zakamulin. The Herfindahl index measures the concentration of the filter weights by summing the squared filter weights, with lower values suggesting a smoother filter. With normalized weights the minimum value of the Herfindahl index for low-pass filters is 1/N where N is the filter length.
- Percentage Overshoot : Defined as the maximum value of the filter step response, minus 1 multiplied by 100. Larger values suggest higher overshoots.
- Percentage Positive Weights : Percentage of filter weights greater than 0.
Each of these calculations is based on the filter's impulse response, with the impulse position controlled by the Impulse Position setting (its default is 1000). Make sure the number of inputs the filter uses is smaller than Impulse Position and that the number of bars on the chart is also greater than Impulse Position . In order for these metrics to be as accurate as possible, make sure the filter weights add up to 1 for low-pass and band-stop filters, and 0 for high-pass and band-pass filters.
The comments section displays information related to the type of filter analyzed. The detection algorithm is based on the metrics described above. The script can detect the following type of filters:
All-Pass
Low-Pass
High-Pass
Band-Pass
Band-Stop
It is assumed that the user is analyzing one of these types of filters. The comments box also displays various warnings. For example, a warning will be displayed when a low-pass/band-stop filter has a non-unity pass-band, and another is displayed if the filter overshoot is considered too important.
HOW TO SET THE SCRIPT UP
In order to use this script, the user must first enter the filter settings in the section provided for this purpose in the top section of the script. The filter to be analyzed must then be entered into the:
f(input)
function, where `input` is the filter's input source. By default, this function is a simple moving average of period length . Be sure to remove it.
If, for example, we wanted to analyze a Blackman filter, we would enter the following:
f(input)=>
pi = 3.14159,sum = 0.,sumw = 0.
for i = 0 to length-1
k = i/length
w = 0.42 - 0.5 * cos(2 * pi * k) + 0.08 * cos(4 * pi * k)
sumw := sumw + w
sum := sum + w*input
sum/sumw
EXAMPLES
In this section we will look at the information given by the script using various filters. The first filter we will showcase is the linearly weighted moving average (WMA) of period 9.
As we can see, its lag is 2.6667, which is indeed correct as the closed form of the lag of the WMA is equal to (period-1)/3 , which for period 9 gives (9-1)/3 which is approximately equal to 2.6667. The WMA does not have overshoots, this is shown by the the percentage overshoot value being equal to 0%. Finally, the percentage of positive weights is 100%, as the WMA does not possess negative weights.
Lets now analyze the Hull moving average of period 9. This moving average aims to provide a low-lag response.
Here we can see how the lag is way lower than that of the WMA. We can also see that the Herfindahl index is higher which indicates the WMA is smoother than the HMA. In order to reduce lag the HMA use negative weights, here 55% (as there are 45% of positive ones). The use of negative weights creates overshoots, we can see with the percentage overshoot being 26.6667%.
The WMA and HMA are both low-pass filters. In both cases the script correctly detected this information. Let's now analyze a simple high-pass filter, calculated as follows:
input - sma(input,length)
Most weights of a high-pass filters are negative, which is why the lag value is negative. This would suggest the indicator is able to predict future input values, which of course is not possible. In the case of high-pass filters, the Herfindahl index is greater than 0.5 and converges toward 1, with higher values of length . The comment box correctly detected the type of filter we were using.
Let's now test the script using the simple center of gravity bandpass filter calculated as follows:
wma(input,length) - sma(input,length)
The script correctly detected the type of filter we are using. Another type of filter that the script can detect is band-stop filters. A simple band-stop filter can be made as follows:
input - (wma(input,length) - sma(input,length))
The script correctly detect the type of filter. Like high-pass filters the Herfindahl index is greater than 0.5 and converges toward 1, with greater values of length . Finally the script can detect all-pass filters, which are filters that do not change the frequency content of the input.
WARNING COMMENTS
The script can give warning when certain filter characteristics are detected. One of them is non-unity pass-band for low-pass filters. This warning comment is displayed when the weights of the filter do not add up to 1. As an example, let's use the following function as a filter:
sum(input,length)
Here the filter pass-band has non unity, and the sum of the weights is equal to length . Therefore the script would display the following comments:
We can also see how the metrics go wild (note that no filter type is detected, as the detected filter could be of the wrong type). The comment mentioning the detection of high overshoot appears when the percentage overshoot is greater than 50%. For example if we use the following filter:
5*wma(input,length) - 4*sma(input,length)
The script would display the following comment:
We can indeed see high overshoots from the filter:
@alexgrover for PineCoders
Look first. Then leap.
Grand Trend Forecasting - A Simple And Original Approach Today we'll link time series forecasting with signal processing in order to provide an original and funny trend forecasting method, the post share lot of information, if you just want to see how to use the indicator then go to the section "Using The Indicator".
Time series forecasting is an area dealing with the prediction of future values of a series by using a specific model, the model is the main tool that is used for forecasting, and is often an expression based on a set of predictor terms and parameters, for example the linear regression (model) is a 1st order polynomial (expression) using 2 parameters and a predictor variable ax + b . Today we won't be using the linear regression nor the LSMA.
In time series analysis we can describe the time series with a model, in the case of the closing price a simple model could be as follows :
Price = Trend + Cycles + Noise
The variables of the model are the components, such model is additive since we add the component with each others, we should be familiar with each components of the model, the trend represent a simple long term variation of high amplitude, the cycles are periodic fluctuations centered around 0 of varying period and amplitude, the noise component represent shorter term irregular variations with mean 0.
As a trader we are mostly interested by the cycles and the trend, altho the cycles are relatively more technical to trade and can constitute parasitic fluctuations (think about retracements in a trend affecting your trend indicator, causing potential false signals).
If you are curious, in signal processing combining components has a specific name, "synthesis" , here we are dealing with additive synthesis, other type of synthesis are more specific to audio processing and are relatively more complex, but could be used in technical analysis.
So what to do with our components ? If we want to trade the trend, we should estimate right ? Estimating the trend component involve removing the cycle and noise component from the price, if you have read stuff about filters you should know where i'am going, yep, we should use filters, in the case of keeping the trend we can use a simple moving average of relatively high period, and here we go.
However the lag problem, which is recurrent, come back again, we end up with information easier to interpret (here the trend, which is a simple fluctuation such as a line or other smooth curve) at the cost of decision timing, that is unfortunate but as i said the information, here the moving average output, is relatively simple, and could be easily forecasted right ? If you plot a moving average of high period it would be easier for you to forecast its future values. And thats what we aim to do today, provide an estimate of the trend that should be easy to forecast, and should fit to the price relatively well in order to produce forecast that could determine the position of future closing prices observations.
Estimating And Forecasting The Trend
The parameter of the indicator dealing with the estimation of the trend is length , with higher values of length attenuating the cycle and noise component in the price, note however that high values of length can return a really long term trend unlike a simple moving average, so a small value of length, 14 for example can still produce relatively correct estimate of trend.
here length = 14.
The rough estimate of the trend is t in the code, and is an IIR filter, that is, it is based on recursion. Now i'll pass on the filter design explanation but in short, weights are constants, with higher weights allocated to the previous length values of the filter, you can see on the code that the first part of t is similar to an exponential moving average with :
t(n) = 0.9t(n-length) + 0.1*Price
However while the EMA only use the precedent value for the recursion, here we use the precedent length value, this would just output a noisy and really slow output, therefore in order to create a better fit we add : 0.9*(t(n-length) - t(n-2length)) , and this create the rough trend estimate that you can see in blue. On the parameters, 0.9 is used since it gives the best estimate in my opinion, higher values would create more periodic output and lower values would just create a rougher output.
The blue line still contain a residual of the cycle/noise component, this is why it is smoothed with a simple moving average of period length. If you are curious, a filter estimating the trend but still containing noisy fluctuations is called "Notch" filter, such filter would depending on the cutoff remove/attenuate mid term cyclic fluctuations while preserving the trend and the noise, its the opposite of a bandpass filter.
In order to forecast values, we simply sum our trend estimate with the trend estimate change with period equal to the forecasting horizon period, this is a really really simple forecasting method, but it can produce decent results, it can also allows the forecast to start from the last point of the trend estimate.
Using The Indicator
We explained the length parameter in the precedent section, src is the input series which the trend is estimated, forecast determine the forecasting horizon, recommend values for forecast should be equal to length, length/2 or length*2, altho i strongly recommend length.
here length and forecast are both equal to 14 .
The corrective parameter affect the trend estimate, it reduce the overshoot and can led to a curve that might fit better to the price.
The indicator with the non corrective version above, and the corrective one below.
The source parameter determine the source of the forecast, when "Noisy" is selected the source is the blue line, and produce a noisy forecast, when "Smooth" is selected the source is the moving average of t , this create a smoother forecast.
The width interval control...the width of the intervals, they can be seen above and under the forecast plot, they are constructed by adding/subtracting the forecast with the forecast moving average absolute error with respect to the price. Prediction intervals are often associated with a probability (determining the probability of future values being between the interval) here we can't determine such probability with accuracy, this require (i think) an analysis of the forecasting distribution as well as assumptions on the distribution of the forecasting error.
Finally it is possible to see historical forecasts, that is, forecasts previously generated by checking the "Show Historical Forecasts" option.
Examples
Good forecasts mostly occur when the price is close to the trend estimate, this include the following highlighted periods on AMD 15TF with default settings :
We can see the same thing at the end of EURUSD :
However we can't always obtain suitable fits, here it is isn't sufficient on BTCUSD :
We can see wide intervals, we could change length or use the corrective option to get better results, another option is to use a log scale.
We will end the examples with the log SPX, who posses a linear trend, so for example a linear model such as a linear regression would be really adapted, lets see how the indicator perform :
Not a great fit, we could try to use an higher length value and use "Smooth" :
Most recent fits are quite decent.
Conclusions
A forecasting indicator has been presented in this post. The indicator use an original approach toward estimating the trend component in the closing price. Of course i should have given statistics related to the forecasting error, however such analysis is worth doing with better methods and in more advanced environment allowing for optimization.
But we have learned some stuff related to signal processing as well as time series analysis, seeing a time series as the sum of various components is really helpful when it comes to make sense of chaotic and noisy series and is a basic topic in time series analysis.
You can see that in this new year i work harder on the visual of my indicators without trying to fall in the label addict trap, something that i wasn't really doing before, let me know what do you think of it.
Thanks for reading !
[e2] Reflex & TrendflexNew Indicator from John F. Ehlers issued in the February 2020 Technical Analysis of Stocks and Commodities article "Reflex: A New Zero-Lag Indicator"
This indicator includes both studies described in the article and intend to significantly reduce the lag of the signal compared to other oscillators.
Reflex for the cycle component and is more sensitive to major reversals, Trendflex for the trend component.
Pivot Max range as the borders for top and bottom reading of the indicators (the script will plot separate borders for both components) and divergences were added.
Divergence function is the interpretation of built-in divergence script, optimized the code and added option to show real-time divs (without offset), all credits to ...)
daily*tip: I must say that very quickly I began to realize how fragmented and imperfectly modern economic knowledge is and how little can be taken from fundamental science in terms of practical recipes. (c) Andrey Movchans.
stay safe ;)
CHK TimeSeriesLagReductionFilter[MULTI MA]This script is an improvement on the idea published on " Time Series Lag Reduction Filter "
This script allows users to select the Moving Average of his choice. Helps precise entries and precise exits.
Since every Moving Average is different, play with the settings to get the best fit. If the "Lag Reduce" overshoots bring down the number.
CREDITS ::
TO theheirophant for this idea
TO NEOBUTANE for his MULTI TYPE MOV AVG GUPPY
Thank You NEOBUTANE and Theheirophant.
This is my first publication :)
Sharing few examples what this script can do
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!
Lag-Less Rainbow RibbonThis is my polychromatic "Lag-Less Rainbow Ribbon" indicator using Pine Script version 4.0. I'm sure you may noticed by now, this indicator is truly an astounding rainbow to witness upon encountering it initially. It's jaw dropping beauty is the first of it's kind on TV, but will continue to shine here, or on your chart, so long as TV exists. This one isn't disappearing into non-existence any time soon.
It's extremely easy to use having only one input() to control the entire ribbon and it's lag. I couldn't make it any simpler to use, and that's one unique yet powerful feature of this elegant indicator. Another unique characteristic of deploying this in rainbow fashion is it provides very clear indications of when and where a significant reversal has occurred. Afterwards, trend direction following a large reversal is quickly established.
This script uses all 64 of the available plottable series TV will allow currently, so adding features to it may be impossible in the future. Yet the cloud handles it with ease and speed I have never encountered in a ribbon indicator before. The Pine Script in this indicator is highly optimized, coming in at a light weight 120+ lines of code, probably contributing to it's efficiency.
Lastly, with this flagship indicator, I included a multi-color "neon source" line to view close, hl2, etc... Any one of the two indicators may actually be enabled/disabled independently.
In the demonstration chart, you will witness the other color schemes available. I provided multiple 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 wish to contribute to seeing the color schemes improved along with other future indicators I shall release.
I.P.O.C.S.: "Initial Public Offering Clean Start" proprietary technology. Firstly, many of my other indicators already possess this capability. It allows suitable plotting from day one, minute one of IPO, remedying visually delayed signal analysis. It's basically accurate plotting from the very first bar (bar_index==0) on Tradingview. If you don't know what this is, most people don't, go back to the VERY beginning of any stock on the "All" chart and compare it to other similar indicators. What's so special about this? It is extremely difficult to get a healthy plot from bar_index==0 on any platform. However, I have become exceedingly talented performing this feat in most cases, but not all depending on the algorithm. This indicator is a successful accomplishment implementing IPOCS. It's inherent value is predominantly for IPO traders who in the past have had to wait 20, 50, and 150 bars before they obtain a precise indicator measurement for the simplest of algorithms in order to make a properly informed decision to potentially invest in an asset. How is this achieved? It's a highly protected secret of mine... but I will say I rarely use Pine built-in functions at all. When I do, I use them scarcely due to currently existing Pine language limitations.
Features List Includes:
I.P.O.C.S.(Initial Public Offering Clean Start) Technology
Enable/disable dark background for enhanced visibility
One "Lag Factor" adjustment to adjust them all
Color schemes
"Transparency" control
Independent "Source" options
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. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section if you do have any questions or comments regarding this indicator. 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 with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
MTF Even Better Sine Wave - Dr. John EhlersThis is my enhanced "MTF Even Better Sine Wave" indicator using Pine Script version 4.0. This originates from the book "Cycle Analytics for Traders" written by Dr. John Ehlers in Chapter 12. While the original was simplistically designed, I enhanced it by adding a multitude of features Pine Script now accommodates.
Most noticeably is the multiple time frame (MTF) features in the indicator "Settings". The three displayed indicators are using 5 second, 30 second, and 7 minute time frames. This may be the first PSv4.0 script to accommodate seconds in MTF adequately, but don't quote me on that. I haven't spent hours extensively looking for them. Be forewarned, second-based time frames are currently for Premium subscribers only, until such time in the future when the prerogative of TV might change. I will be adding second-based time frames to my other indicators where I feel it is beneficial to the indicator.
Unlike Dr. John Ehlers' other Sinewave indicator that is intended for identifying turning points in cycling price fluctuations, the "Even Better Sine Wave", having stochastic like qualities, is intended for trending assets.
Features List Includes:
I.P.O.C.S.(Initial Public Offering Clean Start) Technology
Enable/disable dark background for enhanced visibility
"Source" selection with multiple time frame adjustments - including seconds
"Duration" adjustment
"Super Smoother BandEdge" adjustment
"Display Area" selection for visual mutations displayed above
Ranges and thresholds are enable/disable capable
Upper threshold adjustment
Lower threshold adjustment
Adjustable centered medial zone
Normalized zero mean to +/-1
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 concepts 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 with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
Autonomous Recursive Moving AverageIntroduction
People often ask me what is my best indicators, i can't really respond to this question with a straight answer but i would say you to check this indicator. The Autonomous Recursive Moving Average (ARMA) is an adaptive moving average that try to minimize the sum of squares thanks to a ternary operator, this choice can seem surprising since most of the adaptive moving averages adapt to a smoothing variable thanks to exponential averaging, but there are lot of downsides to this method, i really wanted to have a flat filter during flat markets and this is what i achieved.
The Indicator
length control the amount of smoothing during trending periods, gamma is the trend sensitivity threshold, higher values of gamma will make an overall flat filter, adjust gamma to skip ranging markets.
gamma = 2, we can adjust to 3 while preserving smoothing reactivity with trading periods.
gamma = 3
low length and higher gamma create more boxy result, the filter add overshoots directly in the output, its unfortunate.
The Zero-Lag option can reduce the lag as well as getting additional flat results without changing gamma.
Conclusion
The indicator need work, but i can't leave without publishing it, the overshoots are a big problems, changing sma for another stable filter can help. I hope you find an use to it, i really like this indicator.
Thanks for reading
Zero-Lag Smoothed CycleOld indicator ! But its a simple trick to have a zero-lag smoothing effect, i think i did it because the smoothing was kinda asymmetrical with the detrended line. So even if the result appear quite good take into account that the detrended line isn't always correlated with the price.
BOSS Zero-Lag Dynamic MACDTHE BEST FOREX, BINARY OPTIONS, AND CRYPTO INDICATORS FOR TRADINGVIEW.COM
Our MACD is a Zero-Lag (well near zero-lag) We make this claim because MACD utilizes Moving Averages and as you know moving averages are lagging indicators.
For our MACD we utilize The McGinley Dynamic which looks like a moving average line yet it is a smoothing mechanism for prices that turns out to track far better than any moving average.
The McGinley Dynamic minimizes price separation, price whipsaws and hugs prices much more closely.
The McGinley Dynamic does this automatically as this is a factor of the formula.
Because of the calculation, the Dynamic Line speeds up in down markets as it follows prices yet moves more slowly in up markets.
As traders we want to be quick to sell in a down market, yet ride an up market as long as possible.
Source: Investopedia.com
Chart Image shows conventional MACD on Bottom and BOSS Zero-Lag Dynamic MACD on top
Available at: bosscripts.com
Fast Z-ScoreIntroduction
The ability of the least squares moving average to provide a great low lag filter is something i always liked, however the least squares moving average can have other uses, one of them is using it with the z-score to provide a fast smoothing oscillator.
The Indicator
The indicator aim to provide fast and smooth results. length control the smoothness.
The calculation is inspired from my sample correlation coefficient estimation described here
Instead of using the difference between a moving average of period length/2 and a moving average of period length , we use the difference between a lsma of period length/2 and a lsma of period length , this difference is then divided by the standard deviation. All those calculations use the price smoothed by a moving average as source.
The yellow version don't divide the difference by a standard deviation, you can that it is less reactive. Both version have length = 200
Conclusion
I presented a smooth and responsive version of a z-score, the result could be used to estimate an even faster lsma by using the line rescaling technique and our indicator as correlation coefficient.
Hope you like it, feel free to modify it and share your results ! :)
Notes
I have been requested a lot of indicators lately, from mt4 translations to more complex time series analysis methods, this accumulation of work made that it is impossible for me to publish those within a short period of time, also some are really complex. I apologize in advance for the inconvenience, i will try to do my best !
Zero Phase Filtering [Repaint] - ExperimentalImportant !
The indicator is for experimental purpose only, it must not be used as a decisional tool but only as a visual one (like Zig-Zag, Fractal etc). The information this indicator display is uncertain and subject to drastic changes over time. If you have further question feel free to pm me.
Introduction
Most of the filters you will find are causal, this mean that they depend on present and past input values, this explain the lag they produce. Non causal filters however will use future input values. A well know way to get a zero-phase filter is by using the forward backward method, but this is not possible in pinescript as i recall. So we have to use some kind of function that will display future values, this is possible using the security function in version 2 or the one in version 3 using barmerge.lookahead_on .
The Use Of A Repainting Indicator
Its always better to filter data in order to have a clearer view of what is happening, this can be useful when doing some forecasting or doing less formal kind of analysis. However since it repaint you cant use it as a signal provider or use signals of other indicators using this filter as source.
For example if you want to forecast a smooth indicator, the forecast of this indicator under normal circumstances could still have lag associated with it, so you would have to react before your forecast, this wont happen if you apply this filter as your indicator source.
The Filter
We smooth with a simple moving average the price provided by the security function twice, length control the smoothing level. Since security depend on the time frame you are in you must select your time frame in the indicator parameter selection window.
Filtering using 45 minutes time frame close price in a 5 minutes chart, we fix this by selecting our time frame.
Consider the fact that the input of the indicator is just periodic price, so sometimes the lag can sometimes be less or more than 0 and the estimation not centered.
The indicator can work on time frames up to 1h, after that the filter have some lag, i tried fixing this and i ended up having data errors.
Applying our filter as source for the rsi oscillator.
Conclusion
It is possible to have a kind of zero-phase filters, but it would be better if pinescript could support backward indexing thus making us able to do forward backward filtering.
Since noise can affect our analysis, applying smoothing without having to use offset in plot can be considered useful.
Light LSMAEstimating the LSMA Without Classics Parameters
I already mentioned various methods in order to estimate the LSMA in the idea i published. The parameter who still appeared on both the previous estimation and the classic LSMA was the sample correlation coefficient. This indicator will use an estimate of the correlation coefficient using the standard score thus providing a totally different approach in the estimation of the LSMA. My motivation for such indicator was to provide a different way to estimate a LSMA.
Standardization
The standard score is a statistical tool used to measure at how many standard deviations o a data point is bellow or above its mean. It can also be used to rescale variables, this conversion process is called standardizing or normalizing and it will be the basis of our estimation.
Calculation : (x - x̄)/o where x̄ is the moving average of x and o the standard deviation.
Estimating the Correlation Coefficient
We will use standardization to estimate the correlation coefficient r . 1 > r > -1 so in (y - x̄)/o we want to find y such that y is always above or below 1 standard deviation of x̄ , i had for first idea to pass the price through a band-stop filter but i found it was better to just use a moving average of period/2 .
Estimating the LSMA
We finally rescale a line through the price like mentioned in my previous idea, for that we standardize a line and we multiply the result by our correlation estimation, next we multiply the previous calculation by the price standard deviation, then we sum this calculation to the price moving average.
Comparison of our estimate in white with a LSMA in red with both period 50 :
Working With Different Independents Variables
Here the independent variable is a line n (which represent the number of data point and thus create a straight line) but a classic LSMA can work with other independent variables, for exemple if a LSMA use the volume as independent variable we need to change our correlation estimate with (ȳ - x̄)/ô where ȳ is the moving average of period length/2 of y, y is equal to : change(close,length)*change(volume,length) , x̄ is the moving average of y of period length , and ô is the standard deviation of y. This is quite rudimentary and if our goal is to provide a easier way to calculate correlation then the product-moment correlation coefficient would be more adapted (but less reactive than the sample correlation) .
Conclusion
I showed a way to estimate the correlation coefficient, of course some tweaking could provide a better estimate but i find the result still quite close to the LSMA.