Skip to content

Instantly share code, notes, and snippets.

@raddy
Created February 7, 2014 16:55
Show Gist options
  • Save raddy/8866799 to your computer and use it in GitHub Desktop.
Save raddy/8866799 to your computer and use it in GitHub Desktop.
simplest y=mx + b kalman example
import pykalman
import numpy as np
#model of the form -- I apologize for mathjax weirndess but too lazy to fix right now
#yt = β0,t +β1,txt +νt, νt ∼ N(0, σ2 ν)
#β0,t+1 = β0,t +ξt, ξt ∼ N(0, σ2 ξ)
#β1,t+1 = β1,t +ςt, ςt ∼ N(0, σ2 ς )
n_steps = len(dex_returns)
A = np.matrix([[1,0],[0,1]])
# Transition matrix is dependent on previous B0/B1 with no inherent cross dependency
C = map(lambda x: np.matrix(np.append(1,x[0])),np.reshape(dex_returns,(n_steps,1,1)))
# Observation matrix is tensor of [1,x_t] (of length equal to our observations)
# Initial hidden state means are 0 for intercept and 1 for slope
# Initial coverariance estimates aren't terribly critical, I've picked just two small numbers
# Transition covariance describes the B0 and B1 variances -- these can be estimated from
# inverse of covariance matrix (preicison matrix)
kf = pykalman.KalmanFilter(transition_matrices=[A for i in xrange(n_steps)],
observation_matrices=C,
observation_covariance=np.eye(1)*1e-3,
transition_covariance = np.eye(2)*1e-5,
initial_state_mean=np.array([0,1]),
initial_state_covariance = np.eye(2)*1e-5)
(filtered_state_means, filtered_state_covariances)=kf.filter(np.reshape(single_name_returns,(n_steps,1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment