Trend Regression Kernel [IkkeOmar]Kernel by @jdehorty huge shoutout to him! This is only an idea for how I use it when trading
All credit for the kernel goes to him, I did not make the kernel! I don't know how to make it more clear.
I use this to assist with top-down analysis.
timeframe I want to trade : timeframe to analyse with white noise and kernel:
1m : 1H
5m : 2H
15m : 4H
1H : 1D
In the chart you see that I have the 1H open, I use the white noise at a "lower setting length" (55 in this case), I change the source of to be the kernel on the higher timeframe. When a new trend is detected by the White noise I wait for price to retest the kernel before building a position. Another case described below:
Here i use the adaptive MCVF (I have made this free for everyone on TradingView) to buy when price is below the kernel while the trend for the white noise is bullish .
Notice that the Kernel is set on the 4H timeframe! The source of the white noise is the kernel!
Here is an example in a bearish trend:
Notice, I am on the 5m chart, kernel uses the 2H chart and the source of the white noise is the kernel.
I use the adaptive MCVF to help me get entries AFTER the first touch of the kernel.
Mandatory code explanation, with respect to the house rules:
Input settings:
Input Settings:
The script provides various input parameters to customize the indicator:
src: The source of price data, defaulted to closing prices.
h, r, x_0: Parameters for Kernel 1.
h2, r2, x_2: Parameters for Kernel 2.
Kernel Regression Functions:
Two functions kernel_regression1 and kernel_regression2 are defined to perform kernel regression calculations.
These functions estimate the trend using the Nadaraya-Watson kernel non-parametric regression method.
They take the source data (_src), the size of the data series (_size), and the lookback window (_h) as inputs.
They iterate over the data series and calculate the weighted sum of the values based on the specified kernel parameters.
The result is divided by the cumulative weight to obtain the estimated value.
Estimations:
The kernel_regression1 and kernel_regression2 functions are called with the respective parameters to estimate trends (yhat1 and yhat2).
Buy and Sell Signals:
Buy and sell signals are generated based on crossover and crossunder conditions between the two trend estimates (yhat1 and yhat2).
buySignal is true when yhat1 crosses above yhat2.
SellSignal is true when yhat1 crosses below yhat2.
Plotting:
The average of the two trend estimates (yhat1 and yhat2) is calculated and plotted.
The color of the plot is determined based on whether yhat1 is greater than yhat2, less than yhat2, or equal to yhat2.
Buy and sell signals are plotted using triangle shapes below and above bars, respectively.
Alerts:
Alert conditions are set based on buy and sell signals. Alerts are triggered when a crossover (long signal) or crossunder (short signal) occurs.
The alerts include information about the signal type, symbol, and price.
It's important to mention that the buy and sell signals from the indicator is very discretionary, I rarely use them, and if I do it's if they are in confluence with a correction i am biased towards or if it has confluence with some of my other systems.
The adaptive MCVF and White noise is free for everyone on TradingView, linked below:)
Huge shoutout to @jdehorty, original kernel below:
Nadaraya-watson
Nadaraya-Watson Envelope Strategy (Non-Repainting) Log ScaleIn the diverse world of trading strategies, the Nadaraya-Watson Envelope Strategy offers a different approach. Grounded in mathematical analysis, this strategy utilizes the Nadaraya-Watson kernel regression, a method traditionally employed for interpreting complex data patterns.
At the core of this strategy lies the concept of 'envelopes', which are essentially dynamic volatility bands formed around the price based on a custom Average True Range (ATR). These envelopes help provide guidance on potential market entry and exit points. The strategy suggests considering a buy when the price crosses the lower envelope and a sell when it crosses the upper envelope.
One distinctive characteristic of the Nadaraya-Watson Envelope Strategy is its use of a logarithmic scale, as opposed to a linear scale. The logarithmic scale can be advantageous when dealing with larger timeframes and assets with wide-ranging price movements.
The strategy is implemented using Pine Script v5, and includes several adjustable parameters such as the lookback window, relative weighting, and the regression start point, providing a level of flexibility.
However, it's important to maintain a balanced view. While the use of mathematical models like the Nadaraya-Watson kernel regression may provide insightful data analysis, no strategy can guarantee success. Thorough backtesting, understanding the mathematical principles involved, and sound risk management are always essential when applying any trading strategy.
The Nadaraya-Watson Envelope Strategy thus offers another tool for traders to consider. As with all strategies, its effectiveness will largely depend on the trader's understanding, application, and the specific market conditions.
Adaptive Price Channel (log scale)The field of technical analysis is consistently expanding, with numerous indicators used for market forecasting. Amongst them, a novel indicator dubbed the Adaptive Price Channel (log scale), inspired by the renowned Nadaraya-Watson Envelope (LuxAlgo) from LuxAlgo, is gaining traction for its distinctive features and versatility. Unlike its predecessor, the Adaptive Price Channel (log scale) is applicable on a logarithmic scale, thereby allowing it to be utilized on both smaller and larger timeframes.
1. Key Features
The Adaptive Price Channel (log scale) is founded on the trading view Pinescript language, version 5, with its primary aim to maximize the versatility and scalability of trading indicators. It allows traders to adapt it according to their preferred timeframe, thereby making it applicable for a wide range of trading strategies.
Its bandwidth can be adjusted through the input parameters, offering traders the flexibility to manipulate the indicator according to their strategic requirements. Furthermore, it provides an option for repainting smoothing. This option enables users to control the repainting effect in which the historical output of the indicator may change over time. When disabled, the indicator provides the endpoints of the calculations, ensuring consistency in historical values.
Moreover, the Adaptive Price Channel (log scale) allows for color customization, thereby improving visibility and user-friendliness. The colors of the indicator's upward and downward directions can be changed according to the user's preference.
2. Working Mechanism
The Adaptive Price Channel (log scale) uses the logarithm of the source, which is typically the closing price of a trading instrument. It leverages a Gaussian function that exponentially decreases the further the price moves away from the mean, accounting for both positive and negative values. The bandwidth of the Gaussian function can be adjusted to adapt to different market conditions.
Additionally, the Adaptive Price Channel (log scale) features an array of 500 lines for each bar, which helps in defining the boundaries or envelope for price movements. The calculations are executed using the Nadaraya-Watson estimator, which uses kernel regression for non-parametric analysis.
The calculated values for the upper and lower bounds of the envelope are then converted back from the logarithmic scale using the exponential function. This calculation process continues for each bar until the last bar in the data set.
To ensure optimal performance, the Adaptive Price Channel (log scale) uses dynamic repainting. If the repainting mode is enabled, it adjusts the smoothing of the indicator for the entire historical data, making the results more accurate.
3. Visualization and Alerts
The Adaptive Price Channel (log scale) offers an array of visual aids, including labels and plots. The upper and lower bounds of the envelope are plotted, and the indicator triggers labels at points where the closing price crosses these boundaries. These labels serve as alerts for potential trading opportunities.
4. Conclusion
The Adaptive Price Channel (log scale) is an innovative and adaptable trading indicator, drawing inspiration from its predecessor but introducing unique features to increase its versatility. By providing a repainting option, it ensures consistent historical values, thereby enhancing the reliability of the indicator. Furthermore, the capability to operate on a logarithmic scale broadens its usability for different timeframes. The Adaptive Price Channel (log scale) is a powerful tool for any trader, facilitating a better understanding of market dynamics, and enabling more informed decision-making.
Nadaraya-Watson Envelope (Non-Repainting) Logarithmic ScaleIn the fast-paced world of trading, having a reliable and accurate indicator can make all the difference. Enter the Nadaraya-Watson Envelope Indicator, a cutting-edge tool designed to provide traders with valuable insights into market trends and potential price movements. In this article, we'll explore the advantages of this non-repainting indicator and how it can empower traders to make informed decisions with confidence.
Accurate Price Analysis:
The Nadaraya-Watson Envelope Indicator operates in a logarithmic scale, allowing for more accurate price analysis. By considering the logarithmic nature of price movements, this indicator captures the subtle nuances of market dynamics, providing a comprehensive view of price action. Traders can leverage this advantage to identify key support and resistance levels, spot potential breakouts, and anticipate trend reversals.
Non-Repainting Reliability:
One of the most significant advantages of the Nadaraya-Watson Envelope Indicator is its non-repainting nature. Repainting indicators can mislead traders by changing historical signals, making it difficult to evaluate past performance accurately. With the non-repainting characteristic of this indicator, traders can have confidence in the reliability and consistency of the signals generated, ensuring more accurate backtesting and decision-making.
Customizable Parameters:
Every trader has unique preferences and trading styles. The Nadaraya-Watson Envelope Indicator offers a range of customizable parameters, allowing traders to fine-tune the indicator to their specific needs. From adjusting the lookback window and relative weighting to defining the start of regression, traders have the flexibility to adapt the indicator to different timeframes and trading strategies, enhancing its effectiveness and versatility.
Envelope Bounds and Estimation:
The Nadaraya-Watson Envelope Indicator calculates upper and lower bounds based on the Average True Range (ATR) and specified factors. These envelope bounds act as dynamic support and resistance levels, providing traders with valuable reference points for potential price targets and stop-loss levels. Additionally, the indicator generates an estimation plot, visually representing the projected price movement, enabling traders to anticipate market trends and make well-informed trading decisions.
Visual Clarity with Plots and Fills:
Clear visualization is crucial for effective technical analysis. The Nadaraya-Watson Envelope Indicator offers plots and fills to enhance visual clarity and ease of interpretation. The upper and lower boundaries are plotted, along with the estimation line, allowing traders to quickly assess price trends and volatility. Fills between the boundaries provide a visual representation of different price regions, aiding in identifying potential trading opportunities and risk management.
Conclusion:
The Nadaraya-Watson Envelope Indicator is a powerful tool for traders seeking accurate and reliable insights into market trends and price movements. With its logarithmic scale, non-repainting nature, customizable parameters, and visual clarity, this indicator equips traders with a competitive edge in the financial markets. By harnessing the advantages offered by the Nadaraya-Watson Envelope Indicator, traders can navigate the complexities of trading with confidence and precision. Unlock the potential of this advanced indicator and elevate your trading strategy to new heights.
Smart Trend EnvelopeThe "Smart Trend Envelope" indicator is a powerful tool that combines the "Nadaraya-Watson Envelope " indicator by LuxAlgo and the "Strongest Trendline" indicator by Julien_Eche.
This indicator provides valuable insights into price trends and projection confidence levels in financial markets. However, it's important to note that the indicator may repaint, meaning that the displayed results can change after the fact.
The "Strongest Trendline" indicator by Julien_Eche focuses on identifying the strongest trendlines using logarithmic transformations of price data. It calculates the slope, average, and intercept of each trendline over user-defined lengths. The indicator also provides standard deviation, Pearson's R correlation coefficient, and upper/lower deviation values to assess the strength and reliability of the trendlines.
In addition, the "Nadaraya-Watson Envelope " indicator developed by LuxAlgo utilizes the Nadaraya-Watson kernel regression technique. It applies a kernel function to smooth the price data and estimate future price movements. The indicator allows adjustment of the bandwidth parameter and multiplier to control the width of the envelope lines around the smoothed line.
Combining these two indicators, the "Smart Trend Envelope" indicator offers traders and investors a comprehensive analysis of price trends and projection confidence levels. It automatically selects the strongest trendline length based on the highest Pearson's R correlation coefficient. Traders can observe the trendlines on the price chart, along with upper and lower envelope lines generated by the Nadaraya-Watson smoothing technique.
The "Smart Trend Envelope" indicator has several qualities that make it a valuable tool for technical analysis:
1. Automatic Length Selection: The indicator dynamically selects the optimal trendline length based on the highest Pearson's R correlation coefficient, ensuring accurate trend analysis.
2. Projection Confidence Level: The indicator provides a projection confidence level ranging from "Ultra Weak" to "Ultra Strong." This allows traders to assess the reliability of the projected trend and make informed trading decisions.
3. Color-Coded Visualization: The indicator uses color schemes, such as teal and red, to highlight the direction of the trend and the corresponding envelope lines. This visual representation makes it easier to interpret the market trends at a glance.
4. Customizable Settings: Traders can adjust parameters such as bandwidth, multiplier, line color, and line width to tailor the indicator to their specific trading strategies and preferences.
The "Smart Trend Envelope" indicator has been specifically designed and coded to be used in logarithmic scale. It takes advantage of the logarithmic scale's ability to represent exponential price movements accurately. Therefore, it is highly recommended to use this indicator with the chart set to logarithmic scale for optimal performance and reliable trend analysis, especially on higher timeframes.
It's important to remember that the "Smart Trend Envelope" indicator may repaint, meaning that the displayed results can change after the fact. Traders should use this indicator as a tool for generating trade ideas and confirmation, rather than relying solely on its historical values. Combining the indicator with other technical analysis tools and considering fundamental factors can lead to more robust trading strategies.
Nadaraya-Watson OscillatorThis indicator is based on the work of @jdehorty and his amazing Nadaraya-Watson Kernel Envelope, which you can see here:
General Description
The Nadaraya-Watson Oscillator (NWO) will give the same information as the Nadaraya-Watson Envelope, but as an oscillator off the main chart, by plotting the relationship between price and the Kernel and its bands. This also means that we can now detect divergences between price and the NWO.
You can see the relationship between the two here:
You can think of this indicator as the kernel envelope version of a Bollinger Band %B. In ranging markets the bands are perfect for mean reversion trades, but in certain situations the break of one of the bands can signal the beggining of a strong trend and price will remain close to the bands for a long period and will only give small pullbacks. As with any indicator, confluence with price and other tools must be taken into account.
Main Features
As with @jdehorty 's Envelope, you can change the following settings:
Lookback Window.
Relative Weighting.
The initial bar for the regression.
ATR period for the bands.
Inner and Outer Multiples for the bands.
I also added the following:
A middle band around the Kernel to filter out false crossovers.
A Hull Moving Average to smoothen out the movements of the oscillator and give extra confirmation of turnover points.
Colors
Some special things to note regarding the coloring:
The zero line features a gradient that changes color every time the Kernel slope changes direction.
The Oscillator plot has a gradient coloring that gets stronger the closer it gets to each of the bands.
Every time the oscillator crosses over/under the outer bands the background will be highlighted.
Happy trading!
Machine Learning: Lorentzian Classification█ OVERVIEW
A Lorentzian Distance Classifier (LDC) is a Machine Learning classification algorithm capable of categorizing historical data from a multi-dimensional feature space. This indicator demonstrates how Lorentzian Classification can also be used to predict the direction of future price movements when used as the distance metric for a novel implementation of an Approximate Nearest Neighbors (ANN) algorithm.
█ BACKGROUND
In physics, Lorentzian space is perhaps best known for its role in describing the curvature of space-time in Einstein's theory of General Relativity (2). Interestingly, however, this abstract concept from theoretical physics also has tangible real-world applications in trading.
Recently, it was hypothesized that Lorentzian space was also well-suited for analyzing time-series data (4), (5). This hypothesis has been supported by several empirical studies that demonstrate that Lorentzian distance is more robust to outliers and noise than the more commonly used Euclidean distance (1), (3), (6). Furthermore, Lorentzian distance was also shown to outperform dozens of other highly regarded distance metrics, including Manhattan distance, Bhattacharyya similarity, and Cosine similarity (1), (3). Outside of Dynamic Time Warping based approaches, which are unfortunately too computationally intensive for PineScript at this time, the Lorentzian Distance metric consistently scores the highest mean accuracy over a wide variety of time series data sets (1).
Euclidean distance is commonly used as the default distance metric for NN-based search algorithms, but it may not always be the best choice when dealing with financial market data. This is because financial market data can be significantly impacted by proximity to major world events such as FOMC Meetings and Black Swan events. This event-based distortion of market data can be framed as similar to the gravitational warping caused by a massive object on the space-time continuum. For financial markets, the analogous continuum that experiences warping can be referred to as "price-time".
Below is a side-by-side comparison of how neighborhoods of similar historical points appear in three-dimensional Euclidean Space and Lorentzian Space:
This figure demonstrates how Lorentzian space can better accommodate the warping of price-time since the Lorentzian distance function compresses the Euclidean neighborhood in such a way that the new neighborhood distribution in Lorentzian space tends to cluster around each of the major feature axes in addition to the origin itself. This means that, even though some nearest neighbors will be the same regardless of the distance metric used, Lorentzian space will also allow for the consideration of historical points that would otherwise never be considered with a Euclidean distance metric.
Intuitively, the advantage inherent in the Lorentzian distance metric makes sense. For example, it is logical that the price action that occurs in the hours after Chairman Powell finishes delivering a speech would resemble at least some of the previous times when he finished delivering a speech. This may be true regardless of other factors, such as whether or not the market was overbought or oversold at the time or if the macro conditions were more bullish or bearish overall. These historical reference points are extremely valuable for predictive models, yet the Euclidean distance metric would miss these neighbors entirely, often in favor of irrelevant data points from the day before the event. By using Lorentzian distance as a metric, the ML model is instead able to consider the warping of price-time caused by the event and, ultimately, transcend the temporal bias imposed on it by the time series.
For more information on the implementation details of the Approximate Nearest Neighbors (ANN) algorithm used in this indicator, please refer to the detailed comments in the source code.
█ HOW TO USE
Below is an explanatory breakdown of the different parts of this indicator as it appears in the interface:
Below is an explanation of the different settings for this indicator:
General Settings:
Source - This has a default value of "hlc3" and is used to control the input data source.
Neighbors Count - This has a default value of 8, a minimum value of 1, a maximum value of 100, and a step of 1. It is used to control the number of neighbors to consider.
Max Bars Back - This has a default value of 2000.
Feature Count - This has a default value of 5, a minimum value of 2, and a maximum value of 5. It controls the number of features to use for ML predictions.
Color Compression - This has a default value of 1, a minimum value of 1, and a maximum value of 10. It is used to control the compression factor for adjusting the intensity of the color scale.
Show Exits - This has a default value of false. It controls whether to show the exit threshold on the chart.
Use Dynamic Exits - This has a default value of false. It is used to control whether to attempt to let profits ride by dynamically adjusting the exit threshold based on kernel regression.
Feature Engineering Settings:
Note: The Feature Engineering section is for fine-tuning the features used for ML predictions. The default values are optimized for the 4H to 12H timeframes for most charts, but they should also work reasonably well for other timeframes. By default, the model can support features that accept two parameters (Parameter A and Parameter B, respectively). Even though there are only 4 features provided by default, the same feature with different settings counts as two separate features. If the feature only accepts one parameter, then the second parameter will default to EMA-based smoothing with a default value of 1. These features represent the most effective combination I have encountered in my testing, but additional features may be added as additional options in the future.
Feature 1 - This has a default value of "RSI" and options are: "RSI", "WT", "CCI", "ADX".
Feature 2 - This has a default value of "WT" and options are: "RSI", "WT", "CCI", "ADX".
Feature 3 - This has a default value of "CCI" and options are: "RSI", "WT", "CCI", "ADX".
Feature 4 - This has a default value of "ADX" and options are: "RSI", "WT", "CCI", "ADX".
Feature 5 - This has a default value of "RSI" and options are: "RSI", "WT", "CCI", "ADX".
Filters Settings:
Use Volatility Filter - This has a default value of true. It is used to control whether to use the volatility filter.
Use Regime Filter - This has a default value of true. It is used to control whether to use the trend detection filter.
Use ADX Filter - This has a default value of false. It is used to control whether to use the ADX filter.
Regime Threshold - This has a default value of -0.1, a minimum value of -10, a maximum value of 10, and a step of 0.1. It is used to control the Regime Detection filter for detecting Trending/Ranging markets.
ADX Threshold - This has a default value of 20, a minimum value of 0, a maximum value of 100, and a step of 1. It is used to control the threshold for detecting Trending/Ranging markets.
Kernel Regression Settings:
Trade with Kernel - This has a default value of true. It is used to control whether to trade with the kernel.
Show Kernel Estimate - This has a default value of true. It is used to control whether to show the kernel estimate.
Lookback Window - This has a default value of 8 and a minimum value of 3. It is used to control the number of bars used for the estimation. Recommended range: 3-50
Relative Weighting - This has a default value of 8 and a step size of 0.25. It is used to control the relative weighting of time frames. Recommended range: 0.25-25
Start Regression at Bar - This has a default value of 25. It is used to control the bar index on which to start regression. Recommended range: 0-25
Display Settings:
Show Bar Colors - This has a default value of true. It is used to control whether to show the bar colors.
Show Bar Prediction Values - This has a default value of true. It controls whether to show the ML model's evaluation of each bar as an integer.
Use ATR Offset - This has a default value of false. It controls whether to use the ATR offset instead of the bar prediction offset.
Bar Prediction Offset - This has a default value of 0 and a minimum value of 0. It is used to control the offset of the bar predictions as a percentage from the bar high or close.
Backtesting Settings:
Show Backtest Results - This has a default value of true. It is used to control whether to display the win rate of the given configuration.
█ WORKS CITED
(1) R. Giusti and G. E. A. P. A. Batista, "An Empirical Comparison of Dissimilarity Measures for Time Series Classification," 2013 Brazilian Conference on Intelligent Systems, Oct. 2013, DOI: 10.1109/bracis.2013.22.
(2) Y. Kerimbekov, H. Ş. Bilge, and H. H. Uğurlu, "The use of Lorentzian distance metric in classification problems," Pattern Recognition Letters, vol. 84, 170–176, Dec. 2016, DOI: 10.1016/j.patrec.2016.09.006.
(3) A. Bagnall, A. Bostrom, J. Large, and J. Lines, "The Great Time Series Classification Bake Off: An Experimental Evaluation of Recently Proposed Algorithms." ResearchGate, Feb. 04, 2016.
(4) H. Ş. Bilge, Yerzhan Kerimbekov, and Hasan Hüseyin Uğurlu, "A new classification method by using Lorentzian distance metric," ResearchGate, Sep. 02, 2015.
(5) Y. Kerimbekov and H. Şakir Bilge, "Lorentzian Distance Classifier for Multiple Features," Proceedings of the 6th International Conference on Pattern Recognition Applications and Methods, 2017, DOI: 10.5220/0006197004930501.
(6) V. Surya Prasath et al., "Effects of Distance Measure Choice on KNN Classifier Performance - A Review." .
█ ACKNOWLEDGEMENTS
@veryfid - For many invaluable insights, discussions, and advice that helped to shape this project.
@capissimo - For open sourcing his interesting ideas regarding various KNN implementations in PineScript, several of which helped inspire my original undertaking of this project.
@RikkiTavi - For many invaluable physics-related conversations and for his helping me develop a mechanism for visualizing various distance algorithms in 3D using JavaScript
@jlaurel - For invaluable literature recommendations that helped me to understand the underlying subject matter of this project.
@annutara - For help in beta-testing this indicator and for sharing many helpful ideas and insights early on in its development.
@jasontaylor7 - For helping to beta-test this indicator and for many helpful conversations that helped to shape my backtesting workflow
@meddymarkusvanhala - For helping to beta-test this indicator
@dlbnext - For incredibly detailed backtesting testing of this indicator and for sharing numerous ideas on how the user experience could be improved.
Nadaraya-Watson: Envelope (Non-Repainting)Due to popular request, this is an envelope implementation of my non-repainting Nadaraya-Watson indicator using the Rational Quadratic Kernel. For more information on this implementation, please refer to the original indicator located here:
What is an Envelope?
In technical analysis, an "envelope" typically refers to a pair of upper and lower bounds that surrounds price action to help characterize extreme overbought and oversold conditions. Envelopes are often derived from a simple moving average (SMA) and are placed at a predefined distance above and below the SMA from which they were generated. However, envelopes do not necessarily need to be derived from a moving average; they can be derived from any estimator, including a kernel estimator such as Nadaraya-Watson.
How to use this indicator?
Overall, this indicator offers a high degree of flexibility, and the location of the envelope's bands can be adjusted by (1) tweaking the parameters for the Rational Quadratic Kernel and (2) adjusting the lookback window for the custom ATR calculation. In a trending market, it is often helpful to use the Nadaraya-Watson estimate line as a floating SR and/or reversal zone. In a ranging market, it is often more convenient to use the two Upper Bands and two Lower Bands as reversal zones.
How are the Upper and Lower bounds calculated?
In this indicator, the Rational Quadratic (RQ) Kernel estimates the price value at each bar in a user-defined lookback window. From this estimation, the upper and lower bounds of the envelope are calculated based on a custom ATR calculated from the kernel estimations for the high, low, and close series, respectively. These calculations are then scaled against a user-defined multiplier, which can be used to further customize the Upper and Lower bounds for a given chart.
How to use Kernel Estimations like this for other indicators?
Kernel Functions are highly underrated, and when calibrated correctly, they have the potential to provide more value than any mundane moving average. For those interested in using non-repainting Kernel Estimations for technical analysis, I have written a Kernel Functions library that makes it easy to access various well-known kernel functions quickly. The Rational Quadratic Kernel is used in this implementation, but one can conveniently swap out other kernels from the library by modifying only a single line of code. For more details and usage examples, please refer to the Kernel Functions library located here:
Nadaraya-Watson non repainting [LPWN]// ENGLISH
The problem of the wonderfuls Nadaraya-Watson indicators is that they repainting, @jdehorty made an aproximation of the Nadaraya-Watson Estimator using raational Quadratic Kernel so i used this indicator as inspiration i just added the Upper and lower band using ATR with this we get an aproximation of Nadaraya-Watson Envelope without repainting
Settings:
Bandwidth. This is the number of bars that the indicator will use as a lookback window.
Relative Weighting Parameter. The alpha parameter for the Rational Quadratic Kernel function. This is a hyperparameter that controls the smoothness of the curve. A lower value of alpha will result in a smoother, more stretched-out curve, while a lower value will result in a more wiggly curve with a tighter fit to the data. As this parameter approaches 0, the longer time frames will exert more influence on the estimation, and as it approaches infinity, the curve will become identical to the one produced by the Gaussian Kernel.
Color Smoothing. Toggles the mechanism for coloring the estimation plot between rate of change and cross over modes.
ATR Period. Period to calculate the ATR (upper and lower bands)
Multiplier. Separation of the bands
// SPANISH
El problema de los maravillosos indicadores de Nadaraya-Watson es que repintan, @jdehorty hizo una aproximación delNadaraya-Watson Estimator usando un Kernel cuadrático racional, así que usé este indicador como inspiración y solo agregamos la banda superior e inferior usando ATR con esto obtenemos una aproximación de Nadaraya-Watson Envelope sin volver a pintar
Configuración:
Banda ancha. Este es el número de barras que el indicador utilizará como ventana retrospectiva.
Parámetro de ponderación relativa. El parámetro alfa para la función Rational Quadratic Kernel. Este es un hiperparámetro que controla la suavidad de la curva. Un valor más bajo de alfa dará como resultado una curva más suave y estirada, mientras que un valor más bajo dará como resultado una curva más ondulada con un ajuste más ajustado a los datos. A medida que este parámetro se acerque a 0, los marcos de tiempo más largos ejercerán más influencia en la estimación y, a medida que se acerque al infinito, la curva será idéntica a la que produce el Gaussian Kernel.
Suavizado de color. Alterna el mecanismo para colorear el gráfico de estimación entre la tasa de cambio y los modos cruzados.
Período ATR. Periodo para calcular el ATR (bandas superior e inferior)
Multiplicador. Separación de las bandas
KernelFunctionsLibrary "KernelFunctions"
This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substitution/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels. Compared to Moving Averages (which are really just simple kernels themselves), these kernel functions are more adaptive and afford the user an unprecedented degree of customization and flexibility.
rationalQuadratic(_src, _lookback, _relativeWeight, _startAtBar)
Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_relativeWeight : Relative weighting of time frames. Smaller values result in a more stretched-out curve, and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Rational Quadratic Kernel.
gaussian(_src, _lookback, _startAtBar)
Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Gaussian Kernel.
periodic(_src, _lookback, _period, _startAtBar)
Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions that repeat themselves exactly.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Periodic Kernel.
locallyPeriodic(_src, _lookback, _period, _startAtBar)
Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
Parameters:
_src : The source series.
_lookback : The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
_period : The distance between repititions of the function.
_startAtBar : Bar index on which to start regression. The first bars of a chart are often highly volatile, and omitting these initial bars often leads to a better overall fit.
Returns: yhat The estimated values according to the Locally Periodic Kernel.