Forecasting weekly closing prices of Barclays PLC (BARC.L) using a stacked LSTM neural network trained on 2.5 years of historical market data.
This project builds a Long Short-Term Memory (LSTM) neural network to forecast stock prices β one of the most challenging problems in financial machine learning. Unlike traditional models, LSTMs learn long-range temporal dependencies, making them well-suited for financial time series where past behaviour influences future price movements.
The model is trained on weekly OHLCV data for Barclays PLC (LON: BARC) from January 2020 to August 2022, covering the COVID-19 crash, the recovery rally, and the 2022 macro downturn β a highly varied test of the model's generalisation ability.
Full BARC.L weekly close price history. The vertical dashed line marks the 80/20 train/test boundary.
A stacked two-layer LSTM followed by fully connected Dense layers for regression output.
| Layer | Type | Units | Notes |
|---|---|---|---|
| Input | β | 60 Γ 1 | 60-week lookback window |
| LSTM 1 | LSTM | 50 | return_sequences=True |
| LSTM 2 | LSTM | 50 | return_sequences=False |
| Dense 1 | Dense | 12 | Hidden layer |
| Dense 2 | Dense | 1 | Price output |
Raw close prices are MinMax scaled to [0, 1] before training to stabilise gradient updates. The dataset is split into 80% training and 20% testing with no data leakage. Each training sample uses a 60-timestep sliding window to predict the next week's price.
from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(dataset)
training_data_len = math.ceil(len(dataset) * .8) # β 110 weeks
# Build sliding windows: [t-60 ... t-1] β predict t for i in range(60, len(train_data)): x_train.append(train_data[i-60:i, 0]) y_train.append(train_data[i, 0])
Compiled with the Adam optimiser and Mean Squared Error loss. Trained for 2 epochs with a batch size of 2.
| Epoch | Training Loss (MSE) |
|---|---|
| 1 | 0.1082 |
| 2 | 0.0053 |