Contents
Popular Libraries
Keras
Initialize Algorithm
Create Subscriptions
You need to subscribe to some data to train the model. For example, to get daily data for the SPY ETF in the last 2 year, run:
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
Set Training Schedule
To initialize and train the model, you can call the Train
method in Initialize
.
def Initialize(self) -> None: self.Train(self.MyTrainingMethod)
You can also recalibrate the model periodically by calling the Train
method as a scheduled event.
# Set MyTrainingMethod to be executed at 8:00 am every Sunday self.Train(self.DateRules.Every(DayOfWeek.Sunday), self.TimeRules.At(8,0), self.MyTrainingMethod)
Train Models
In this example, a neural-network regression prediction model using the following features and labels will be trained:
Data Category | Description |
---|---|
Features | Daily percent change of the open, high, low, close, and volume of the SPY over the last 5 days |
Labels | Daily percent return of the SPY over the next day |
The following image shows the time difference between the features and labels:

Follow these steps to create a method to train your model:
History Call
You need historical data to train the model. Call History
with Symbol
, timerule, and resolution to obtain historical data. In this example, 2 years of daily trade bar data is used.
self.History(self.spy, 252*2, Resolution.Daily)
Prepare Data
Follow the below steps to create a method to prepare the data for training and prediction.
- Create a method to process the data for the algorithm class, with input data and number of timestep as arguments.
- Call the
pct_change
anddropna
methods. - Loop through the
daily_pct_change
DataFrame and collect the features and labels. - Convert the lists of features and labels into
numpy
arrays and return them.
def ProcessData(self, data, n_tsteps=5):
daily_pct_change = history.pct_change().dropna()
n_steps = 5
features = [] labels = [] for i in range(len(daily_pct_change)-n_steps): features.append(daily_pct_change.iloc[i:i+n_steps].values) labels.append(daily_pct_change['close'].iloc[i+n_steps])
features = np.array(features) labels = np.array(labels) return features, labels
Build Model
Follow the below steps to create a method to build the model.
- Create a method to build the model for the algorithm class.
- Call the
Sequential
constructor with a list of layers. - Call the
compile
method with a loss function, an optimizer, and a list of metrics to monitor. - return the trained model.
def BuildModel(self):
model = Sequential([Dense(10, input_shape=(5,5), activation='relu'), Dense(10, activation='relu'), Flatten(), Dense(1)])
Set the input_shape
of the first layer to (5, 5)
because each sample contains the percent change of 5 factors (percent change of the open, high, low, close, and volume) over the previous 5 days. Call the Flatten
constructor because the input is 2-dimensional but the output is just a single value.
model.compile(loss='mse', optimizer=Adam(), metrics=['mae', 'mse'])
return model
Fit Model
Follow the below steps to fit the model with the prepared data.
- Instantiate the model and save it as a class variable.
- Call the
fit
method with the features and labels of the training dataset and a number of epochs.
self.model = self.BuildModel()
self.model.fit(X_train, y_train, epochs=5)
Save Models
You can save keras
models using the ObjectStore by following these steps.
- Set the key name of the model to be stored in the ObjectStore.
- Call the
GetFilePath
method with the key. - Call the
save
method the file path. - Call the
Save
method with the key.
model_key = "model"
file_name = self.ObjectStore.GetFilePath(model_key)
This method returns the file path where the model will be stored.
model.save(file_name)
self.ObjectStore.Save(model_key)
Load Models
You can load and trade with pre-trained keras
models that saved in ObjectStore. To do so, follow these steps to load it:
- Check if the
ObjectStore
already has the model saved duringInitialize
with the model key. - Call the
GetFilePath
method with the key name. - Call the
load_model
method with the file path.
def Initialize(self) -> None: if self.ObjectStore.ContainsKey(model_key):
This method returns a boolean that represents if the model_key
is in the ObjectStore. If the ObjectStore does not contain the model_key
, save the model using the model_key
before you proceed.
file_name = self.ObjectStore.GetFilePath(model_key)
This method returns the path where the model is stored.
self.model = load_model(file_name)
This method returns the saved model.
Deploy Model
You need to build and train the model before you deploy it for backtesting and trading. Follow these steps to deploy the model:
- Process new data in form of
pandas.Dataframe
. - Make new prediction.
- Trade based on the new prediction.
new_X, __ = self.ProcessData(df)
prediction = self.model.predict(new_X) prediction = float(prediction[-1])
if prediction > 0: self.SetHoldings(self.spy, 1) elif prediction < 0: self.SetHoldings(self.spy, -1)