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.

406

if all(self.latest_prices > -1.0):

# Create the observation matrix of the latest prices

# of TLT and the intercept value (1.0) as well as the

# scalar value of the latest price from IEI

F = np.asarray([self.latest_prices[0], 1.0]).reshape((1, 2))

y = self.latest_prices[1]

# The prior value of the states \theta_t is

# distributed as a multivariate Gaussian with

# mean a_t and variance-covariance R_t

if self.R is not None:

self.R = self.C + self.wt

else:

self.R = np.zeros((2, 2))

# Calculate the Kalman Filter update

# ----------------------------------

# Calculate prediction of new observation

# as well as forecast error of that prediction

yhat = F.dot(self.theta)

et = y - yhat

# Q_t is the variance of the prediction of

# observations and hence \sqrt{Q_t} is the

# standard deviation of the predictions

Qt = F.dot(self.R).dot(F.T) + self.vt

sqrt_Qt = np.sqrt(Qt)

# The posterior value of the states \theta_t is

# distributed as a multivariate Gaussian with mean

# m_t and variance-covariance C_t

At = self.R.dot(F.T) / Qt

self.theta = self.theta + At.flatten() * et

self.C = self.R - At * F.dot(self.R)

Finally we generate the trading signals based on the values of e t and √ Q t . To do this we

need to check what the "invested" status is - either "long", "short" or "None". Notice how we

need to adjust the cur_hedge_qty current hedge quantity when we go long or short as the slope

θt 0 is constantly adjusting in time:

# Only trade if days is greater than a "burn in" period

if self.days > 1:

# If we’re not in the market...

if self.invested is None:

if e < -sqrt_Q:

# Long Entry

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

Saved successfully!

Ooh no, something went wrong!