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.

414

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)

# 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 et < -sqrt_Qt:

# Long Entry

print("LONG: %s" % event.time)

self.cur_hedge_qty = int(

floor(self.qty*self.theta[0])

)

self.events_queue.put(

SignalEvent(

self.tickers[1],

"BOT", self.qty

)

)

self.events_queue.put(

SignalEvent(

self.tickers[0],

"SLD", self.cur_hedge_qty

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

Saved successfully!

Ooh no, something went wrong!