13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

195

Utilise the Kalman Filter from the PyKalman package

to calculate the slope and intercept of the regressed

ETF prices.

"""

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

Finally we plot these values as returned from the previous function. To achieve this we simply

create a Pandas DataFrame of the slopes and intercepts at time values t using the index from

the prices DataFrame and plot each column as a subplot:

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()

The output is given in Figure 13.2.

Clearly the time-varying slope changes dramatically over the 2011 to 2016 period, dropping

from around 1.38 in 2011 to around 0.9 in 2016. It is not difficult to see that utilising a fixed

hedge ratio in a pairs trading strategy would be far too rigid.

In addition the estimate of the slope is relatively noisy. This can be controlled by the delta

variable given in the code above but has the effect of also reducing the responsiveness of the filter

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

Saved successfully!

Ooh no, something went wrong!