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.

428

used by the machine learning model for prediction.

"""

# Adjust the feature vector to move all lags by one

# and then recalculate the returns

for i, f in reversed(list(enumerate(self.cur_prices))):

if i > 0:

self.cur_prices[i] = self.cur_prices[i-1]

else:

self.cur_prices[i] = event.close_price / float(

PriceParser.PRICE_MULTIPLIER

)

if self.minutes > (self.lags + 1):

for i in range(0, self.lags):

self.cur_returns[i] = ((

self.cur_prices[i]/self.cur_prices[i+1]

)-1.0)*100.0

As with all QSTrader Strategy subclasses the signal generation happens in the calculate_signals

method. Firstly, the current returns are updated upon receipt of a new market data bar. If

enough minutes have passed (lags+2) then the model begins making predictions based on the

current returns data.

Note that in newer versions of Scikit-Learn it is necessary to reshape one-dimensional arrays

into two-dimensional arrays containing a single row otherwise a deprecation warning is given.

This explains the reshape((1,-1)) method call. Finally, since model.predict returns an array

of a single scalar rather than the scalar itself it is necessary to use the index element operator

([0]) to extract the value.

The remaining logic is tasked with going long or exiting depending upon whether the strategy

is already invested and whether the prediction is +1 or -1. As usual, SignalEvent objects are

sent to the events_queue to be utilised by the Portfolio object:

def calculate_signals(self, event):

"""

Calculate the intraday machine learning

prediction strategy.

"""

if event.type == EventType.BAR:

self._update_current_returns(event)

self.minutes += 1

# Allow enough time to pass to populate the

# returns feature vector

if self.minutes > (self.lags + 2):

pred = self.model.predict(self.cur_returns.reshape((1, -1)))[0]

# Long only strategy

if not self.invested and pred == 1:

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

self.events_queue.put(

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

Saved successfully!

Ooh no, something went wrong!