How to do it...

Execute the following steps to train a multilayer perceptron in PyTorch.

  1. Import the libraries:
import yfinance as yfimport numpy as npimport torchimport torch.optim as optimimport torch.nn as nnimport torch.nn.functional as Ffrom import (Dataset, TensorDataset,                              DataLoader, Subset)from sklearn.metrics import mean_squared_errordevice = 'cuda' if torch.cuda.is_available() else 'cpu'
  1. Define the parameters:
# dataTICKER = 'ANF'START_DATE = '2010-01-02'END_DATE = '2019-12-31'N_LAGS = 3# neural network VALID_SIZE = 12BATCH_SIZE = 5N_EPOCHS = 1000
  1. Download the stock prices of Abercrombie and Fitch and process the data:
df =,                  start=START_DATE,                  end=END_DATE,                 progress=False)df = df.resample("M").last() ...

Get Python for Finance Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.