Nadaraya-Watson Trend [QuantAlgo]🟢 Overview
The Nadaraya-Watson Trend indicator estimates a smooth, adaptive trend path by applying non-parametric kernel regression directly to price. For each bar it weights historical values inside a configurable lookback window with a chosen kernel function, normalizes those weights, and returns a single endpoint estimate that forms the plotted trend line. Bandwidth and kernel type control how aggressively recent bars dominate the estimate, optional residual bands express how far price is dispersed around that path, and slope based coloring with reversal markers make direction and turning points readable at a glance across any timeframe or instrument.
🟢 How It Works
The indicator is built around a one sided Nadaraya-Watson (NW) estimator: only the current bar and past bars enter the calculation, so the path behaves as a causal smoother rather than a centered, repainting fit. The pipeline has three stages: kernel weighting over the lookback window, normalized regression into a single trend value, and optional residual band construction from the same estimate.
First, effective bandwidth is formed from the configured bandwidth and multiplier. Each lag distance is then mapped to a kernel weight. Gaussian and Rational Quadratic keep infinite support with different decay shapes. Compact kernels (Epanechnikov, Triangular, Quartic, Cosine) only assign weight while the normalized lag stays inside the unit interval:
kernel_weight(float dist, float h, string ktype, float rq) =>
float w = 0.0
if h > 0.0
float u = dist / h
if ktype == 'Gaussian'
w := math.exp(-(dist * dist) / (2.0 * h * h))
else if ktype == 'Rational Quadratic'
w := math.pow(1.0 + (dist * dist) / (2.0 * rq * h * h), -rq)
else if math.abs(u) <= 1.0
if ktype == 'Epanechnikov'
w := 0.75 * (1.0 - u * u)
else if ktype == 'Triangular'
w := 1.0 - math.abs(u)
else if ktype == 'Quartic'
w := (15.0 / 16.0) * math.pow(1.0 - u * u, 2.0)
else if ktype == 'Cosine'
w := (math.pi / 4.0) * math.cos(math.pi * u / 2.0)
w
float h = bandwidth * h_mult
Next, the Nadaraya-Watson path is computed as the normalized weighted average of the selected source across the lookback window. Nearer bars dominate when bandwidth is low. Weight spreads more evenly when bandwidth is high, producing a smoother path:
float sum_w = 0.0
float sum_p = 0.0
for i = 0 to lookback
float w = kernel_weight(i, h, kernel_type, rel_weight)
sum_w += w
sum_p += src * w
float nw_trend = sum_w != 0.0 ? sum_p / sum_w : na
Finally, residual bands can be drawn from a kernel weighted mean absolute residual of the source versus the current NW estimate, scaled by the band multiplier. When price is tightly clustered around the path the envelope contracts. When price is dispersed the envelope expands, framing extension and compression relative to the same estimator that defines the trend:
float sum_abs = 0.0
float sum_res_w = 0.0
for i = 0 to lookback
float w = kernel_weight(i, h, kernel_type, rel_weight)
if w > 0.0 and not na(src ) and not na(nw_trend)
sum_abs += w * math.abs(src - nw_trend)
sum_res_w += w
float residual = sum_res_w != 0.0 ? sum_abs / sum_res_w : na
float upper = not na(nw_trend) and not na(residual) ? nw_trend + residual * band_mult : na
float lower = not na(nw_trend) and not na(residual) ? nw_trend - residual * band_mult : na
🟢 Signal Interpretation
▶ Bullish Path (Rising NW Line with Bullish Color): When the Nadaraya-Watson estimate is increasing bar to bar, the path and optional gradient fill plot in the bullish color, reading as an uptrend in the kernel smoothed series. Treat this as a long bias: strongest on the reversal marker with price holding above the path, or on pullbacks that respect the path while slope stays up. Bias weakens if price loses the path and the slope flattens or flips down.
▶ Bearish Path (Falling NW Line with Bearish Color): When the estimate is decreasing bar to bar, the path and fill plot in the bearish color, reading as a downtrend in the kernel smoothed series. Treat this as a short bias: strongest on the reversal marker with price holding below the path, or on bounces that fail at the path while slope stays down. Bias weakens if price reclaims the path and the slope flattens or flips up.
▶ Residual Bands (Optional Envelope Around the Path): With residual bands enabled, the upper and lower lines track a scaled kernel weighted residual around the NW path. Touches or closes beyond the outer band highlight price stretched away from the estimate. Returns toward the path after an extension often mark mean reversion relative to the kernel trend rather than a full regime change. Band width is derived from how widely the source has been scattered around the current NW estimate inside the lookback window
🟢 Features
▶ Preconfigured Presets: Three parameter sets tuned for different trading styles and timeframes. "Default" delivers balanced trend estimation for swing trading on 1H to daily charts, smoothing short lived noise while still responding to genuine directional turns. "Fast Response" is built for intraday work on 5 minute to 1H charts, keeping the path tighter to recent structure so turns register earlier at the cost of more frequent reversals in chop. "Smooth Trend" is aimed at position style reading on daily and weekly charts, forming a more stable baseline that flips only when the kernel path itself shifts with more conviction. Kernel type, residual bands, and visual options stay independently configurable under every preset.
▶ Kernel Library: Six kernel functions expand how the same endpoint Nadaraya-Watson framework assigns weight across the window. Gaussian is the classic smooth default with infinite support. Epanechnikov, Triangular, Quartic, and Cosine are compact kernels that fully exclude bars beyond the bandwidth scale. Rational Quadratic keeps infinite support with heavier tails, and its Relative Weighting input controls how much influence farther bars retain versus a Gaussian like decay. Switching kernels changes the shape of the single plotted path without adding a second model or external oscillator.
▶ Residual Bands: Optional envelope around the NW path built from kernel weighted mean absolute residuals of the source versus the estimate, scaled by Band Multiplier. Enable when you want extension and compression context around the same trend line. Disable when you want only the path, gradient, and markers.
▶ Built-in Alerts: Five alert conditions support hands off monitoring. "Bullish Kernel Reversal" fires on the bar the path slope flips from down to up. "Bearish Kernel Reversal" fires on the bar the path slope flips from up to down. "Any Kernel Reversal" fires on either directional flip. "Source Cross Above Upper Band" and "Source Cross Below Lower Band" fire when the selected source crosses the residual envelope extremes. Alert messages include exchange, ticker, and timeframe for immediate context.
▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) apply coordinated bullish and bearish colors to the path, gradient fill, residual bands, markers, optional bar coloring, and optional background coloring. Custom unlocks independent bullish and bearish color pickers. Gradient fill, residual bands, reversal markers, bar coloring, and background coloring can each be toggled so the chart stays as clean or as expressive as the workflow requires.
インジケーター

Nadaraya-Watson Envelope [Gabremoku]Nadaraya-Watson Envelope
This indicator builds a non-repainting Nadaraya-Watson envelope using a one-sided Gaussian kernel, so every value is computed from the current bar and past bars only. The goal is to provide a smoother adaptive baseline than a standard moving average while keeping the script operationally honest and suitable for live use.
What makes this script different:
- The central basis is a kernel-weighted Nadaraya-Watson estimate, not a classic SMA/EMA baseline.
- The main envelope is not built from standard deviation by default. It uses kernel-weighted mean absolute deviation (MAD), which is generally less sensitive to single-bar outliers and often produces a more stable channel.
- Standard deviation bands can still be enabled as an optional overlay, so users can compare MAD-based and Stdev-based dispersion around the same kernel basis.
- Signal logic is configurable. Breakout labels can be triggered by close crossing the band, wick piercing the band, or full body breakout, which makes the visual behavior easier to align with the trader’s interpretation.
How it works:
The script applies Gaussian weights to past bars inside the selected window. More recent bars receive the highest weight, while older bars progressively contribute less. The Bandwidth input controls how fast those weights decay. In practice, the effective lookback is usually much shorter than the full Window setting when Bandwidth is low. A practical rule of thumb is that the effective lookback is about 3 × Bandwidth bars, capped by the Window value.
The indicator computes:
1. A kernel-weighted mean, used as the Nadaraya-Watson basis.
2. A kernel-weighted MAD, used as the primary envelope width.
3. An optional kernel-weighted standard deviation, displayed only when the comparison bands are enabled.
The upper and lower MAD bands are then filled with a gradient that increases in strength as price moves away from the basis toward the envelope edges. This makes the visual intensity reflect displacement magnitude, not just bullish or bearish direction.
Compression logic:
The compression zone is based on min-max normalization of envelope width over a lookback period. This is not a statistical percentile rank. A threshold of 0.15 means the current envelope width is near the lower end of the observed width range over the selected compression lookback.
Signal modes:
- Close Cross: triggers only when the close crosses a band.
- Wick Pierce: triggers when the candle’s high or low exceeds a band.
- Body Breakout: triggers when the candle body exceeds a band.
Use Wick Pierce if you want signal labels to match the visible moment where candles extend outside the envelope.
How to use it:
- Use the basis as an adaptive trend reference.
- Use the MAD envelope to judge whether price is stretched relative to recent kernel-weighted behavior.
- Watch compression zones for narrow-range conditions that may precede expansion.
- Compare MAD and Stdev bands when you want to evaluate whether recent volatility is dominated by isolated spikes or by broader dispersion.
Practical notes:
- This script is non-repainting by construction because it does not use centered calculations or future bars.
- Low Bandwidth values create a more reactive basis and shorter effective memory.
- High Bandwidth values create a smoother basis and wider historical influence.
- Increasing Window far beyond roughly 3 × Bandwidth usually has little additional effect.
- Signal labels are state-machine filtered, so they are designed to mark sequence transitions rather than every repeated touch outside the bands.
This indicator is intended as a visual decision-support tool, not as a standalone trading system. It helps traders study adaptive trend, envelope displacement, compression, and breakout structure in a cleaner way than a standard volatility channel. インジケーター

Machine Learning: Volume-Weighted Mean Reversion [Dots3Red]█ MACHINE LEARNING: VOLUME-WEIGHTED MEARN REVERSION KERNEL REGRESSION
Nadaraya-Watson kernel regression is a non-parametric machine learning method. Unlike moving averages which apply fixed, predefined weights to historical bars, kernel regression derives each bar's weight from a mathematical function — the kernel — that measures how relevant that bar is to the current estimate. No hardcoded coefficients. No assumed shape. The model adapts purely from the data.
This script introduces a fundamental extension to the standard method: volume as a second weighting dimension . The result is a regression curve that gravitates toward price levels where real market participation occurred — not toward price levels where a clock happened to tick.
█ WHY KERNEL REGRESSION IS MACHINE LEARNING
The term machine learning describes algorithms that derive structure from data rather than from manually specified rules. Kernel regression satisfies this definition formally. The estimator computes:
ŷ = Σ [ w(i) × close ] / Σ
where each weight w(i) is determined by a kernel function — not by the programmer. The model decides, from the data, how much each historical bar should influence the current estimate. This is the same mathematical family as K-Nearest Neighbors, which weights neighbors by proximity. It is cited as a foundational non-parametric ML method in Bishop (2006) and Hastie et al. (2009), and is described as an attention mechanism in deep learning literature — the same concept behind transformer models. The claim is accurate, not cosmetic.
█ THE CORE INNOVATION — VOLUME WEIGHTING
Every existing Nadaraya-Watson implementation on TradingView uses a pure time kernel:
• Standard NW: w(i) = K(i/h)
This means a bar with 10,000 shares traded and a bar with 10,000,000 shares traded receive identical weight if they are the same number of bars away. A thin overnight drift and a high-volume institutional session influence the regression equally. That is statistically incorrect — volume is a direct measure of how much informational content a price bar carries.
This script uses a volume-weighted kernel:
• This script: w(i) = vol_norm(i) × K(i/h)
where vol_norm(i) is the bar's volume normalized against the peak volume in the lookback window, raised to a configurable power exponent. The regression estimate is therefore:
ŷ = Σ [ vol_norm(i) × K(i/h) × close ] / Σ
High-volume bars anchor the curve. Low-volume bars — thin sessions, overnight drift, holiday trading — contribute minimally. The regression finds where the market actually agreed on price, not just where the clock recorded a tick.
█ THREE KERNEL FUNCTIONS
All three apply the same volume weighting. The choice controls how rapidly influence decays with time distance:
• Rational Quadratic (default) — heavier tail than Gaussian. Bars from 40–60 periods ago still contribute meaningfully if they had high volume. Best for daily and weekly charts where old high-volume levels remain structurally relevant.
• Gaussian — standard bell curve decay. Weight drops sharply with distance. Best for intraday charts where recency matters more than historical anchors.
• Epanechnikov — hard cutoff at the bandwidth boundary. Anything beyond h periods receives zero weight. Produces the most locally sensitive regression. Best for fast charts requiring tight responsiveness.
█ SIGNAL LOGIC
The envelope bands are placed at a configurable multiple of ATR, standard deviation, or a fixed percentage above and below the regression line. Three band width methods are available to match different volatility contexts.
Two signal modes are available:
• Reversion mode (default) — a signal fires when price crosses back through the band after an extension. The ▲ label appears on the bar where price returns inside the lower band. The ▼ label appears on the bar where price returns inside the upper band. This confirms reversion has begun rather than anticipating it.
• Extension mode — enable Signal on extension close to fire a signal the moment price closes outside a band. This is an early warning — useful for alerts before the reversion bar arrives.
Additional signal filters: minimum bars between signals to prevent repeat firing, optional slope direction gate so signals only fire when the regression slope agrees with the signal direction.
█ WHAT YOU SEE ON THE CHART
Regression line
The volume-weighted fair value curve. Cyan when slope is rising, magenta when falling. This is where the model estimates price should be given the recent history of high-participation price levels.
Envelope bands
Upper and lower boundaries built from ATR, standard deviation, or a fixed percentage. The upper band is tinted red — resistance zone. The lower band is tinted green — support zone.
Bar coloring — 4 states
• Bright red — price closed above the upper band. Extended, statistically stretched above fair value.
• Bright green — price closed below the lower band. Extended, statistically stretched below fair value.
• Dim silver — price inside bands, regression rising or falling, i.e normal bullish or bearish context.
The contrast between fully saturated outside-band bars and dimmed inside-band bars makes overextension immediately visible without reading the scale.
Signal labels
▲ REVERT or ▼ REVERT with VW=XX% showing the volume weight of the signal bar. A signal at VW=85% fired on a high-participation bar. A signal at VW=9% fired on a thin bar — lower confidence.
Signal bar highlighting
Two additional layers available: a background flash on the signal bar and a thick vertical line through the bar's full range. Both are independently toggleable. The vertical line uses width=4 — the maximum Pine Script allows — making the signal bar visually distinct even when zoomed out.
Dashboard
Displays: current regression value, slope direction, band width, Bar Vol Weight meter (▰▰▰▱▱▱) showing how much influence the current bar has on the regression, active kernel type, volume weighting status, percentage distance from the regression midline, and non-repainting mode status.
█ NON-REPAINTING
When Non-Repainting Mode is enabled (default), all calculations use a bar offset. The current bar's close does not enter its own regression estimate. Historical signals visible on closed bars will not change as new bars form. Disable this to see a predictive (repainting) version where the current bar participates in its own estimate — useful for visual exploration but not recommended for backtesting or alerts.
█ HOW TO USE
Core use case — mean reversion
This is a mean reversion tool. It works best when price is oscillating rather than trending directionally. The recommended workflow:
1 — Confirm a ranging regime with a separate regime classifier before acting on signals.
2 — Wait for price to reach or pierce the upper or lower band (bars turn bright red or green).
3 — Check the VW% in the signal label. Higher volume weight on the signal bar = higher confidence.
4 — Enter on the reversion signal (▲ or ▼ label). Stop beyond the wick of the signal bar.
5 — Target the regression midline as the primary exit. The % from mid dashboard row tracks progress in real time.
Timeframe guidance
The volume-weighting advantage increases with timeframe because higher timeframes produce more meaningful volume data per bar. H4 and Daily are the strongest timeframes for this tool. For intraday use, reduce the Volume Weight Power to 0.3–0.5 to soften the impact of individual volume spikes.
Quick-start settings by asset class
• Stocks daily: Window=100, Bandwidth=8, Vol Power=1.0, ATR×2.0
• Crypto daily: Window=80, Bandwidth=6, Vol Power=0.7, ATR×1.8
• Forex H4: Window=100, Bandwidth=10, Vol Power=1.0, ATR×1.5
• Indices H1: Window=120, Bandwidth=12, Vol Power=0.8, Stdev×2.0
█ SETTINGS REFERENCE
Kernel Settings
• Lookback Window — number of historical bars in the regression. Larger = smoother, more lag.
• Bandwidth (h) — controls how fast kernel weight decays with time. Higher = older bars still contribute.
• Kernel Type — Gaussian / Rational Quadratic / Epanechnikov. See kernel section above.
• RQ Alpha (α) — Rational Quadratic only. Lower = smoother mixture of length scales.
• Non-Repainting Mode — uses offset. Recommended ON for backtesting.
Volume Weighting
• Enable Volume Weighting — toggle the core innovation on or off. OFF = standard NW.
• Volume Normalization Window — peak volume reference window. Match or exceed the lookback window.
• Volume Weight Power — exponent on the volume weight. 1.0 = linear. 2.0 = quadratic. 0.5 = softer.
• Volume Weight Floor — minimum weight for any bar. Prevents zero-volume bars from being ignored entirely.
Envelope Bands
• Band Width Method — ATR (volatility-adaptive), Stdev (statistical), or Percent (fixed).
• ATR Length — period for ATR calculation.
• ATR / Stdev Mult — multiplier applied to ATR or standard deviation.
• Percent Offset % — used when Percent method is selected.
Signals
• Signal on band crossover — enable signals on band cross events.
• Signal on extension close — fire signal when price closes outside a band (early warning mode).
• Require slope change — only signal when regression slope direction agrees.
• Min bars between signals — gap guard to prevent repeat signals.
Visuals
• Dashboard — regression stats and live metrics table.
• Signal labels — ▲/▼ REVERT labels with volume weight percentage.
• Band fill — fill between upper and lower bands.
• Background flash — bright background color on signal bars.
• Vertical line on signal bar — thick line through full bar height at signal.
• Large dot marker — additional plotchar layer on signal bars.
• Dashboard position — Top Right / Top Left / Bottom Right / Bottom Left.
█ ALERTS
Seven alert conditions are available:
• Long signal — reversion through lower band
• Short signal — reversion through upper band
• Any signal — either direction
• Extended below lower band — early warning before reversion fires
• Extended above upper band — early warning before reversion fires
• Regression slope turned bullish
• Regression slope turned bearish
█ DISCLAIMER
This indicator is a decision-support tool. It does not constitute financial advice and does not guarantee future results. Past statistical patterns do not predict future price behavior. Always use proper risk management.
Method: Nadaraya-Watson Kernel Regression (Non-Parametric ML)
Innovation: Volume × Time Kernel Weighting
Kernels: Gaussian · Rational Quadratic · Epanechnikov
Signals: Mean Reversion (band crossover or extension)
Repainting: Configurable — non-repainting mode available インジケーター

Nadaraya-Watson Regression Liquidity Sweeps [AlgoAlpha]🟠 OVERVIEW
This script combines Nadaraya-Watson regression, momentum analysis, and liquidity level tracking into a single workflow. It measures the slope of a smoothed price regression curve, converts that slope into a normalized oscillator, and uses momentum shifts to identify areas where liquidity may be resting.
The oscillator is built from the rate of change of the Nadaraya-Watson estimate rather than price itself. This allows momentum transitions to be measured relative to the underlying regression trend. When momentum weakens after an extended move, the script records swing-based liquidity levels that can later be swept by price.
A volatility-adjusted Nadaraya-Watson band is also displayed on the chart. This provides context for trend direction, momentum strength, and potential rebound conditions around the regression value.
🟠 CONCEPTS
Nadaraya-Watson Regression — A kernel-based smoothing method that estimates an underlying price curve by weighting nearby historical data more heavily than distant data.
Normalized Regression Slope — The change in the Nadaraya-Watson estimate divided by its recent standard deviation, allowing momentum strength to be compared across different market conditions.
Liquidity Sweep Level — A horizontal level created from a swing high or swing low when momentum begins to weaken, representing an area that may later attract price.
Oscillator Signal Line — An EMA of the normalized oscillator used to identify momentum crossovers and momentum phase changes.
Rebound Condition — A signal generated when price moves back through the Nadaraya-Watson value while oscillator direction remains aligned with the prevailing momentum bias.
🟠 FEATURES
Normalized Nadaraya-Watson Oscillator — Measures momentum using the slope of a smoothed regression curve.
Liquidity Sweep Detection — Creates liquidity levels when bullish or bearish momentum begins to weaken.
Volatility-Adjusted Regression Band — Displays a dynamic overlay around the Nadaraya-Watson estimate using smoothed ATR values.
Momentum Weakening Signals — Marks locations where oscillator momentum begins to lose strength against the current directional bias.
Rebound Signals — Highlights situations where price reclaims or loses the regression value while momentum remains aligned with trend direction.
🟠 HOW TO USE
Monitor the oscillator relative to its signal line to identify momentum shifts and changes in directional bias.
Watch for newly created liquidity levels after momentum weakening events, as these levels may become future sweep targets.
Use sweeps of upper or lower liquidity levels to identify areas where price has taken resting liquidity.
Look for bullish rebound signals when price reclaims the regression value while bullish momentum remains active.
Look for bearish rebound signals when price loses the regression value while bearish momentum remains active.
Combine oscillator direction, liquidity levels, and regression band structure to build context around trend continuation or reversal scenarios.
🟠 CONCLUSION
The Nadaraya-Watson Regression Liquidity Sweeps indicator combines regression-based momentum analysis, volatility-adjusted trend structure, and liquidity level tracking. By linking momentum transitions to swing-derived liquidity zones, it helps identify where liquidity may be forming and when it has been swept. This provides traders with additional context for trend analysis, pullbacks, and potential reversal areas. インジケーター

Iterative Locally Periodic EnvelopeThe Iterative Locally Periodic Envelope is a phase-conditioned kernel estimator with temporal locality and endogenous dispersion modeling, implemented as a Nadaraya–Watson estimator under a locally periodic kernel.
The locally periodic kernel defines similarity through cyclical phase alignment modulated by temporal proximity. Observations contribute to the estimator based on both their position within a repeating cycle structure and their recency, emphasizing structural recurrence with sensitivity to local regime conditions.
The indicator computes a latent equilibrium using a kernel-weighted mean and a dispersion measure using kernel-weighted variance under the same weighting structure. The resulting envelope reflects cycle-consistent deviation with temporal locality, rather than a conventional volatility band. All values are computed exclusively on closed historical bars using a bounded lookback window to ensure non-repainting behavior.
This indicator belongs to a broader class of iterative kernel-based envelopes that includes Gaussian, Rational Quadratic, and Periodic variants. All share a common Nadaraya–Watson estimation framework, differentiated by their kernel.
TRADING USES
The Iterative Locally Periodic Envelope is best interpreted as a cycle-aware structural estimator with adaptive temporal sensitivity, rather than a volatility-based band. The temporal locality component allows the estimator to adapt more readily to emerging regime shifts than the pure periodic variant.
Equilibrium Tracking
The latent equilibrium represents the phase-conditioned central tendency of price under locally periodic similarity weighting. Oscillations around this level reflect movement within a repeating structural cycle, with more recent phase-aligned observations contributing more strongly than temporally distant ones.
Cycle Regime Structure
The envelope emphasizes repeating structural behavior through phase recurrence weighting, modulated by temporal decay. Changes in symmetry, amplitude, or persistence of oscillation around the latent equilibrium may indicate transitions between cyclical regimes.
Mean Reversion Within Cycles
When a stable periodic structure is present, deviations from the latent equilibrium may revert toward phase-consistent levels. Mean-reversion behavior is conditioned on both cycle structure and temporal proximity.
Structural Extremes
Extreme deviations relative to the envelope correspond to phase-inconsistent states where cyclical structure becomes stretched or destabilized. Because the kernel incorporates temporal decay, these conditions are identified with greater sensitivity to recent price behavior.
State Estimation
The system defines a latent equilibrium as the inferred central cyclical state under joint phase and temporal weighting, with dispersion derived from kernel-weighted variance under identical constraints. This produces a structurally consistent representation of the market state that is sensitive to both cyclical position and local regime conditions.
LOCALLY PERIODIC ENVELOPE CONSTRUCTION
The envelope is constructed using kernel-weighted variance under the same locally periodic similarity measure used to estimate the latent equilibrium. The latent equilibrium defines the central state estimate and kernel-weighted variance defines dispersion under identical weighting, producing an endogenously determined envelope. The band width is fixed at ±1 kernel standard deviation with no multiplier, ensuring dispersion remains an intrinsic property of the locally periodic similarity structure rather than an externally imposed scaling parameter.
THEORY
The locally periodic kernel defines similarity in terms of cyclical phase recurrence modulated by temporal proximity. Observations contribute to the estimator based on alignment within a repeating cycle structure, with influence attenuated by temporal distance from the estimation point.
The estimator is formulated as a Nadaraya–Watson kernel regression under a locally periodic kernel, where weights are defined as:
k(i) = exp( -2 · sin²(πi / p) / L² ) · exp( -i² / 2L² )
Where:
p = period (cycle length)
L = lookback window (shared bandwidth parameter; effective smoothing scales with L²)
In this MacKay consistent formulation, the lookback window acts as a unified bandwidth parameter governing periodic phase selectivity and the Radial Basis Function (RBF) temporal decay envelope. The two components are coupled through L, producing a kernel that simultaneously emphasizes phase-aligned and temporally proximate observations.
As L increases, both the periodic and RBF components broaden, producing stronger smoothing across phase and time. As L decreases, phase selectivity and temporal locality both increase, making the estimator more sensitive to recent cycle-consistent observations.
This induces a similarity structure in which influence concentrates at phase-aligned intervals within a temporally bounded neighborhood. The resulting estimator defines a latent equilibrium governed by phase alignment and temporal proximity that can be interpreted as a locally stationary periodic extension of kernel regression on a circular phase manifold.
The key distinction from the pure periodic kernel is that phase-aligned observations at distant lags are progressively suppressed by the RBF decay term, allowing the estimator to adapt to structural drift while preserving cycle-aware weighting. During stable cyclical regimes the two estimators converge; during structural transitions the locally periodic variant adapts faster by downweighting older phase information.
CALIBRATION
As established in Gaussian Processes for Machine Learning (Rasmussen & Williams, 2006), the period should reflect the recurrence interval of the dominant cycle in the data, while the bandwidth parameter L controls how quickly similarity decays away from perfect phase alignment. For daily charts, common cycle anchors include the trading week (~5 bars), trading month (~21 bars), trading quarter (~63 bars), and trading year (~252 bars).
Length (Lookback / Bandwidth)
Controls structural depth of the estimator and acts as the unified bandwidth parameter for the periodic and RBF components; as L governs phase selectivity and temporal decay simultaneously, its effect is stronger than in the pure periodic variant. The default of 100 reflects the locally periodic kernel's temporal decay component; at longer lengths the RBF term weakens and behavior converges toward the pure periodic estimator.
- 50–100: high responsiveness, strong temporal locality, short-cycle sensitivity
- 150–250: balanced regime stability with moderate temporal decay
- 300+: broad structural smoothing, weak temporal decay, behavior converges toward pure periodic envelopes
Period (Cycle Length)
Defines the recurrence interval of the kernel and governs phase alignment and cyclical structure. Shorter periods increase phase resolution and cycle sensitivity, while longer periods emphasize broader structural recurrence. The period should reflect the dominant cycle present in the data, aligned with the anchor scales defined above.
Start At Bar
Offsets the kernel window backward from the most recent bars and excludes newer observations from the estimator. This ensures all calculations are based strictly on closed historical data and preserves non-repainting behavior.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices.
Performance is dependent on the presence of stable cyclical structure; in regimes lacking periodic coherence, the estimator converges toward a local smoother with reduced phase discrimination. インジケーター

Iterative Periodic EnvelopeThe Iterative Periodic Envelope is a phase-conditioned kernel estimator with endogenous dispersion modeling, implemented as a Nadaraya–Watson estimator under a canonical periodic kernel.
The periodic kernel defines similarity through cyclical phase alignment rather than temporal proximity or multi-scale distance decay. Observations contribute to the estimator based on their position within a repeating cycle structure, emphasizing structural recurrence over linear time dependence.
The indicator computes a latent equilibrium using a kernel-weighted mean and a dispersion measure using kernel-weighted variance under the same weighting structure. The resulting envelope reflects cycle-consistent deviation, rather than a conventional volatility band. All values are computed exclusively on closed historical bars using a bounded lookback window, ensuring non-repainting behavior.
This indicator belongs to a broader class of iterative kernel-based envelopes that includes Gaussian and Rational Quadratic variants. All share a common Nadaraya–Watson estimation framework, differentiated by their kernel.
TRADING USES
The Iterative Periodic Envelope is best interpreted as a cycle-aware structural estimator rather than a volatility-based band.
Equilibrium Tracking
The latent equilibrium represents the phase-conditioned central tendency of price under periodic similarity weighting. Oscillations around this level reflect movement within a repeating structural cycle rather than directional drift.
Cycle Regime Structure
The envelope emphasizes repeating structural behavior through phase recurrence weighting. Changes in symmetry, amplitude, or persistence of oscillation around the latent equilibrium may indicate transitions between cyclical regimes.
Mean Reversion Within Cycles
When a stable periodic structure is present, deviations from the latent equilibrium may revert toward phase-consistent levels. This supports mean-reversion behavior that is conditioned on cycle structure rather than purely statistical dispersion.
Structural Extremes
Extreme deviations relative to the envelope correspond to phase-inconsistent states where cyclical structure becomes stretched or destabilized. These conditions often precede transitions such as cycle inversion, expansion, or compression.
State Estimation
The system defines a latent equilibrium as the inferred central cyclical state, with dispersion derived from kernel-weighted variance under identical periodic similarity constraints. This produces a structurally consistent representation of market state.
PERIODIC ENVELOPE CONSTRUCTION
The envelope is constructed using kernel-weighted variance under the same periodic similarity measure used to estimate the latent equilibrium. The latent equilibrium defines the central state estimate and kernel-weighted variance defines dispersion under identical weighting, producing an endogenously determined envelope. The band width is fixed at ±1 kernel standard deviation with no multiplier, ensuring dispersion remains an intrinsic property of the periodic similarity structure rather than an externally imposed scaling parameter.
THEORY
The periodic kernel defines similarity in terms of cyclical phase recurrence rather than linear temporal distance. Observations contribute to the estimator based on alignment within a repeating cycle structure.
The estimator is formulated as a Nadaraya–Watson kernel regression under a canonical periodic kernel, where weights are defined as:
k(i) = exp( -2 · sin²(πi / p) / L² )
Where:
p = period (cycle length)
L = lookback window (bandwidth parameter; effective smoothing scales with L²)
In this MacKay consistent formulation, the lookback window acts as a bandwidth control parameter, governing phase selectivity and structural smoothing. As L increases, the kernel becomes broader, producing stronger smoothing and reduced phase sensitivity. As L decreases, phase selectivity increases and the estimator becomes more locally sensitive to cyclical alignment.
This induces a cyclical similarity structure in which influence concentrates at recurring phase intervals. The resulting estimator defines a latent equilibrium governed by phase alignment rather than temporal proximity. This formulation can be interpreted as a periodic extension of kernel regression on a circular phase manifold.
CALIBRATION
Length (Lookback / Bandwidth)
Controls structural depth of the estimator and acts as the primary kernel bandwidth parameter.
- 50–100: high responsiveness, short-cycle sensitivity
- 150–250: balanced regime stability
- 300+: strong structural smoothing, reduced sensitivity to phase noise
Period (Cycle Length)
Defines the recurrence interval of the kernel and governs phase alignment and cyclical structure. Commonly aligns with dominant market rhythms such as intraday or macro-cycle structure.
- Lower values: faster cycle sensitivity
- Higher values: slower, broader structural cycles
Start At Bar
Offsets the kernel window backward from the most recent bars and excludes newer observations from the estimator. This ensures all calculations are based strictly on closed historical data and preserves non-repainting behavior.
MARKET USAGE
Stock, Forex, Crypto, Commodities, and Indices.
Performance is dependent on the presence of stable cyclical structure; in regimes lacking periodic coherence, the estimator converges toward a smoother, low-information state. インジケーター

Exponential Nadaraya Watson kernel regression [Jamallo](2025)
Intro
Nadaraya-Watson (N-W) kernel regression is a non-parametric smoothing technique that estimates the underlying trend of a price series without assuming any fixed model shape (like a straight line or curve). Unlike a simple moving average which weights bars equally, or an EMA which applies a fixed exponential decay, N-W regression derives its curve by computing a weighted average of all prices within a lookback window — where the weights are determined by a kernel function.
The most common kernel used is the Gaussian kernel, which assigns weights in a bell-curve shape — prices closer to the center of the window receive higher weight, prices at the edges receive lower weight. Most N-W implementations use a pure symmetric Gaussian kernel, meaning every bar within the lookback window is weighted purely by its distance from the center, with no preference for recency.
This indicator uses a hybrid Exponential Nadaraya-Watson (ENW) kernel that combines two weighting forces simultaneously:
Gaussian spatial weight — bell-curve weighting centered on the window, same as standard N-W
Exponential time-decay weight — progressively heavier weighting on recent bars, similar to how an EMA behaves
Both weights are multiplied together for each bar, meaning a price bar must be both spatially central and recent to receive maximum influence. In practice this shifts the effective weight peak toward the recent end of the window, making the K Line more responsive to current price action than standard N-W.
Breakdown
K Line — ENW Kernel Regression
The central baseline of the indicator. A smooth adaptive curve derived from the hybrid ENW kernel applied to closing prices. Bandwidth is controlled via the Kernel Length and Alpha inputs — higher alpha increases the recency bias, lower alpha brings behavior closer to standard N-W.
Volatility Bands (Inner & Outer)
Rather than using ATR or standard deviation for band width, this indicator measures the absolute deviation of price from the K Line and smooths that deviation through the same ENW kernel. This means bands are fully adaptive — they expand and contract organically based on how far price has been straying from the regression curve, not a fixed statistical formula. Inner and outer bands are independently scaled via deviation multipliers.
A Line — Vervoort ATR Stop
A trailing stop built on the HLC4 price source with an ATR-based loss distance. Flips direction on a close beyond the stop level. Serves as the primary trend bias line — when above the K Line the fill turns bullish, when below it turns bearish. Cross signals (triangles) are plotted whenever the A Line crosses the K Line, marking potential trend shifts.
Signal Line — Vervoort ATR Stop (Secondary)
A second independent Vervoort trailing stop running on its own ATR period and multiplier settings. Typically configured looser than the A Line — wider multiplier, longer or equal period — so it acts as a slower confirmation layer. Useful for filtering noise on the A Line crosses: an A Line cross that also aligns with the Signal Line's bias carries more weight than one that doesn't.
-------
Nadaraya-Watson kernel regression concept — E. Nadaraya (1964), G.S. Watson (1964)
Vervoort ATR Stop — Sylvain Vervoort
インジケーター

Adaptive Nadaraya-Watson (Non Repainting) [Metrify]To understand this implementation of the Nadaraya-Watson estimator, we have to look at the core equation governing non-parametric regression. This script aren't trying to average prices; we are trying to find the probability density of where price should be relative to its recent history.
1. The Kernel Physics (Bandwidth Modulation)
In standard kernel regression, you have a bandwidth parameter (h). This controls the "smoothness" of the curve. If h is too low, the curve jitters with every tick of noise. If h is too high, it acts like a sluggish SMA.
A static h fails because market volatility is dynamic. When the market explodes (high volatility), a tight bandwidth generates false signals. When the market sleeps, a wide bandwidth misses the micro-trends.
It try solving this by making h a function of the Asset's volatility ratio:
heff=h×max(0.5,min(SMA(ATR20,100)ATR20,2.0))
If the current ATR(20) is double the long-term average (100), the bandwidth doubles. This forces the estimator to "zoom out" during chaos, effectively ignoring noise that would otherwise look like a reversal.
vol_ratio = use_vol ? vol_raw / (vol_base == 0 ? 1 : vol_base) : 1.0
vol_mod = math.max(0.5, math.min(vol_ratio, 2.0))
h_eff = h_val * vol_mod
2. The Gaussian Loop (Endpoint Estimation)
Standard Nadaraya-Watson scripts repaint because they calculate the regression over a full window centered on the bar. To make this usable for live trading, we must calculate the Endpoint Estimate.
We iterate backward from the current bar (i=0) to the lookback limit. For every historical price Xi, we calculate a weight wi based on how far away it is in time (distance).
The weight is derived from the Gaussian Kernel function:
wi=exp(−2heff2i2)
Price data closer to the current bar (i=0) gets a weight near 1.0. Data further away (i=50) decays exponentially toward 0.
for i = 0 to lookback by 1
float dist = float(i)
float w = math.exp(-math.pow(dist, 2) / (2 * math.pow(h_eff, 2)))
num := num + w * src
den := den + w
3. Statistical Deviation (MAE vs. StDev)
Most Bollinger Band-style indicators use Standard Deviation (Root Mean Square). The problem with StDev is that it squares the errors, which heavily penalizes large outliers. In crypto or volatile forex pairs, one wick can blow out the bands for 20 bars.
This one use Mean Absolute Error (MAE) instead.
MAE=N1∑∣Price−y^∣
MAE is linear. It measures the average distance price strays from the kernel estimate without squaring the penalty. This creates "tighter" bands that adhere closer to price action during normal trend behavior but don't expand ridiculously during a flash crash.
Pine Script
float error = math.abs(src - y_hat)
float mae = ta.sma(error, lookback)
We project two sets of bands:
Inner Band (Balanced): The "Noise Zone". Price inside here is considered random walk.
Outer Band (Precision): The "Exhaustion Zone". Price reaching here is statistically unlikely (2.8x MAE).
Input & Visual Summary
Kernel Physics:
h_val: The base smoothness. Lower (e.g., 6) = faster, noisier. Higher (e.g., 10) = slower, smoother.
use_vol: Keep this TRUE. It prevents the bands from being too tight during news events.
Envelope Statistics:
mult_in / mult_out: These are your risk settings. 1.5/2.8 is a standard deviation-like setting suited for MAE.
インジケーター

ストラテジー

インジケーター

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 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. インジケーター

インジケーター

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. ライブラリ
