QuantumAlgo
Home›Guides›Indicators · Trend & Smoothing
Indicators · Trend & Smoothing

Kalman Filter Trading: How the Indicator Works and When It Helps

Kalman Filter Trading: How the Indicator Works and When It Helps — Quantum Algo guide
◆ THE SHORT ANSWER

A Kalman filter in trading is a recursive smoother that estimates the true price level by blending its own prediction with each new bar, weighted by a gain set from process noise Q and measurement noise R. The simple one-state version settles into an EMA; lower lag comes only from adding a velocity state or adaptive noise settings.

Kalman filter indicators are sold as "zero-lag" moving averages. Run the math and a different picture appears: the common one-dimensional version settles into an ordinary EMA whose length you can calculate from two inputs. This Quantum Algo guide shows that calculation, works five bars by hand, explains where genuinely lower lag comes from (a velocity state, adaptive noise), and covers the use where Kalman filters have the best published record: time-varying hedge ratios for pairs trading. There is also a calculator so you can test your own prices.

Premium Indicators

Indicators that prove themselves in public.

One engine, four precision tools — the Gold (XAU) Scalper, the institutional Gravity Zone, the Zeno momentum Oscillator, and Zeno Stocks for equities.

Tap a side card, drag, or use the dots to switch
At a glance: Kalman Filter Trading in one minute
QuestionUseful answerWhat is itA recursive estimator that tracks a hidden true value from noisy measurementsWho created itRudolf E. Kálmán, published 1960 in the Journal of Basic EngineeringCore formulax(t) = x(t−1) + K × (price − x(t−1)), with K = P⁻ ÷ (P⁻ + R)Best useTrend bias line, slope oscillator, and dynamic hedge ratios in pairs tradingMain limitOne-state version behaves like an EMA; Q and R are regime-dependent and easy to overfit
Zeno on real charts
◆ Real charts · Zeno on gold, Bitcoin and NAS1001 / 3
◆ Real chart · XAUUSD · 15M · Quantum Algo Zeno Gold
Quantum Algo Zeno Gold on XAUUSD 15-minute chart: long and short signals with take-profit and stop-loss zones and the dashboard showing margin, TP1, TP2 and Smart Entry status
What every indicator on this page is a filter for: Zeno on gold marks the location — sweep, order block, entry, stop, TP1/TP2. The oscillator decides when.
Swipe or use the arrows · 3 real charts
Every Zeno call is logged on the public track record.See Zeno plans

Why traders put a Kalman filter on a price chart

Every price print is a mix of two things: where the market "really" is, and noise from the order book, spreads and impatient traders. A moving average tries to separate the two by averaging a fixed window. A Kalman filter does it differently. It keeps a running best guess of the true level, keeps a number for how uncertain that guess is, and when a new bar arrives it decides how much to believe the bar versus its own guess.

That decision is the whole trick. If the filter is unsure of itself and prices are clean, it follows price closely. If it is confident and prices are noisy, it barely moves. The weight it gives each new bar is called the Kalman gain, and it is recalculated on every bar.

The method comes from engineering, not markets. Rudolf E. Kálmán published "A New Approach to Linear Filtering and Prediction Problems" in the Journal of Basic Engineering in 1960, and an early implementation by Stanley Schmidt's team at NASA Ames ended up in the Apollo navigation computer. Traders borrowed it for three jobs:

  • A smoothed trend line that you read like a moving average.
  • A trend-plus-slope estimate that projects momentum forward to cut lag.
  • A time-varying hedge ratio for pairs and spread trading, which is where it has the strongest track record in published quant work.

Most articles stop at "it adapts, so it is better." The useful truth is more specific, and it starts with the equations.

The Kalman filter equations, one line at a time

◆ Chart · Kalman filters
Flow diagram of the Kalman filter loop from prior state estimate to prediction, measurement, Kalman gain and updated estimate, above a noisy price line with the smoothed Kalman estimate
The loop behind every bar: predict the state, compare it with the new price, weight the surprise by the gain K, and update. Below, the result on a noisy series: less noise, little lag.

For price smoothing, traders almost always use the simplest version: one hidden state (the true price level) that is assumed to wander like a random walk. Statisticians call this the local level model. Each bar runs two phases, predict and update.

Predict: x⁻ = x(t−1) P⁻ = P(t−1) + Q
Gain: K = P⁻ ÷ (P⁻ + R)
Update: x(t) = x⁻ + K × (price − x⁻) P(t) = (1 − K) × P⁻
SymbolNameWhat it means on a chart
xState estimateThe filter line you plot
PEstimate varianceHow unsure the filter is about its own line
QProcess noiseHow much you think the true level really moves per bar
RMeasurement noiseHow noisy you think each price print is
KKalman gain (0 to 1)The share of the latest surprise that gets added to the line

Read the update line slowly: new estimate equals old estimate plus K times the surprise. That is exactly the shape of an exponential moving average, where the EMA adds α times the surprise. The only difference is that the EMA's α is fixed by you, while K is computed from P, Q and R.

The general filter uses matrices (a transition matrix F, an observation matrix H, and covariance matrices for Q and R) so it can track several hidden values at once. The one-dimensional version above is the special case where everything is a single number.

How Q and R trade smoothness for responsiveness

Here is the fact that most Kalman indicator pages bury: in the one-dimensional model, the gain settles to a fixed value after a few dozen bars, and that value depends only on the ratio q = Q ÷ R. Scale both by ten and nothing changes.

Steady-state gain: K∞ = ( −q + √(q² + 4q) ) ÷ 2, where q = Q ÷ R
Equivalent EMA length: N = 2 ÷ K∞ − 1

Once K has settled, the filter is mathematically identical to an EMA with α = K∞. The textbook Forecasting: Principles and Practice shows the same link from the other side: simple exponential smoothing can be written as an innovations state-space model whose state equation is level(t) = level(t−1) + α × error.

q = Q ÷ RSteady-state gain K∞Behaves like EMA ofCharacter
0.0010.031≈ 63 barsVery smooth, slow
0.010.095≈ 20 barsSwing-trend baseline
0.050.2009 barsShort-term trend
0.10.270≈ 6.4 barsFast
0.50.5003 barsHugs price
1.00.618≈ 2.2 barsAlmost raw price

This table is the most practical thing in this guide. One widely used open-source TradingView Kalman script defaults to Q = 0.01 and R = 0.1, a ratio of 0.1. In steady state that line carries the same weighting as roughly a 6-period EMA. Knowing that, you can stop guessing what a setting does and match it to an average you already understand.

◆ Rule of thumb: raise Q (or lower R) for a faster, noisier line; lower Q (or raise R) for a smoother, laggier one. Only the ratio matters once the filter has warmed up.

A five-bar Kalman filter, computed by hand

Let us run the filter on six closes: 100.00, 101.20, 100.60, 102.10, 103.00, 102.40. Settings: Q = 0.1, R = 1, starting estimate x = 100.00 (the first close) and starting variance P = 1.

BarCloseP⁻ = P + QGain KEstimate xNew P
1101.201.10000.5238100.62860.5238
2100.600.62380.3842100.61760.3842
3102.100.48420.3262101.10120.3262
4103.000.42620.2988101.66860.2988
5102.400.39880.2851101.87720.2851

Bar 1 in full

  1. Predict: x⁻ = 100.00, P⁻ = 1 + 0.1 = 1.1.
  2. Gain: K = 1.1 ÷ (1.1 + 1) = 0.5238.
  3. Surprise: 101.20 − 100.00 = 1.20.
  4. Update: x = 100.00 + 0.5238 × 1.20 = 100.6286.
  5. New variance: P = (1 − 0.5238) × 1.1 = 0.5238.

What the numbers show

The gain falls every bar: 0.52, 0.38, 0.33, 0.30, 0.29. It is heading for the steady-state value of 0.270 from the table above. While it is high, the filter chases price harder than its steady-state EMA would. An EMA with α fixed at 0.270 on the same data ends bar 5 at 101.697; the Kalman line ends at 101.877, closer to price, purely because of that warm-up.

Now the uncomfortable comparison. A plain 5-period EMA (α = 0.333) seeded at 100 ends bar 5 at 101.916, even closer to price than the Kalman line. So "Kalman is faster than an EMA" depends entirely on which EMA and which Q/R you compare. Paste these closes into the calculator below to check every number.

KALMAN FILTER CALCULATORPrices, Q and R → latest estimate, gain and EMA comparison
Reading——

Choosing Q and R for your market and timeframe

Here is something that surprises most people who read Kalman code for the first time: in the classic linear filter, the gain sequence never looks at prices. P, P⁻ and K depend only on Q, R and the starting P. You could compute every gain before the chart even loads. Prices only enter through the surprise term. That is why the Q ÷ R ratio, not the instrument, decides the behavior, and why a script with fixed Q and R behaves the same on Bitcoin as on EUR/USD.

The starting variance P does matter for the first few dozen bars. A P that is large relative to R makes the line jump to price at the start; a tiny P makes it crawl. Setting the starting estimate to the first close and P equal to R is a neutral choice.

Starting points, not magic numbers

These are reasonable first settings expressed as q = Q ÷ R, chosen to match moving-average lengths traders commonly use on each horizon. They are a place to begin testing, not optimized values.

UseTypical timeframeStarting qBehaves like
Scalping baseline1 to 5 minute0.05 to 0.1EMA 6 to 9
Intraday trend15 minute to 1 hour0.01EMA 20
Swing bias4 hour to daily0.002 to 0.005EMA 28 to 45
Position trendDaily to weekly0.0005 to 0.001EMA 63 to 89

Estimating Q and R from data

If you want something more principled than matching an EMA, estimate the two noises directly. R is the variance of prices around their underlying level: take a smooth reference line, compute close minus line for each bar, and use the variance of that residual. Q is the variance of bar-to-bar changes in the reference line itself. On a liquid index future in a calm week, that usually produces a small q; in a news-driven week it jumps. Statisticians fit these by maximum likelihood instead, which is what the state-space tools in Python and R do, but the residual method gets you within the right order of magnitude.

Whatever method you use, recheck after a volatility shift. A ratio estimated in a quiet regime is the single most common reason a Kalman line that looked perfect last month is lagging badly this month.

Does a Kalman filter really lag less than an EMA?

◆ Chart · Kalman filters
Two stacked panels of the same noisy price series: a Kalman filter estimate that adapts quickly to a regime change and an EMA with fixed smoothing that lags the new trend
Same noisy series, two smoothers. When the trend shifts, the Kalman estimate re-weights toward new data while the fixed-alpha EMA trails behind. The advantage comes from adaptation, not magic.

Short answer: the one-dimensional level filter does not, once it has warmed up. It lags exactly like the EMA it converges to. Claims of lower lag come from three other places, and each has a price.

  1. Warm-up and resets. A high starting P makes the early gain large, so the line snaps to price at the start of the chart. Some scripts inflate P after big moves to get the same effect mid-chart. That reduces lag right after shocks and increases noise right after shocks.
  2. Adaptive Q and R. Scripts that scale R or Q with ATR or standard deviation change the gain with volatility. That is closer in spirit to Kaufman's adaptive moving average than to a classic Kalman filter, and it adds parameters you have to tune.
  3. A velocity state. This is the real one. If the model tracks level and slope, the prediction step projects the trend forward, so the line keeps up in a steady trend. It also overshoots at turns, the same trade-off you see with the Hull moving average.

None of this is free lunch. Lower lag in trends always shows up as more overshoot and more whipsaw somewhere else. What the Kalman framework buys you is a principled way to set that trade-off, plus an uncertainty band (from P) that a moving average does not give you.

The two-state version: level plus velocity

The constant-velocity model adds a second hidden value, the slope per bar. The prediction step becomes "next level = level + slope; next slope = slope." Only the level is observed, so the filter infers the slope from how prices keep surprising it.

State: [level, slope] F = [[1, 1], [0, 1]] H = [1, 0]
Predict: level⁻ = level + slope, slope⁻ = slope, P⁻ = F·P·Fᵀ + Q

In practice this behaves like a smoothed linear projection, similar in feel to a rolling linear regression line but updated recursively. The slope state is useful by itself: plot it as an oscillator and it becomes a smoothed rate-of-change that crosses zero when the trend flips.

Eric Benhamou's 2016 paper "Trend Without Hiccups: A Kalman Filter Approach" compared several such models with DEMA and TEMA on one year of daily E-mini S&P 500 data. The models were tuned on that same year with no out-of-sample test, so treat the reported profits as a demonstration, not evidence of an edge.

Kalman hedge ratios in pairs trading

This is where the Kalman filter earns its reputation. In a pairs trade you hold one asset against another in a ratio β so that the spread is mean-reverting. A fixed β from one regression goes stale; a rolling regression forces you to pick a lookback. The Kalman approach treats β (and an intercept) as hidden states that drift as a random walk, and updates them every bar.

Observation: priceY(t) = β₀(t) + β₁(t) × priceX(t) + noise
State: β(t) = β(t−1) + small random change

Ernest Chan popularized the method for retail quants in Algorithmic Trading: Winning Strategies and Their Rationale (Wiley, 2013), using the EWA and EWC country ETFs. The filter also gives you two by-products: the forecast error e(t), which is the spread, and its variance, whose square root works like a moving standard deviation. Trade it like Bollinger Bands on the spread: go long the spread when e(t) falls below −k × √variance, short when it rises above +k × √variance.

QuantStart's write-ups apply the method to the TLT and IEI Treasury ETFs. In its QSTrader backtest (daily bars, August 2009 to August 2016, threshold of one standard deviation) the article reports a CAGR of 8.73%, a Sharpe ratio of 0.75 and a 15.79% maximum drawdown, explicitly gross of transaction costs, with a 777-day drawdown duration. That last number is the honest one: even a textbook-good pairs filter can go two years without a new equity high. For the broader logic of fading stretched spreads, see our mean reversion trading guide.

Setting up a Kalman filter indicator on TradingView

TradingView has no built-in Kalman filter, so you will be using a community script. Search "Kalman" in the Indicators dialog and you will find dozens: plain level filters, adaptive versions that scale with ATR, Kalman-smoothed RSI and oscillator variants. Before adding one, check four things in the description or source:

  1. Which model. One state (level) or two (level and velocity)? A one-state script will behave like an EMA once warmed up.
  2. Which inputs. Separate Q and R, or a single "smoothness" input? If separate, compute q = Q ÷ R and look it up in the table above.
  3. Adaptive scaling. If Q or R is multiplied by ATR or standard deviation, the line will change character between quiet and volatile sessions. Our ATR guide explains what that volatility input measures.
  4. Repainting. A forward filter that only uses past bars does not repaint. A Kalman smoother (which runs backward over the data) does, and it will look magical on historical charts. Our guide to non-repainting indicators shows how to test this with bar replay.

A practical tuning routine

  1. Pick the EMA length you already trust on that market and timeframe, say 20 on a 1-hour chart.
  2. Convert it: α = 2 ÷ 21 = 0.095. That corresponds to q ≈ 0.01, so start with Q = 0.01 and R = 1.
  3. Overlay both lines. They should nearly coincide after the warm-up. If they do, the script is a level filter and you now know its baseline.
  4. Only then experiment: adaptive scaling, a velocity state, or a different q. Change one thing at a time and judge on out-of-sample bars.

If scripts and inputs are new to you, our TradingView platform guide covers adding, saving and templating indicators.

Kalman filter vs EMA, ALMA and McGinley Dynamic

All of these try to answer the same question: how much should the line move on this bar? They answer it with different machinery.

SmootherHow it sets its speedLag in a steady trendMain risk
EMAFixed α = 2 ÷ (N + 1)Moderate, constantToo slow or too noisy, never both right
Kalman (level)Gain from Q, R and P; settles to a fixed valueSame as its equivalent EMA once warmed upMistaking warm-up speed for an edge
Kalman (level + velocity)Gain plus slope projectionLowOvershoot at turning points
ALMAGaussian weights shifted toward recent bars (offset, sigma)Low to moderateOffset set too high gets jumpy
McGinley DynamicSpeed adjusts with the ratio of price to the lineModerate, catches up faster in sell-offsCan trail in sharp rallies
KAMAEfficiency ratio of direction vs noiseLow in clean trends, flat in chopSlow to restart after a range

If you want a filter that also tells you how wide the noise band is, Kalman wins: P gives you an uncertainty estimate for free. If you just want a line, an ALMA or a well-chosen EMA is simpler to reason about. For a channel-style alternative built on a different smoothing family, see the Gaussian Channel guide.

Where Kalman filters fail in live trading

  • Regime changes. Q and R are guesses about how much the market moves and how noisy it is. A Q tuned on a quiet month will lag badly in a news-driven trend; one tuned on a trending month will whipsaw in a range. Checking whether the market is trending or mean-reverting first, for example with the Hurst exponent, tells you which regime you are tuning for.
  • Overfitting. With adaptive multipliers, velocity noise, initial P and a signal threshold, a "simple" Kalman system easily has five or six free parameters. Optimize them on one sample and the backtest will look clean. Hold back at least a third of your data and test once.
  • Fat tails. The filter assumes Gaussian noise. One gap or flash spike creates a huge surprise, and the line jumps by K times that surprise. Clip extreme surprises or filter on a steadier input such as the bar's median price.
  • Broken pairs. In pairs trading, the filter will keep updating β even when the relationship has truly ended. It adapts to a broken spread instead of warning you. Pair it with a periodic cointegration check.
  • The smoother trap. Backward-looking Kalman smoothers use future bars. Any backtest built on them is invalid.
  • Crossover systems. Price crossing a Kalman line whipsaws exactly as much as price crossing the equivalent EMA. Changing the name of the average does not fix crossover noise; filters like a Supertrend band or a volatility buffer do.

Three sensible ways to use a Kalman line

◆ Chart · Kalman filters
Intraday price chart with a Kalman filter estimate and a 20 EMA through a bullish regime shift, a long entry where the Kalman line turns first, a stop below the base and a target at the prior high
A trend entry with the filter: after the regime shift the Kalman line turns before the 20 EMA, the long goes in on the first pullback, with the stop under the base and the target at the prior high.
  1. Trend bias. Use a slow setting (q around 0.001 to 0.01) as a bias line. Above and rising, look for longs; below and falling, look for shorts. Same job as a 50-period average, with a P-based band to show how far price can stray before the bias is in doubt.
  2. Slope oscillator. With the two-state model, plot the velocity state. Zero crosses mark trend flips with less noise than a raw momentum oscillator, similar in spirit to the MACD histogram.
  3. Spread z-score. For pairs or for price vs its own Kalman line, divide the surprise by √P⁻ (or by the forecast-error standard deviation). That gives a self-scaling z-score for mean-reversion entries.

Kalman filters also show up as preprocessing inside more complex models. If that direction interests you, our guide to machine learning trading indicators covers how smoothed inputs feed classifiers.

Kalman Filter and Quantum Algo

A Kalman line is a good answer to "which way is the trend and how noisy is it?" It is not an entry system. That split maps cleanly onto how we build tools at Quantum Algo. Use a slow Kalman setting as a directional filter, then let a timing tool handle entries and risk. Zeno's signals come with a stop and targets built in, so the Kalman bias decides which side you are allowed to take, and Zeno decides when and where the risk is defined. On gold, Zeno Gold works across timeframes; on index CFDs, Zeno Stocks covers NAS100 and SPX500.

If you would rather stay free and open-source, the Adaptive Trend Sentinel is an adaptive trend line you can compare side by side with a Kalman script, and the Supertrend Engine adds a volatility buffer to cut crossover whipsaw. All QuantumAlgo free scripts are on the free indicators page, and the Academy covers trend filters from first principles.

◆ Interactive check

How well do you know Kalman filters?

Questions traders ask about Kalman filters

What is a Kalman filter in trading?+

It is a recursive estimator that tracks a hidden value, usually the true price level or a hedge ratio, from noisy prices. Each bar it predicts, measures the surprise, and corrects by a gain that depends on process noise Q and measurement noise R.

Is a Kalman filter better than a moving average?+

Not automatically. The one-state Kalman filter converges to an EMA, so after warm-up it lags the same. Its advantages are an uncertainty estimate and the option to add a velocity state or time-varying parameters. Compare with our moving averages guide.

What are good Q and R values for a Kalman filter indicator?+

Only the ratio Q ÷ R matters in the simple model. A ratio near 0.01 behaves like a 20-period EMA, 0.05 like a 9-period EMA and 0.5 like a 3-period EMA. Start from an EMA length you already use and convert it.

Does the Kalman filter repaint?+

A forward Kalman filter that uses only past bars does not repaint. A Kalman smoother, which runs backward through the data, does. Check the script's source before trusting a backtest.

Is there a Kalman filter on TradingView?+

There is no built-in Kalman indicator, but many community scripts implement it, including adaptive versions and Kalman-smoothed oscillators. Check whether a script uses one or two states and how it sets Q and R.

How is the Kalman filter used in pairs trading?+

It estimates a time-varying hedge ratio between two assets. The forecast error is the spread, and its variance sets entry bands, so you trade the spread when it stretches beyond a multiple of its standard deviation.

Who invented the Kalman filter?+

Rudolf E. Kálmán, who published it in 1960 in the Journal of Basic Engineering. An early implementation was used in the Apollo navigation computer.

What is the Kalman gain?+

The share of the latest surprise that is added to the estimate, between 0 and 1. It equals P⁻ ÷ (P⁻ + R), so it is high when the filter is unsure and prices are clean, and low when the filter is confident and prices are noisy.

Can a Kalman filter predict price?+

It predicts only one step ahead under its own model, which for the level version is simply the last estimate. It smooths and estimates; it does not forecast turning points.

References & Related Guides

Read next

Primary sources

Writer · Quantum Algo

ILY writes trading education for Quantum Algo — breaking down smart money concepts, market structure, and price action into clear, practical lessons. Every guide is reviewed by Quant, the founder, and every trade idea Quantum Algo publishes is timestamped so anyone can verify it.

✓ Reviewed by Quant · Founder & Head Trader