13.08.2022 Views

advanced-algorithmic-trading

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

198

delta = 1e-5

trans_cov = delta / (1 - delta) * np.eye(2)

obs_mat = np.vstack(

[prices[etfs[0]], np.ones(prices[etfs[0]].shape)]

).T[:, np.newaxis]

kf = KalmanFilter(

n_dim_obs=1,

n_dim_state=2,

initial_state_mean=np.zeros(2),

initial_state_covariance=np.ones((2, 2)),

transition_matrices=np.eye(2),

observation_matrices=obs_mat,

observation_covariance=1.0,

transition_covariance=trans_cov

)

state_means, state_covs = kf.filter(prices[etfs[1]].values)

return state_means, state_covs

def draw_slope_intercept_changes(prices, state_means):

"""

Plot the slope and intercept changes from the

Kalman Filter calculated values.

"""

pd.DataFrame(

dict(

slope=state_means[:, 0],

intercept=state_means[:, 1]

), index=prices.index

).plot(subplots=True)

plt.show()

if __name__ == "__main__":

# Choose the ETF symbols to work with along with

# start and end dates for the price histories

etfs = [’TLT’, ’IEI’]

start_date = "2010-8-01"

end_date = "2016-08-01"

# Obtain the adjusted closing prices from Yahoo finance

etf_df1 = pdr.get_data_yahoo(etfs[0], start_date, end_date)

etf_df2 = pdr.get_data_yahoo(etfs[1], start_date, end_date)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!