Kalman VWAP Filter [BackQuant]Kalman VWAP Filter
A precision-engineered price estimator that fuses Kalman filtering with the Volume-Weighted Average Price (VWAP) to create a smooth, adaptive representation of fair value. This hybrid model intelligently balances responsiveness and stability, tracking trend shifts with minimal noise while maintaining a statistically grounded link to volume distribution.
If you would like to see my original Kalman Filter, please find it here:
Concept overview
The Kalman VWAP Filter is built on two core ideas from quantitative finance and control theory:
Kalman filtering — a recursive Bayesian estimator used to infer the true underlying state of a noisy system (in this case, fair price).
VWAP anchoring — a dynamic reference that weights price by traded volume, representing where the majority of transactions have occurred.
By merging these concepts, the filter produces a line that behaves like a "smart moving average": smooth when noise is high, fast when markets trend, and self-adjusting based on both market structure and user-defined noise parameters.
How it works
Measurement blend : Combines the chosen Price Source (e.g., close or hlc3) with either a Session VWAP or a Rolling VWAP baseline. The VWAP Weight input controls how much the filter trusts traded volume versus price movement.
Kalman recursion : Each bar updates an internal "state estimate" using the Kalman gain, which determines how much to trust new observations vs. the prior state.
Noise parameters :
Process Noise controls agility — higher values make the filter more responsive but also more volatile.
Measurement Noise controls smoothness — higher values make it steadier but slower to adapt.
Filter order (N) : Defines how many parallel state estimates are used. Larger orders yield smoother output by layering multiple one-dimensional Kalman passes.
Final output : A refined price trajectory that captures VWAP-adjusted fair value while dynamically adjusting to real-time volatility and order flow.
Why this matters
Most smoothing techniques (EMA, SMA, Hull) trade off lag for smoothness. Kalman filtering, however, adaptively rebalances that tradeoff each bar using probabilistic weighting, allowing it to follow market state changes more efficiently. Anchoring it to VWAP integrates microstructure context — capturing where liquidity truly lies rather than only where price moves.
Use cases
Trend tracking : Color-coded candle painting highlights shifts in slope direction, revealing early trend transitions.
Fair value mapping : The line represents a continuously updated equilibrium price between raw price action and VWAP flow.
Adaptive moving average replacement : Outperforms static MAs in variable volatility regimes by self-adjusting smoothness.
Execution & reversion logic : When price diverges from the Kalman VWAP, it may indicate short-term imbalance or overextension relative to volume-adjusted fair value.
Cross-signal framework : Use with standard VWAP or other filters to identify convergence or divergence between liquidity-weighted and state-estimated prices.
Parameter guidance
Process Noise : 0.01–0.05 for swing traders, 0.1–0.2 for intraday scalping.
Measurement Noise : 2–5 for normal use, 8+ for very smooth tracking.
VWAP Weight : 0.2–0.4 balances both price and VWAP influence; 1.0 locks output directly to VWAP dynamics.
Filter Order (N) : 3–5 for reactive short-term filters; 8–10 for smoother institutional-style baselines.
Interpretation
When price > Kalman VWAP and slope is positive → bullish pressure; buyers dominate above fair value.
When price < Kalman VWAP and slope is negative → bearish pressure; sellers dominate below fair value.
Convergence of price and Kalman VWAP often signals equilibrium; strong divergence suggests imbalance.
Crosses between Kalman VWAP and the base VWAP can hint at shifts in short-term vs. long-term liquidity control.
Summary
The Kalman VWAP Filter blends statistical estimation with market microstructure awareness, offering a refined alternative to static smoothing indicators. It adapts in real time to volatility and order flow, helping traders visualize balance, transition, and momentum through a lens of probabilistic fair value rather than simple price averaging.
Pricefilter
Gaussian Price Filter [BackQuant]Gaussian Price Filter
Overview and History of the Gaussian Transformation
The Gaussian transformation, often associated with the Gaussian (normal) distribution, is a mathematical function characteristically prominent in statistics and probability theory. The bell-shaped curve of the Gaussian function, expressing the normal distribution, is ubiquitously employed in various scientific and engineering disciplines, including financial market analysis. This transformation's core utility in trading and economic forecasting is derived from its efficacy in smoothing data series and highlighting underlying trends, which are pivotal for making strategic trading decisions.
The Gaussian filter, specifically, is a type of data-smoothing algorithm that mitigates the random "noise" of market price data, thus enhancing the visibility of crucial trend changes and patterns. Historically, this concept was adapted from fields such as signal processing and image editing, where precise extraction of useful information from noisy environments is critical.
1. What is a Gaussian Transformation?
A Gaussian transformation involves the application of a Gaussian function to a set of data points. The function is applied as a filter in the context of trading algorithms to smooth time series data, which helps in identifying the intrinsic trends obscured by market volatility. The transformation is characterized by its parameter, sigma (σ), representing the standard deviation, which determines the width of the Gaussian bell curve. The breadth of this curve impacts the degree of smoothing: a wider curve (higher sigma value) results in more smoothing, beneficial for longer-term trend analysis.
2. Filtering Price with Gaussian Transformation and its Benefits
In the provided Script, the Gaussian transformation is utilized to filter price data. The filtering process involves convolving the price data with Gaussian weights, which are calculated based on the chosen length (the number of data points considered) and sigma. This convolution process smooths out short-term fluctuations and highlights longer-term movements, facilitating a clearer analysis of market trends.
Benefits:
Reduces noise: It filters out minor price movements and random fluctuations, which are often misleading.
Enhances trend recognition: By smoothing the data, it becomes easier to identify significant trends and reversals.
Improves decision-making: Traders can make more informed decisions by focusing on substantive, smoothed data rather than reacting to random noise.
3. Potential Limitations and Issues
While Gaussian filters are highly effective in smoothing data, they are not without limitations:
Lag introduction: Like all moving averages, the Gaussian filter introduces a lag between the actual price movements and the output signal, which can delay decision-making.
Feature blurring: Over-smoothing might obscure significant price movements, especially if a large sigma is used.
Parameter sensitivity: The choice of length and sigma significantly affects the output, requiring optimization and backtesting to determine the best settings for specific market conditions.
4. Extending Gaussian Filters to Other Indicators
The methodology used to filter price data with a Gaussian filter can similarly be applied to other technical indicators, such as RSI (Relative Strength Index) or MACD (Moving Average Convergence Divergence). By smoothing these indicators, traders can reduce false signals and enhance the reliability of the indicators' outputs, leading to potentially more accurate signals and better timing for entering or exiting trades.
5. Application in Trading
In trading, the Gaussian Price Filter can be strategically used to:
Spot trend reversals: Smoothed price data can more clearly indicate when a trend is starting to change, which is crucial for catching reversals early.
Define entry and exit points: The filtered data points can help in setting more precise entry and exit thresholds, minimizing the risk and maximizing the potential return.
Filter other data streams: Apply the Gaussian filter on volume or open interest data to identify significant changes in market dynamics.
6. Functionality of the Script
The script is designed to:
Calculate Gaussian weights (f_gaussianWeights function): Generates the weights used for the Gaussian kernel based on the provided length and sigma.
Apply the Gaussian filter (f_applyGaussianFilter function): Uses the weights to compute the smoothed price data.
Conditional Trend Detection and Coloring: Determines the trend direction based on the filtered price and colors the price bars on the chart to visually represent the trend.
7. Specific Actions of This Code
The Pine Script provided by BackQuant executes several specific actions:
Input Handling: It allows users to specify the source data (src), kernel length, and sigma directly in the chart settings.
Weight Calculation and Normalization: Computes the Gaussian weights and normalizes them to ensure their sum equals one, which maintains the original data scale.
Filter Application: Applies the normalized Gaussian kernel to the price data to produce a smoothed output.
Trend Identification and Visualization: Identifies whether the market is trending upwards or downwards based on the smoothed data and colors the bars green (up) or red (down) to indicate the trend direction.

