Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Implementation of Kalman Filter Estimation of Mean in Python using PyKalman, Bokeh and NSEPy

4 min read

A Kalman filter in Python with PyKalman takes only a few lines: create a KalmanFilter with a transition and observation matrix of 1, set the two covariances, and call filter() on the closing prices to get a smooth, adaptive estimate of the mean. This post explains how the filter works, shows the original 2017 notebook with NSEPy and Bokeh, and adds a tested 2026 version.

Key takeaways
  • A Kalman filter estimates a hidden value (here, the “true” price mean) from noisy observations, updating with every new bar.
  • In PyKalman, transition_covariance (Q) and observation_covariance (R) control how fast the estimate reacts.
  • Higher Q / lower R = faster, noisier line; lower Q / higher R = smoother, slower line.
  • NSEPy has not been updated since 2020; the updated code uses yfinance and Bokeh 3 with PyKalman 0.11.

What is a Kalman filter?

Kalman Filter is an optimal estimation algorithm to estimate the variable which can be measured indirectly and to find the best estimate of states by combining measurement from various sensors in the presence of noise.

Kalman filter is named after Rudolf E. Kálmán, one of the primary developers of its theory. Kalman filter has wide range of applications from aerospace Navigation, Robotics, Trajectory Optimization, Control Systems, Signal Processing, time series analysis and econometrics. In fact the very first application of kalman filter was made at NASA AMES center in the early 1960s during the feasibility study of circumlinear navigation control of the apollo space capsule.

Python for traders, the quick way in

BEGINNER FRIENDLY · RATED 5.0

Python for traders, the quick way in

A crash course that gets you from zero to writing your own market data scripts.

  • Python basics with market examples
  • Fetch, clean and chart price data
  • Lifetime access
Start learning →by Marketcalls

Kalman Filters is ideal for systems which are continuously changing and well suited for building real time systems as kalman filter is a dynamic linear model, that is able to adapt to an ever changing environment. The major advantage of Kalman Filter is that it is predictive and adaptive, and it is really fast as it doesn’t track the historical data but rather the previous state.

Kalman Filter Explained in Simple Terms

Kalman Filters State Estimation

Kalman Filter – Optimal State Estimator

How the Kalman filter estimates the mean

For a price series the model is simple. The hidden mean follows a random walk, and each closing price is that mean plus noise. At every bar the filter does two things:

  1. Predict: the mean is expected to stay where it was, but its uncertainty grows by Q (the transition covariance).
  2. Update: compare the new close with the prediction and move the estimate by a fraction K of the difference. K, the Kalman gain, is large when the estimate is uncertain and small when the observation noise R is large.

So the estimate behaves like an adaptive moving average whose speed is set by the ratio of Q to R. The original notebook used Q = 0.01 and R = 1, which settles at a gain of about 0.095, roughly the responsiveness of a 20-period exponential average. Try it in the widget below.

Interactive
Tune a Kalman filter yourself

Drag the two covariance sliders that PyKalman exposes and watch how the Kalman estimate of the mean trades smoothness against lag, compared with a simple moving average.

0Steady-state Kalman gain
0Kalman error vs true mean
020-period SMA error vs true mean

Grey: noisy observed price. Navy dashed: hidden true mean. Teal: Kalman estimate. Amber: 20-period SMA. Raising Q or lowering R makes the filter follow price faster; the opposite makes it smoother but slower. Simulated data.

Kalman filter in Python using PyKalman

When comes to implementation of Kalman filter python comes very handy as the library PyKalman makes life easier rather than digging with complex math stuff to calculate kalman estimation.

Implementation of Kalman Filter Mean Estimation in IPython Notebook using PyKalman, Bokeh, NSEPy and pandas to plot Interactive Intraday Candlestick Charts with Kalman Filter

The notebook is embedded below as it was published in 2017. Here is its code, verbatim (it was written for Python 2 and the 2017 NSEPy and Bokeh APIs):

from math import pi
import pandas as pd
from bokeh.plotting import figure, show, output_notebook
from nsepy.archives import get_price_history
from datetime import date
from datetime import datetime
from pykalman import KalmanFilter

%matplotlib notebook

df = get_price_history(stock = 'TCS', 
                        start = date(2015,1,1), 
                        end = date(2017,04,19))

kf = KalmanFilter(transition_matrices = [1],
                  observation_matrices = [1],
                  initial_state_mean = df['Close'].values[0],
                  initial_state_covariance = 1,
                  observation_covariance=1,
                  transition_covariance=.01)

state_means,_ = kf.filter(df[['Close']].values)
state_means = state_means.flatten()

df["date"] = pd.to_datetime(df.index)

mids = (df.Open + df.Close)/2
spans = abs(df.Close-df.Open)

inc = df.Close > df.Open
dec = df.Open > df.Close
w = 12*60*60*1000 # half day in ms

output_notebook()

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"

p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, toolbar_location="left",y_axis_label = "Price",
          x_axis_label = "Date")

p.segment(df.date, df.High, df.date, df.Low, color="black")
p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color='green', line_color="green")
p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color='red', line_color="red")
p.line(df.date,state_means,line_width=1,line_color = 'blue',legend="Kalman filter")

p.title = "Implementation of Kalman Filter Estimation - TCS EOD chart"
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3

show(p)

Updated version (2026)

Three things have changed since 2017. NSEPy has had no release since version 0.8 in March 2020, so the data now comes from yfinance. PyKalman is maintained again (version 0.11.2, January 2026, Python 3.10 to 3.14, GitHub). Bokeh 3 renamed plot_width to width and legend to legend_label, and date(2017,04,19) is a syntax error in Python 3. This version was tested with PyKalman 0.11.2, Bokeh 3.10.2 and yfinance 1.8.0:

pip install -U pykalman bokeh yfinance pandas
from math import pi
import pandas as pd
import yfinance as yf
from bokeh.plotting import figure, show
from pykalman import KalmanFilter

# Daily OHLC for TCS from Yahoo Finance (NSEPy no longer works with the NSE site)
df = yf.download("TCS.NS", start="2023-01-01", end="2026-11-01",
                 auto_adjust=False, progress=False, multi_level_index=False)
df = df.dropna()

kf = KalmanFilter(transition_matrices=[1],
                  observation_matrices=[1],
                  initial_state_mean=df["Close"].values[0],
                  initial_state_covariance=1,
                  observation_covariance=1,
                  transition_covariance=.01)

state_means, _ = kf.filter(df[["Close"]].values)
df["kalman"] = state_means.flatten()

df["date"] = pd.to_datetime(df.index)
mids = (df.Open + df.Close) / 2
spans = (df.Close - df.Open).abs()
inc = df.Close > df.Open
dec = df.Open > df.Close
w = 12 * 60 * 60 * 1000  # half day in ms

p = figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,save",
           width=1000, toolbar_location="left",
           y_axis_label="Price", x_axis_label="Date",
           title="Kalman Filter Estimation of Mean - TCS daily chart")
p.segment(df.date, df.High, df.date, df.Low, color="black")
p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="green", line_color="green")
p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="red", line_color="red")
p.line(df.date, df["kalman"], line_width=2, line_color="blue", legend_label="Kalman filter")
p.xaxis.major_label_orientation = pi / 4
p.grid.grid_line_alpha = 0.3
show(p)

To use it in a notebook, add from bokeh.io import output_notebook and call output_notebook() before show(p). For more on downloading NSE data with yfinance, see our yfinance guide.

How to choose the covariance values

Most of the work in using a Kalman filter in Python goes into choosing Q and R:

  • Start with the ratio, not the absolute numbers. Q/R = 0.01 gives a smooth mean for daily bars; 0.1 is closer to a fast 5 to 7 period average.
  • Scale with price. R = 1 is small noise for a ₹4,000 stock and large noise for a ₹40 stock. Normalise prices or scale R by the variance of daily changes.
  • Let PyKalman estimate them. kf.em(df[["Close"]].values, n_iter=10) fits the covariances by expectation maximisation, but check the result out of sample.
  • Use filter(), not smooth(), for trading signals. The smoother uses future data and will make a backtest look far better than live trading.

Want the same filter inside AmiBroker? See Kalman filter and unscented Kalman filter AFL using Python ComServer. For pair trading, a Kalman filter is also a common way to estimate a time-varying hedge ratio, a topic covered in computing cointegration using AmiBroker and Python.

In the next tutorial we will be discussing more interesting statistical model and how to implement the same in python.

Frequently Asked Questions

How do I install PyKalman?

Run pip install pykalman. Version 0.11.2 (January 2026) supports Python 3.10 to 3.14.

What do transition_covariance and observation_covariance mean in PyKalman?

transition_covariance (Q) is how much the hidden mean is allowed to move between bars; observation_covariance (R) is how noisy each price is around that mean. Their ratio sets how fast the estimate reacts.

Is a Kalman filter better than a moving average?

It adapts its weight to the uncertainty of the estimate and can be tuned to lag less than an SMA for the same smoothness, but with fixed Q and R on a random walk it behaves much like an exponential moving average.

Does the Kalman filter repaint?

The forward filter (filter()) does not; each value uses only past data. The Kalman smoother (smooth()) does use future data and should not be used for signals.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

2 Replies to “Implementation of Kalman Filter Estimation of Mean in Python…”

  1. Hey Raj,

    This is awesome!

    Just one question & one request.

    Can we use this as a Buy or Sell Signal?

    If yes, then can you guide me how to backtest this in python?

    I have a very basic knowledge, if you can point some articles or tutorials, I will be good to go.

    Mihir

  2. sir nsepy is support only idle python and it is not support to jupytor notebook .please give me some advice for what to do

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More