Popular Libraries

Scikit-Learn

Introduction

This page explains how to build, train, deploy and store Scikit-Learn models.

Import Libraries

Import the sklearn and joblib libraries.

from AlgorithmImports import *
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
import joblib

You need the joblib library to store models.

Create Subscriptions

In the Initializeinitialize method, subscribe to some data so you can train the sklearn model and make predictions.

# Subscribe to security data and store symbol for referencing in the algorithm.
self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol

Build Models

In this example, build a support vector regression prediction model that uses the following features and labels:

Data CategoryDescription
FeaturesDaily percent change of the open, high, low, close, and volume of the SPY over the last 5 days
LabelsDaily percent return of the SPY over the next day

The following image shows the time difference between the features and labels:

Features and labels for training

To build the model, call the GridSearchCV constructor with the SVR model, the parameter grid, a scoring method, the number of cross-validation folds:

# Define a grid of hyperparameters to search over and perform cross-validation.
aram_grid = {'C': [.05, .1, .5, 1, 5, 10], 
            'epsilon': [0.001, 0.005, 0.01, 0.05, 0.1], 
            'gamma': ['auto', 'scale']}
self.model = GridSearchCV(SVR(), param_grid, scoring='neg_mean_squared_error', cv=5)

Train Models

You can train the model at the beginning of your algorithm and you can periodically re-train it as the algorithm executes.

Warm Up Training Data

You need historical data to initially train the model at the start of your algorithm. To get the initial training data, in the Initializeinitialize method, make a history request.

# Initialize training data with a rolling window of size 252*2 days.
training_length = 252*2
self.training_data = RollingWindow[TradeBar](training_length)
history = self.history[TradeBar](self._symbol, training_length, Resolution.DAILY)
for trade_bar in history:
    self.training_data.add(trade_bar)

Define a Training Method

To train the model, define a method that fits the model with the training data.

# Prepare feature and label data for training by processing rolling window data to create time-series sequences for model training.
def get_features_and_labels(self, n_steps=5):
    training_df = self.pandas_converter.get_data_frame[TradeBar](list(self.training_data)[::-1])
    daily_pct_change = training_df.pct_change().dropna()

    features = []
    labels = []
    for i in range(len(daily_pct_change)-n_steps):
        features.append(daily_pct_change.iloc[i:i+n_steps].values.flatten())
        labels.append(daily_pct_change['close'].iloc[i+n_steps])
    features = np.array(features)
    labels = np.array(labels)

    return features, labels

def my_training_method(self):
    features, labels = self.get_features_and_labels()
    self.model = self.model.fit(features, labels).best_estimator_

Set Training Schedule

To train the model at the beginning of your algorithm, in the Initializeinitialize method, call the Traintrain method.

# Train the model initially to provide a baseline for prediction and decision-making.
self.train(self.my_training_method)

To periodically re-train the model as your algorithm executes, in the Initializeinitialize method, call the Traintrain method as a Scheduled Event.

# Train the model every Sunday at 8:00 AM
self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8, 0), self.my_training_method)

Update Training Data

To update the training data as the algorithm executes, in the OnDataon_data method, add the current TradeBar to the RollingWindow that holds the training data.

# Add the latest bar to training data to ensure the model is trained with the most recent market data.
def on_data(self, slice: Slice) -> None:
    if self._symbol in slice.bars:
        self.training_data.add(slice.bars[self._symbol])

Predict Labels

To predict the labels of new data, in the OnDataon_data method, get the most recent set of features and then call the predict method.

# Generate feature set and predict with the latest data for current market decisions.
features, _ = self.get_features_and_labels()
prediction = self.model.predict(features[-1].reshape(1, -1))
prediction = float(prediction)

You can use the label prediction to place orders.

# Use label prediction to place orders based on forecasted market direction.
if prediction > 0:
    self.SetHoldings(self._symbol, 1)
elif prediction < 0:            
    self.SetHoldings(self._symbol, -1)

Save Models

Follow these steps to save sklearn models into the Object Store:

  1. Set the key name you want to store the model under in the Object Store.
  2. # Set the key to store the model in Object Store for reuse across sessions.
    model_key = "model"
  3. Call the GetFilePathget_file_path method with the key.
  4. # Get the file path to correctly save and access the model in Object Store.
    file_name = self.object_store.get_file_path(model_key)

    This method returns the file path where the model will be stored.

  5. Call the dump method the file path.
  6. # Serialize Python objects into a file to save the model's state for other runs.
    joblib.dump(self.model, file_name)

    If you dump the model using the joblib module before you save the model, you don't need to retrain the model.

Load Models

You can load and trade with pre-trained sklearn models that you saved in the Object Store. To load a sklearn model from the Object Store, in the Initializeinitialize method, get the file path to the saved model and then call the load method.

# Load the sklearn model from Object Store to use its saved state and update with new data if needed.
def initialize(self) -> None:
    if self.object_store.contains_key(model_key):
        file_name = self.object_store.get_file_path(model_key)
        self.model = joblib.load(file_name)

The ContainsKeycontains_key method returns a boolean that represents if the model_key is in the Object Store. If the Object Store does not contain the model_key, save the model using the model_key before you proceed.

Clone Example Algorithm

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: