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.

427

from sklearn.externals import joblib

from qstrader.price_parser import PriceParser

from qstrader.event import (SignalEvent, EventType)

from qstrader.strategy.base import AbstractStrategy

The initialisation of the class is relatively straightforward. It takes the model pickle file path

through model_pickle_file as an initialisation parameter, along with the number of minutely

bar lags to use for predicting the direction of the next bar, via lags.

The strategy stores the current prices in cur_prices, which is one element longer than the

current returns array, cur_returns, since returns require n + 1 price elements to calculate n

returns. The quantity qty is set to 10,000 in this instance, since there is 500,000 USD of equity.

model contains the unpickled predictive model from Scikit-Learn:

class IntradayMachineLearningPredictionStrategy(AbstractStrategy):

"""

Requires:

tickers - The list of ticker symbols

events_queue - A handle to the system events queue

"""

def __init__(

self, tickers, events_queue,

model_pickle_file, lags=5

):

self.tickers = tickers

self.events_queue = events_queue

self.model_pickle_file = model_pickle_file

self.lags = lags

self.invested = False

self.cur_prices = np.zeros(self.lags+1)

self.cur_returns = np.zeros(self.lags)

self.minutes = 0

self.qty = 10000

self.model = joblib.load(model_pickle_file)

The _update_current_returns method is used to generate the rolling lag-length array of

returns of the AREX closing prices. It begins by reverse iterating through the current prices

array and shifts the prices by one, adding in the new most recent price.

The computer scientists among you will recognise this behaviour as well represented by a

double-ended queue (deque). Python contains such an implementation in the collections library.

For simplicity I have used NumPy arrays in this example.

Once the current prices array is generated the returns list is calculated, but only once all

elements have been populated into the list (i.e. after lags+1):

def _update_current_returns(self, event):

"""

Updates the array of current returns "features"

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

Saved successfully!

Ooh no, something went wrong!