Skip to content

About

This project implements a Siamese architecture based deep learning approach for predicting stock price movements from Limit Order Book (LOB) data.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

LOB Stock Price Movement Prediction

Siamese LSTM + Multi-Head Attention

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


Table of Contents

  1. What This Script Does
  2. System Requirements
  3. Setup — Windows
  4. Setup — Mac
  5. Setup — Linux
  6. Dataset Setup
  7. Run the Script
  8. Expected Terminal Output
  9. Output Files
  10. Changing Settings
  11. Troubleshooting

What This Script Does

This script:

  1. Loads tick-by-tick trade data from the MICEX (Moscow Exchange) dataset
  2. Builds LOB-style features using rolling window statistics
  3. Labels each tick as Up / Stationary / Down based on future price change
  4. Trains a Siamese LSTM + Multi-Head Attention neural network
  5. Evaluates the model using Accuracy, F1-Score, and Cohen's Kappa
  6. Saves training curves and confusion matrix as PNG files
  7. Saves the best model weights as a .pt file

System Requirements

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

Setup — Windows

Step 1 — Install Python

  1. Go to https://www.python.org/downloads/
  2. Download Python 3.10 or later
  3. During installation, tick the box "Add Python to PATH"
  4. Click Install Now

Verify installation:

python --version

Expected output: Python 3.10.x


Step 2 — Open Terminal

Press Windows + R → type cmd → press Enter
OR open VS Code → Terminal → New Terminal


Step 3 — Install Dependencies

Option A — Using pip (recommended for most users)

pip install pandas numpy scikit-learn matplotlib seaborn kagglehub

Then install PyTorch (CPU version — works on all Windows machines):

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu

If pip install torch keeps timing out: Download the .whl file manually from your browser: https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-win_amd64.whl Then run: pip install C:\Users\YourName\Downloads\torch-2.1.0+cpu-cp310-cp310-win_amd64.whl

Option B — Using Anaconda (if already installed)

conda install pytorch torchvision torchaudio cpuonly -c pytorch
pip install pandas numpy scikit-learn matplotlib seaborn kagglehub

Step 4 — Fix OMP Warning (Windows only)

If you see an OMP error when running, set this environment variable:

setx KMP_DUPLICATE_LIB_OK TRUE

Close and reopen the terminal after running this command.


Setup — Mac

Step 1 — Install Python

# 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 python

Step 2 — Install Dependencies

pip3 install pandas numpy scikit-learn matplotlib seaborn kagglehub

Install PyTorch (Apple Silicon M1/M2/M3):

pip3 install torch torchvision torchaudio

Install PyTorch (Intel Mac):

pip3 install torch torchvision torchaudio

PyTorch automatically detects your Mac chip. No special flags needed on modern Macs.


Step 3 — Fix Class Weight Error (Mac only)

If you see ValueError: classes should have valid labels, this is a data size issue.
See Troubleshooting section below.


Setup — Linux (Ubuntu/Debian)

Step 1 — Install Python and pip

sudo apt update
sudo apt install python3 python3-pip python3-venv -y
python3 --version

Step 2 — Install Dependencies

pip3 install pandas numpy scikit-learn matplotlib seaborn kagglehub
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu

Step 3 — Verify All Packages

python3 -c "import torch, pandas, numpy, sklearn, matplotlib, seaborn, kagglehub; print('All OK')"

Expected output: All OK


Dataset Setup

Option A — Auto Download (Easiest)

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

  1. Go to https://www.kaggle.com/settings
  2. Scroll to API section
  3. Click "Create New Token"
  4. A file called kaggle.json downloads 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.json

Mac / Linux:

mkdir -p ~/.kaggle
mv ~/Downloads/kaggle.json ~/.kaggle/kaggle.json
chmod 600 ~/.kaggle/kaggle.json

Step 4 — The script will auto-download when you run it ✅


Option B — Manual Download

  1. Go to https://www.kaggle.com/datasets/izaznov/micex-lob-of
  2. Click Download (requires Kaggle login)
  3. Unzip the downloaded file
  4. 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

Option C — Use Your Own CSV Files

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

Run the Script

Step 1 — Navigate to Your Project Folder

Windows:

cd C:\Users\YourUsername\Downloads

Mac / Linux:

cd ~/Downloads

Or wherever you saved lob_stock_prediction.py.


Step 2 — Run the Script

Windows:

python lob_stock_prediction.py

Mac / Linux:

python3 lob_stock_prediction.py

Step 3 — If Dataset Not Found (Auto Download)

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


Expected Terminal Output

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

Output Files

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

Changing Settings

All settings are in the Config class at the top of the script (lines 57–77).

Change data size (for faster runs)

Find line 154 in the script:

frames.append(df.head(5000))   # currently: 5,000 rows

Change 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 hours

Change prediction horizon

HORIZON = 10    # predict 10 ticks ahead (default)
HORIZON = 20    # predict 20 ticks ahead
HORIZON = 50    # predict 50 ticks ahead
HORIZON = 100   # predict 100 ticks ahead

Change epochs

EPOCHS = 10    # faster, less thorough
EPOCHS = 50    # default
EPOCHS = 100   # thorough, slower

Change window size

WINDOW = 50     # use last 50 ticks as input
WINDOW = 100    # default — use last 100 ticks
WINDOW = 200    # more context, slower

Troubleshooting

Error: ModuleNotFoundError: No module named 'torch'

# Windows
pip install torch --index-url https://download.pytorch.org/whl/cpu

# Mac / Linux
pip3 install torch

Error: No module named 'kagglehub'

pip install kagglehub

Error: WinError 32 — file locked (Windows only)

Close all Python processes in Task Manager, then run:

pip install torch --index-url https://download.pytorch.org/whl/cpu --user

Error: OMP: Error #15: Initializing libiomp5md.dll (Windows only)

# Run this ONCE — sets the environment variable permanently
setx KMP_DUPLICATE_LIB_OK TRUE

Close and reopen the terminal, then run the script again.


Error: TypeError: ReduceLROnPlateau got an unexpected keyword argument 'verbose'

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)

Error: ValueError: classes should have valid labels that are in y (Mac)

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]

Error: No such file or directory — script not found

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.py

If 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.py

Script running but stuck / no output after "Training"

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


100% Accuracy — is something wrong?

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.


Quick Start Summary

# 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

Project Info

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

About

This project implements a Siamese architecture based deep learning approach for predicting stock price movements from Limit Order Book (LOB) data.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages