Project: An Efficient Deep Learning Model to Predict Stock Price Movement Based on Limit Order Book
Dataset: MICEX LOB OF (Moscow Exchange) — Kaggle Link
Authors: 25191489 | 24124982 | 24244732 | 25120344
College: National College of Ireland, Dublin
- What This Script Does
- System Requirements
- Setup — Windows
- Setup — Mac
- Setup — Linux
- Dataset Setup
- Run the Script
- Expected Terminal Output
- Output Files
- Changing Settings
- Troubleshooting
This script:
- Loads tick-by-tick trade data from the MICEX (Moscow Exchange) dataset
- Builds LOB-style features using rolling window statistics
- Labels each tick as Up / Stationary / Down based on future price change
- Trains a Siamese LSTM + Multi-Head Attention neural network
- Evaluates the model using Accuracy, F1-Score, and Cohen's Kappa
- Saves training curves and confusion matrix as PNG files
- Saves the best model weights as a
.ptfile
| Requirement | Minimum | Recommended |
|---|---|---|
| Python | 3.8+ | 3.10+ |
| RAM | 4 GB | 8 GB+ |
| Storage | 2 GB free | 5 GB free |
| GPU | Not required | NVIDIA CUDA (optional, faster) |
| OS | Windows 10 / macOS 11 / Ubuntu 20.04 | Any modern OS |
- Go to https://www.python.org/downloads/
- Download Python 3.10 or later
- During installation, tick the box "Add Python to PATH"
- Click Install Now
Verify installation:
python --versionExpected output: Python 3.10.x
Press Windows + R → type cmd → press Enter
OR open VS Code → Terminal → New Terminal
pip install pandas numpy scikit-learn matplotlib seaborn kagglehubThen install PyTorch (CPU version — works on all Windows machines):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpuIf pip install torch keeps timing out: Download the
.whlfile manually from your browser:https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-win_amd64.whlThen run:pip install C:\Users\YourName\Downloads\torch-2.1.0+cpu-cp310-cp310-win_amd64.whl
conda install pytorch torchvision torchaudio cpuonly -c pytorch
pip install pandas numpy scikit-learn matplotlib seaborn kagglehubIf you see an OMP error when running, set this environment variable:
setx KMP_DUPLICATE_LIB_OK TRUEClose and reopen the terminal after running this command.
# Check if Python 3 is already installed
python3 --version
# If not installed, use Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install pythonpip3 install pandas numpy scikit-learn matplotlib seaborn kagglehubInstall PyTorch (Apple Silicon M1/M2/M3):
pip3 install torch torchvision torchaudioInstall PyTorch (Intel Mac):
pip3 install torch torchvision torchaudioPyTorch automatically detects your Mac chip. No special flags needed on modern Macs.
If you see ValueError: classes should have valid labels, this is a data size issue.
See Troubleshooting section below.
sudo apt update
sudo apt install python3 python3-pip python3-venv -y
python3 --versionpip3 install pandas numpy scikit-learn matplotlib seaborn kagglehub
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpupython3 -c "import torch, pandas, numpy, sklearn, matplotlib, seaborn, kagglehub; print('All OK')"Expected output: All OK
The script automatically downloads the dataset when you run it, if you have a Kaggle account.
Step 1 — Create Kaggle Account Go to https://www.kaggle.com and sign up (free)
Step 2 — Get Kaggle API Key
- Go to https://www.kaggle.com/settings
- Scroll to API section
- Click "Create New Token"
- A file called
kaggle.jsondownloads to your computer
Step 3 — Place the API Key
Windows:
# Create the folder
mkdir C:\Users\YourUsername\.kaggle
# Move the file (replace YourUsername with your actual Windows username)
move C:\Users\YourUsername\Downloads\kaggle.json C:\Users\YourUsername\.kaggle\kaggle.jsonMac / Linux:
mkdir -p ~/.kaggle
mv ~/Downloads/kaggle.json ~/.kaggle/kaggle.json
chmod 600 ~/.kaggle/kaggle.jsonStep 4 — The script will auto-download when you run it ✅
- Go to https://www.kaggle.com/datasets/izaznov/micex-lob-of
- Click Download (requires Kaggle login)
- Unzip the downloaded file
- Place the folder so your files are at:
your-project-folder/
├── lob_stock_prediction.py
└── micex-lob-of/
├── Deals_GAZP.csv
├── LOB_GAZP.csv
├── Deals_SBER.csv
├── LOB_SBER.csv
├── Deals_VTBR.csv
└── LOB_VTBR.csv
If you already have the CSV files, place them in a folder called micex-lob-of next to the Python script:
your-project-folder/
├── lob_stock_prediction.py
└── micex-lob-of/
├── Deals_GAZP.csv ← trade events (semicolon-separated)
├── Deals_SBER.csv
└── Deals_VTBR.csv
The CSV files must be semicolon-separated with columns:
event_id ; server_time ; exchange_time ; price ; quantity ; flags
Windows:
cd C:\Users\YourUsername\DownloadsMac / Linux:
cd ~/DownloadsOr wherever you saved lob_stock_prediction.py.
Windows:
python lob_stock_prediction.pyMac / Linux:
python3 lob_stock_prediction.pyThe script will print:
[INFO] Downloading MICEX LOB OF dataset via kagglehub...
Downloading to C:\Users\...\micex-lob-of\1.archive...
100%| ████████████████ | 54.4M/54.4M
[INFO] Dataset ready at: C:\Users\...\micex-lob-of\versions\1
Then automatically continue to training.
When the script runs successfully, you will see this sequence:
============================================================
LOB Stock Price Movement — Siamese LSTM + MHA
============================================================
Device : cpu
Horizon : k=10 | Window: 100 ticks
============================================================
[INFO] Found 3 CSV file(s) in ./micex-lob-of
[LOAD] Deals_GAZP.csv: 595,132 rows, 6 cols
[LOAD] Deals_SBER.csv: 992,616 rows, 6 cols
[LOAD] Deals_VTBR.csv: 245,000 rows, 6 cols
[INFO] Total rows loaded: 15,000
[INFO] Working with 15,000 ticks
[INFO] Ask features: (15000, 22) | Bid features: (15000, 22)
[INFO] Label distribution:
Class 0 ( Up): 23 (0.2%)
Class 1 ( Stationary): 14,954 (99.7%)
Class 2 ( Down): 23 (0.1%)
[INFO] Split — Train: 10,400 | Val: 2,150 | Test: 2,150
[MODEL] Siamese LSTM + MHA | Params: 111,619
Ask dim=22 Bid dim=22
Hidden=64 Layers=2 Heads=4
--------------------------------------------------------------
Training (max 50 epochs | patience 10)
--------------------------------------------------------------
Ep 001/050 | tr_loss=0.1823 tr_acc=0.9967 | vl_loss=0.0001 vl_acc=1.0000 vl_f1=1.0000
Ep 002/050 | tr_loss=0.1654 tr_acc=0.9971 | vl_loss=0.0001 vl_acc=1.0000 vl_f1=1.0000
...
[Early Stop] epoch 11 | best val F1: 1.0000
============================================================ FINAL TEST RESULTS
Accuracy : 1.0000 (100.00%)
Weighted F1 : 1.0000
Cohen's Kappa : nan
[INFO] Saved → training_curves.png
[INFO] Saved → confusion_matrix.png
============================================================
Done! Best model saved → best_siamese_model.pt
============================================================
After the script finishes, these files are saved in the same folder as the Python script:
| File | Description |
|---|---|
training_curves.png |
Graph showing Loss and Accuracy over epochs for Train and Validation |
confusion_matrix.png |
Heatmap showing correct/incorrect predictions per class |
best_siamese_model.pt |
Best model weights — can be loaded later for predictions |
All settings are in the Config class at the top of the script (lines 57–77).
Find line 154 in the script:
frames.append(df.head(5000)) # currently: 5,000 rowsChange to use more data:
frames.append(df.head(50000)) # 50,000 rows — better results, ~5 min
frames.append(df.head(200000)) # 200,000 rows — good results, ~20 min
frames.append(df) # ALL rows — best results, ~1-2 hoursHORIZON = 10 # predict 10 ticks ahead (default)
HORIZON = 20 # predict 20 ticks ahead
HORIZON = 50 # predict 50 ticks ahead
HORIZON = 100 # predict 100 ticks aheadEPOCHS = 10 # faster, less thorough
EPOCHS = 50 # default
EPOCHS = 100 # thorough, slowerWINDOW = 50 # use last 50 ticks as input
WINDOW = 100 # default — use last 100 ticks
WINDOW = 200 # more context, slower# Windows
pip install torch --index-url https://download.pytorch.org/whl/cpu
# Mac / Linux
pip3 install torchpip install kagglehubClose all Python processes in Task Manager, then run:
pip install torch --index-url https://download.pytorch.org/whl/cpu --user# Run this ONCE — sets the environment variable permanently
setx KMP_DUPLICATE_LIB_OK TRUEClose and reopen the terminal, then run the script again.
Find this line in the script:
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5, factor=0.5, verbose=False)Change to:
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=5, factor=0.5)Find line ~460 in the script:
cw = compute_class_weight('balanced', classes=np.array([0, 1, 2]), y=labels[:n_tr])Replace with:
present_classes = np.unique(labels[:n_tr])
cw_values = compute_class_weight('balanced', classes=present_classes, y=labels[:n_tr])
cw = np.ones(3, dtype=np.float32)
for i, c in enumerate(present_classes):
cw[c] = cw_values[i]Make sure you navigated to the correct folder:
# Windows — check current folder
dir lob_stock_prediction.py
# Mac/Linux — check current folder
ls lob_stock_prediction.pyIf not found, use the full path:
# Windows
python C:\Users\YourUsername\Downloads\lob_stock_prediction.py
# Mac/Linux
python3 /Users/YourUsername/Downloads/lob_stock_prediction.pyThe script is still running — it is training. Wait for it.
To speed it up, reduce data size (see Changing Settings).
To check if it's still running: the terminal cursor should be blinking with no new > prompt.
This is expected when using a small dataset (5,000 rows).
99.9% of labels are "Stationary", so the model predicts everything as Stationary and gets 100% accuracy.
Solution: Increase data size to df.head(200000) or more to get meaningful results.
# 1. Install all dependencies
pip install pandas numpy scikit-learn matplotlib seaborn kagglehub torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
# 2. Place your CSV files in ./micex-lob-of/ OR set up Kaggle API for auto-download
# 3. Run the script
python lob_stock_prediction.py
# 4. Check outputs
# training_curves.png — loss and accuracy graph
# confusion_matrix.png — prediction heatmap
# best_siamese_model.pt — saved model weights| Item | Detail |
|---|---|
| Paper | arxiv.org/abs/2505.22678 |
| Dataset | kaggle.com/datasets/izaznov/micex-lob-of |
| Model | Siamese LSTM + Multi-Head Attention |
| Task | 3-class: Up / Stationary / Down |
| College | National College of Ireland |
| Module | Data Analytics — MSc AI |