---
title: "Keras"
description: "This page explains how to build, train, deploy and store Keras models."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/machine-learning/popular-libraries/keras
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/machine-learning/popular-libraries/keras.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/31%20Machine%20Learning/03%20Popular%20Libraries/05%20Keras
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Keras

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Machine Learning > [Popular Libraries](https://www.quantconnect.com/docs/v2/writing-algorithms/machine-learning/popular-libraries.md) > Keras

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

This page explains how to build, train, deploy and store `Keras` models.

## Import Libraries

Import the `keras` libraries.

```python
from AlgorithmImports import *
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
```

## Create Subscriptions

In the `initialize` method, [subscribe to some data](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes.md) so you can train the `keras` model and make predictions.

```python
# Add a security and save a reference to its Symbol.
self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
```

## Build Models

In this example, build a neural-network regression model that uses the following features and labels:

| 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:

![Features and labels for training](https://cdn.quantconnect.com/i/tu/ml-keras-function.png)

Follow the below steps to build the model:

1. In the `initialize` method, create a `Sequential` object with several layers.
   ```python
   # Build a neural network with Dense layers for feature extraction, Flatten for reshaping, and a final
   # Dense layer for prediction.
   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.
2. Call the `compile` method with a loss function, an optimizer, and a list of metrics to monitor.
   ```python
   # Configure the model to use mean squared error loss, Adam optimizer, and track mean absolute error
   # and mean squared error for performance evaluation.
   self.model.compile(loss='mse',
                      optimizer=Adam(),
                      metrics=['mae', 'mse'])
   ```

## 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 `initialize` method, make a [history request](https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/history-requests.md).

```python
# Fill a RollingWindow with 2 years of historical TradeBar objects.
training_length = 252*2
self.training_data = RollingWindow(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.

```python
# Prepare feature and label data for training by processing the RollingWindow data into a time series.
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)
        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.fit(features, labels, epochs=5)
```

### Set Training Schedule

To train the model at the beginning of your algorithm, in the `initialize` method, call the `train` method.

```python
# 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 `initialize` method, call the `train` method as a [Scheduled Event](https://www.quantconnect.com/docs/v2/writing-algorithms/scheduled-events.md).

```python
# 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 `on_data` method, add the current `TradeBar` to the `RollingWindow` that holds the training data.

```python
# 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 `on_data` method, get the most recent set of features and then call the `predict` method.

```python
# Get the current feature set and make a prediction.
features, _ = self.get_features_and_labels()
features = features[-1].reshape(1, 5, 5)
prediction = float(self.model.predict(features)[-1])
```

You can use the label prediction to place orders.

```python
# Place orders based on the forecasted market direction.
if prediction > 0:
    self.set_holdings(self._symbol, 1)
elif prediction < 0:
    self.set_holdings(self._symbol, -1)
```

## Save Models

Follow these steps to save `keras` models into the [Object Store](https://www.quantconnect.com/docs/v2/writing-algorithms/object-store.md):

1. Set the key name you want to store the model under in the Object Store.
   The key must end with a `.keras` extension for the native Keras format (recommended) or a `.h5` extension.
   ```python
   # Set the key to store the model in the Object Store so you can use it later.
   model_key = f"{self.project_id}/model.keras"
   ```
2. Call the `get_file_path` method with the key.
   ```python
   # 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.
3. Call the `save` method with the file path.
   ```python
   # Serialize the model and save it to the file.
   self.model.save(file_name)
   ```

## Upload Models

If you train models locally or in another environment, you can upload the model files to the Object Store so your algorithms can use them. Use the model key that matches the key your algorithm expects when it calls `object_store.get_file_path`.

Follow one of these approaches to upload your model files:

### LEAN CLI

Run the [`lean cloud object-store set`](https://www.quantconnect.com/docs/v2/lean-cli/api-reference/lean-cloud-object-store-set.md) command to upload a local file to the Object Store.

```
$ lean cloud object-store set <projectId>/model.keras <pathTo>/model.keras
```

Replace `<projectId>` with your project Id and `<pathTo>` with the path to the local model file.

### Cloud API

Use the [Upload Object Store Files](https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/object-store-management/upload-object-store-files.md) endpoint to upload a model file through the API.

## Load Models

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

```python
# Load the model from Object Store to use its saved state and update it with new data if needed.
def initialize(self) -> None:
    model_key = f"{self.project_id}/model.keras"
    if self.object_store.contains_key(model_key):
        file_name = self.object_store.get_file_path(model_key)
        self.model = load_model(file_name)
```

The `contains_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.

## Examples

The following examples demonstrate some common practices for using `Keras` library.

### Example 1: Multi-layer Perceptron Model

The below algorithm makes use of `Keras` library to predict the future price movement using the previous 5 OHLCV data. The model is built with multi-layer perceptrons, ReLu activation function, and Adam optimization. It is trained using rolling 2-year data. To ensure the model applicable to the current market environment, we recalibrate the model on every Sunday.

```python
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam

class KerasExampleAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)  # Set Strategy Cash
        # Request SPY data for model training, prediction and trading.
        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol

        # Retrieve already trained model from object store to use immediately.
        self._model_key = f"{self.project_id}/model.keras"
        if self.object_store.contains_key(self._model_key):
            file_name = self.object_store.get_file_path(self._model_key)
            self.model = load_model(file_name)

        # Create a MLP model otherwise to predict price movement.
        else:
            self.model = Sequential([Dense(10, input_shape=(5,5), activation='relu'),
                            Dense(10, activation='relu'),
                            Flatten(),
                            Dense(1)])
            self.model.compile(loss='mse',
                    optimizer=Adam(),
                    metrics=['mae', 'mse'])

        # Use the session rolling window to cache 2-year daily data for training.
        training_length = 252*2
        self.securities[self._symbol].session.size = training_length
        self.set_warm_up(training_length, Resolution.DAILY)

    def on_warmup_finished(self) -> None:
        # Train the model to use the prediction right away.
        self.train(self.my_training_method)
        # Recalibrate the model weekly to ensure its accuracy on the updated domain.
        self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8, 0), self.my_training_method)

    def get_features_and_labels(self, n_steps=5) -> tuple[float, float]:
        # Train and predict the return data, which is more normalized and stationary.
        training_df = self.pandas_converter.get_data_frame[TradeBar](list(self.securities[self._symbol].session)[::-1])
        daily_pct_change = training_df.pct_change().dropna()

        # Stack the data for 5-day OHLCV data per each sample to train with.
        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

    def my_training_method(self) -> None:
        # Prepare the processed training data.
        features, labels = self.get_features_and_labels()
        # Recalibrate the model based on updated data.
        self.model.fit(features, labels, epochs=5)

    def on_data(self, slice: Slice) -> None:
        if self.is_warming_up or self._symbol not in slice.bars:
            return

        # Get prediction by the updated features.
        features, _ = self.get_features_and_labels()
        features = features[-1].reshape(1, 5, 5)
        prediction = float(self.model.predict(features)[-1])

        # If the predicted direction is going upward, buy SPY.
        if prediction > 0:
            self.set_holdings(self._symbol, 1)
        # If the predicted direction is going downward, sell SPY.
        elif prediction < 0:
            self.set_holdings(self._symbol, -1)

    def on_end_of_algorithm(self):
        # Store the model to object store to retrieve it in other instances in case the algorithm stops.
        file_name = self.object_store.get_file_path(self._model_key)
        self.model.save(file_name)
```
