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.

426

bias-variance trade-off of the model. A smaller max_depth will have a reduced predictive capability,

but will produce a much smaller file size and will execute much faster in QSTrader.

Correspondingly, a larger max_depth will potentially overfit on the training data, will have a

significant filesize (the default value leads to a model of 4.1Gb in size!) and will execute slowly

in QSTrader.

The Hit Rate and confusion matrix for the testing set are also output here if the training/test

split is chosen as above.

Note that it is also necessary to modify the path to your data in the application of the joblib

serialisation mechanism ( joblib.dump(model, ’/path/to/your/ml_model_rf.pkl’)):

print("Fitting classifier model...")

model = RandomForestClassifier(

n_estimators=n_estimators,

n_jobs=n_jobs,

random_state=random_state,

max_depth=10

)

model.fit(X_train, y_train)

print("Outputting metrics...")

print("Hit-Rate: %s" % model.score(X_test, y_test))

print("%s\n" % confusion_matrix(model.predict(X_test), y_test))

print("Pickling model...")

joblib.dump(model, ’/path/to/your/ml_model_rf.pkl’)

This concludes the model generation script. The pickled model file is stored in ml_model_rf.pkl

and will be used in the following QSTrader Strategy object.

29.3 QSTrader Strategy Object

Now that the predictive model has been succesfully pickled by joblib, attention will turn to using

it in an "online" predictive manner within a QSTrader Strategy subclass.

The strategy itself is relatively simple. Every bar received via the event is used to form a

rolling lag-length array of the previous bars’ closing prices. This is then turned into a set of

returns and multiplied by 100, as in the predictive model fitting stage.

For ease of understanding the procedure the strategy itself has been set to only go long and

exit. It does not go short and exit, although this is a simple modification if so desired.

For every bar the models predict method is called, which returns +1 or -1 depending upon

predicted direction for the next bar. If the strategy is not invested and receives a +1 then it goes

long 10,000 units of AREX. If the strategy is invested and receives a -1 then it closes the 10,000

unit position.

NumPy and Pandas are both used within the class, as is joblib, for unpickling the predictive

model. In addition, the usual QSTrader objects for Strategy classes are imported:

# intraday_ml_strategy.py

import numpy as np

import pandas as pd

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

Saved successfully!

Ooh no, something went wrong!