PROTECTED SOURCE SCRIPT

One-Sided Hodrick-Prescott Filter

37
Technical & Mathematical Architecture

This indicator represents a significant departure from standard Moving Averages or traditional Hodrick-Prescott (HP) filter implementations found on Trading View. It utilizes a State-Space Model approach to decompose time-series data into trend and cyclical components, solved recursively via a Kalman Filter (Forward Pass) and a Rauch-Tung-Striebel (RTS) Smoother (Backward Pass). Furthermore, it introduces a proprietary Maximum Likelihood Estimation (MLE) loop to adapt the smoothing parameter (λ) dynamically in response to market regimes.

1.1 The State-Space Formulation
The standard HP filter minimizes a specific loss function involving the sum of squared deviations and the sum of squared second differences. While typically solved via batch matrix inversion, this script reformulates the problem as a Local Linear Trend (LLT) model, a stochastic structural model defined by:

Measurement Equation:
y[t] = μ[t] + ε[t]
(Where ε is normally distributed noise)

State Transition Equations:
μ[t+1] = μ[t] + β[t] + η[t]
β[t+1] = β[t] + ζ[t]

Where μ[t] represents the stochastic level (trend) and β[t] represents the stochastic slope (drift). The crucial link to the HP filter is the signal-to-noise ratio. By setting the variance of η to 0 (smooth trend) and defining λ as the ratio of measurement variance to slope variance, the Kalman Filter solution converges exactly to the One-Sided HP Filter.

1.2 The Forward Pass: Kalman Filter
The script executes a recursive estimation loop for real-time (causal) filtering:

Prediction Step: Projects the state mean and error covariance forward based on the transition matrix.
Innovation: Calculates the measurement residual (v[t] = y[t] - predicted y).
Update Step: Computes the Kalman Gain. The posterior state is updated based on how much the prediction missed the actual price.
Stability: The covariance update utilizes the Joseph Form subtraction to ensure the covariance matrix remains positive semi-definite, preventing numerical instability inherent in high-precision floating-point calculations over long durations.
1.3 Adaptive λ via Maximum Likelihood
Standard filters use a static λ (e.g., 1600 for quarterly data), which fails in crypto/FX markets exhibiting changing volatility. This script implements an Adaptive ML Loop.

The Kalman Filter assumes innovations are normally distributed with a specific theoretical variance (S). We compute a running variance ratio test:
Ratio = Actual Innovation Variance / Theoretical Variance

Ratio > 1: The model is "surprised" by volatility. The filter is under-fitting. The script dynamically decreases λ to increase responsiveness (reduce lag).
Ratio < 1: The model is over-fitting noise. The script increases λ to enforce a smoother trend.
This allows the filter to function as a low-lag trend follower during impulses and a robust noise filter during consolidation, automatically.

1.4 The Backward Pass: Rauch-Tung-Striebel (RTS) Smoother
This is the most complex feature of the script. While the Forward Pass provides the optimal estimate based on past data, the Backward Pass computes the optimal estimate based on all data.

The RTS algorithm runs purely on historical arrays stored in memory:

It iterates backward from the last bar to the past. It computes a "Smoother Gain" matrix based on future information. It updates the past estimates to correct them based on what happened afterwards. This results in a Minimum Mean Squared Error (MMSE) estimator. Note: This smoothed line is for analytical hindsight and back testing theoretical limits; it is distinct from the real-time filtered line used for live signaling.

Usage Guide:
This indicator is designed for precision trend following and mean-reversion trading. It separates the market price into a Trend Component (Signal) and a Cycle Component (Noise/Oscillation).

The Two Trend Lines:
The Filtered Trend (Real-Time): This is the filled/shaded line on your chart. It calculates the trend using only past data. It does not repaint. Use this for entering and exiting live trades.
Green Fill: Price is above the trend (Bullish bias).
Red Fill: Price is below the trend (Bearish bias).
The Smoothed Trend (Hindsight): (Optional, enabled via settings). This is the "God mode" line. It uses future data to show you exactly where the trend was.
WARNING: This line repaints. Do not trade the tip of this line. Its purpose is to show you the ideal path for training your eye or optimizing parameters.

Mean Reversion Signals:
The script calculates the "Cycle," which is the percentage deviation of price from the HP Trend.

Bands: The Upper and Lower bands represent the Cycle Threshold.
Long Signal (L): Triggered when the Cycle is Oversold (below lower band) AND begins to turn up, while the Filtered Drift (slope) is positive. This suggests a "dip buy" in an uptrend.
Short Signal (S): Triggered when the Cycle is Overbought (above upper band) AND begins to turn down, while the Filtered Drift is negative. This suggests selling a rally in a downtrend.

Adaptive Lambda Panel:
Enable the "Lambda Panel" to see the engine under the hood.

Rising Lambda (Blue): The market is noisy or consolidating. The filter is becoming "stiffer" to ignore the chop.
Falling Lambda (Orange): The market is trending impulsively. The filter is becoming "looser" to track the price closely and reduce lag.
Strategy: You can use low Lambda values as a confirmation of high-volatility breakout regimes.

Performance Table:
A dashboard in the bottom right corner displays the efficiency of the Kalman Filter:

MSE Filtered vs. Smoothed: Shows the Mean Squared Error of the real-time prediction vs. the hindsight-optimal smooth.
Improvement %: A higher percentage indicates that the RTS Smoother is extracting significantly more noise than the real-time filter (common in choppy markets).
Kalman Gains (K1, K2): These display the current weight the filter assigns to new price data for updating the Level and Slope respectively.
Summary of Settings
Base Lambda: The starting stiffness. Higher = smoother (long-term trend). Lower = responsive (short-term trend).
Adaptation Speed: Recommended between 0.01 and 0.05. Controls how fast λ reacts to volatility shocks.
Smoother Lookback: How far back (in bars) the RTS algorithm re-optimizes the historical line.
Best Practice: Use the Filtered Trend for execution. Use the Smoothed Trend to analyze past price action and determine if your Base Lambda setting is appropriate for the asset's volatility profile.






Penafian

Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.