Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

PyTorch

This page provides an example how to develop a strategy that uses PyTorch model to make predictions.

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 7
      5 import roboquant as rq
      6 from roboquant.journals.basicjournal import BasicJournal
----> 7 from roboquant.ai.features import BarFeature, CombinedFeature, MaxReturnFeature, PriceFeature, SMAFeature, VolumeFeature
      8 from roboquant.ai.strategies import TimeSeriesStrategy, logger

ImportError: cannot import name 'CombinedFeature' from 'roboquant.ai.features' (/home/runner/work/roboquant.py/roboquant.py/roboquant/ai/features.py)

Data and Configuration

Here we define some configuration variables, the feed we’ll be using, and the timeframes for training and testing.

prediction_steps = 5 # predict 5 steps in the future
feed = rq.feeds.YahooFeed("AAPL", start_date="2000-01-01")
apple = feed.get_asset("AAPL")
train_tf = rq.Timeframe.fromisoformat("2000-01-01", "2020-01-01")
test_tf = rq.Timeframe.fromisoformat("2020-01-01", "2030-01-01")

Model

We start with defining a LSTM model we want to use. LSTM (Long Short-Term Memory) is a type of recurrent neural network (RNN) well-suited for time-series and sequential data.

Unlike standard RNNs, LSTMs can learn long-term dependencies by using a gating mechanism that controls the flow of information, making them effective for financial time-series prediction where patterns may span many time steps.

Please note this is just an example and likely to overfit with the limited amount of data we have in this example.

class TimeSeriesLSTM(nn.Module):

    def __init__(self, feature_size) -> None:
        super().__init__()
        self.lstm = nn.LSTM(feature_size, 16, batch_first=True, num_layers=2, dropout=0.4)
        self.flatten = nn.Flatten()
        self.linear = nn.Linear(16, 1)

    def forward(self, inputs):
        output, _ = self.lstm(inputs)
        output = F.relu(self.flatten(output[:, -1, :]))
        output = self.linear(output)
        return output

Features

Now we define the input and label features we want to use. This is just a small sample of the available features and custom features can also be added.

input_feature = CombinedFeature(
    BarFeature(apple).returns(),
    SMAFeature(PriceFeature(apple), 10).returns(),
    SMAFeature(PriceFeature(apple), 20).returns(),
    SMAFeature(VolumeFeature(apple), 25).returns(),
).normalize(20)

label_feature = MaxReturnFeature(
    PriceFeature(apple, price_type="HIGH"),
    prediction_steps
)

Strategy

Finally we create the actual strategy using the LSTM model we just defined.

model = TimeSeriesLSTM(input_feature.size())
strategy = TimeSeriesStrategy(input_feature, label_feature, model, apple, sequences=20, buy_pct=0.02, sell_pct=0.02)

Training

For fitting we use the timeframe with the first twenty years of data. There is also support for validation.

strategy.fit(
    feed,
    timeframe=train_tf,
    epochs=20,
    validation_split=0.25,
    prediction=prediction_steps)

Testing

After the model has been fitted, we can now use the strategy in a test run to see how it performs on unseen historic data.

account = rq.run(feed, strategy, timeframe=test_tf)