Skip to content

Instantly share code, notes, and snippets.

@raddy
Created August 31, 2015 13:50
Show Gist options
  • Select an option

  • Save raddy/3824c99b61c3207aa7a7 to your computer and use it in GitHub Desktop.

Select an option

Save raddy/3824c99b61c3207aa7a7 to your computer and use it in GitHub Desktop.
ab kf
def fit_ab_kf(single_cumulative_returns,dex_cumulative_returns):
n_steps = len(dex_cumulative_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_cumulative_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_cumulative_returns,(n_steps,1)))
kf_theos = (filtered_state_means[:,1]*dex_cumulative_returns+filtered_state_means[:,0])
return kf_theos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment