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.

405

self.time = event.time

# Set the correct latest prices depending upon

# order of arrival of market bar event

price = event.adj_close_price/float

PriceParser.PRICE_MULTIPLIER

)

if event.time == self.time:

if event.ticker == self.tickers[0]:

self.latest_prices[0] = price

else:

self.latest_prices[1] = price

else:

self.time = event.time

self.days += 1

self.latest_prices = np.array([-1.0, -1.0])

if event.ticker == self.tickers[0]:

self.latest_prices[0] = price

else:

self.latest_prices[1] = price

The core of the strategy is carried out in the calculate_signals method. Firstly we set

the correct times and prices (as described above). Then we check that we have both prices for

TLT and IEI, at which point we can consider new trading signals.

y is set equal to the latest price for IEI, while F is the observation matrix containing the latest

price for TLT, as well as a unity placeholder to represent the intercept in the linear regression.

The Kalman Filter is subsequently updated with these latest prices. Finally we calculate the

forecast error e t and the standard deviation of the predictions, √ Q t . We will run through this

code step-by-step as it looks a little complicated.

The first task is to form the scalar value y and the observation matrix F, containing the prices

of IEI and and TLT respectively. We calculate the variance-covariance matrix R or set it to the

zero-matrix if it has not yet been initialised. Subsequently we calculate the new prediction of

the observation yhat as well as the forecast error et.

We then calculate the variance of the observation predictions Qt as well as the standard

deviation sqrt_Qt. We use the update rules derived in the chapter on State Space Models

to obtain the posterior distribution of the states theta, which contains the hedge ratio/slope

between the two prices:

def calculate_signals(self, event):

"""

Calculate the Kalman Filter strategy.

"""

if event.type == EventType.BAR:

self._set_correct_time_and_price(event)

# Only trade if we have both observations

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

Saved successfully!

Ooh no, something went wrong!