Timeseries Methods: Kalman Filter from scratch in Python — Part 2

Edwina Gu
4 min readFeb 21, 2023

In Part 1 we talked about applying simple Kalman Filter, the advantage of Kalman Filter lies in its ability to deal with new observation (streaming data). This is a huge advantage when dealing with high frequency data. If the model is simple there is no need to include all past observation and recompute the simple linear regression.



class kalman_filter:
def __init__(self, x_init, F, Q, R, H, B=None, u=None, sd=np.array([[0]])):
self.x_init = x_init
self.F = F
self.Q = Q
self.R = R
self.H = H
self.X_post = self.x_init
self.P_post = sd
self.X_prior = None
self.P_prior = None
if B is not None and u is not None:
self.B = B
self.u = u
else:
self.B = np.array([[0]])
self.u = np.array([[0]])

self.mean = np.array([[]])
self.covar = np.array([[]])

def fit(self, data, num_state=1, fit_step=None):
self.num_state = num_state
fit_step = fit_step if fit_step is not None and fit_step < data.shape[1] else data.shape[1]
for i in range(fit_step):
z_k = data[:, i]
# predict
self._predict(self.X_post, self.P_post)
self._update(z_k)
# update
self.mean = np.append(self.mean, self.X_post)
self.covar = np.append(self.covar, self.P_post)

def _predict(self, X_post, P_post):
self.X_prior = np.dot(self.F, X_post) + np.dot(self.B, self.u)…

--

--