Detect correlation breakdown anomalies in financial markets using LSTM neural networks with Markov temporal smoothing
A production-ready machine learning pipeline for detecting anomalous market behavior through correlation breakdown analysis. This project combines PyTorch LSTM models with a simple Markov (HMM-lite) temporal smoother to identify periods when asset correlations deviate significantly from normal patterns.
- LSTM Anomaly Detection: PyTorch-based LSTM model trained on ~14 years of financial data
- VIX Integration: Incorporates VIX (volatility index) as a systemic risk feature
- Markov Temporal Smoother: Simple 2-3 state HMM-lite reduces false positives via temporal smoothing
- SQL Data Pipeline: DuckDB-based pipeline for efficient data processing and storage
- Interactive Dashboard: Streamlit dashboard for real-time exploration and visualization
- Production Ready: Complete testing, CI/CD, Docker support, and comprehensive documentation
| Model | Precision | Recall | F1 Score | ROC-AUC | PR-AUC |
|---|---|---|---|---|---|
| LSTM | 0.750 | 0.600 | 0.667 | 1.000 | 0.787 |
| Markov | 0.000 | 0.000 | 0.000 | 1.000 | 0.787 |
Note: Metrics will be computed after running make all. See Running the Pipeline below.
Last Updated: 2025-10-07 10:13 UTC (commit: cf28c22)
Dataset: 2010-2024 (SPY, XLF, XLK, VNQ + VIX)
βββββββββββββββ ββββββββββββββββ βββββββββββββββ
β Data ββββββΆβ Features ββββββΆβ Labels β
β (yfinance) β β (rolling corrβ β(breakdown) β
β SPY,XLF, β β vol, VIX) β β rules β
β XLK,VNQ,VIX β ββββββββββββββββ βββββββββββββββ
βββββββββββββββ β β
βΌ βΌ
ββββββββββββββββββββββββββββββββ
β DuckDB Database β
β (raw_prices, features, β
β labels, predictions) β
ββββββββββββββββββββββββββββββββ
β
βββββββββββββββ΄ββββββββββββββ
βΌ βΌ
ββββββββββββββββ ββββββββββββββββ
β LSTM Model β β Markov β
β (PyTorch) ββββββββββΆ β Smoother β
β β p_anom β (HMM-lite) β
ββββββββββββββββ ββββββββββββββββ
β β
βββββββββββββββ¬ββββββββββββββ
βΌ
ββββββββββββββββββββββββββββ
β Evaluation Pipeline β
β (Metrics, Plots, JSON) β
ββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββ
β Streamlit Dashboard β
β (Interactive Viz) β
ββββββββββββββββββββββββββββ
repo/
βββ src/
β βββ data/
β β βββ download.py # Fetch OHLCV + VIX from Yahoo Finance
β β βββ ingest_sql.py # Load data into DuckDB
β β βββ features.py # Feature engineering (corr, vol, VIX)
β βββ models/
β β βββ lstm.py # PyTorch LSTM model
β β βββ markov_smoother.py # HMM-lite temporal smoother
β β βββ thresholds.py # Threshold tuning utilities
β βββ pipelines/
β β βββ train.py # Training orchestration
β β βββ predict.py # Prediction generation
β β βββ evaluate.py # Metrics & plots
β βββ viz/
β β βββ dashboard.py # Streamlit dashboard
β βββ utils/
β βββ config.py # Configuration management
β βββ seed.py # Random seed utilities
β βββ logging_config.py # Logging setup
β βββ io.py # I/O utilities
βββ sql/
β βββ schema.sql # Database schema
βββ tests/
β βββ test_features.py # Feature engineering tests
β βββ test_lstm.py # LSTM model tests
β βββ test_markov.py # Markov smoother tests
β βββ test_end_to_end.py # Integration tests
βββ config.yaml # Main configuration file
βββ requirements.txt # Python dependencies
βββ Makefile # Build automation
βββ Dockerfile # Container definition
βββ README.md # This file
- Python 3.9+
- pip
# Clone the repository
git clone https://github.com/jamesolaitan/Anomalous-Market-Behavior-Recognition-with-Machine-Learning.git
cd Anomalous-Market-Behavior-Recognition-with-Machine-Learning
# Install dependencies
make setup
# Or manually:
pip install -r requirements.txt
pre-commit installRun the complete pipeline with a single command:
make allThis executes:
- Data download (
make data): Fetches ~14 years of data from Yahoo Finance - Feature engineering (
make features): Computes rolling correlations, volatility, z-scores, VIX features - Training (
make train): Trains LSTM model with early stopping (~100 epochs) - Prediction (
make predict): Generates predictions and applies Markov smoothing - Evaluation (
make eval): Computes metrics (F1, ROC-AUC, PR-AUC) and generates plots
Or run steps individually:
make data # Download and ingest data
make features # Engineer features
make train # Train LSTM model
make predict # Generate predictions
make eval # Evaluate and compute metrics
make dashboard # Launch Streamlit dashboardAfter running the pipeline, launch the interactive dashboard:
make dashboard
# or
streamlit run src/viz/dashboard.pyOpen your browser to http://localhost:8501 to explore:
- Time series with anomaly highlights
- LSTM anomaly probabilities
- Markov smoothed posteriors
- Feature correlations and VIX
- Performance metrics
make test # Run all tests with coverage
make lint # Run linters (flake8, mypy)
make format # Format code (black, isort)Symbols: SPY (S&P 500), XLF (Financials), XLK (Technology), VNQ (Real Estate)
Period: 2010-01-01 to 2024-12-31
Features:
- Daily returns and log returns
- Rolling volatility (20-day window)
- Rolling correlation with SPY (60-day window)
- Z-scores of correlation and volatility
- VIX level and delta
Anomalies are labeled when:
- Rolling correlation drops below threshold (< 0.1)
- AND correlation change is steep (Ξcorr < -0.3 within 10 days)
Labels persist for 5 days to mark "breakdown episodes."
Architecture:
- Input: 8 features
- LSTM: 1 layer, 64 hidden units
- Output: sigmoid(logit) β P(anomaly)
Training:
- Loss: BCEWithLogitsLoss with pos_weight=5.0 (class imbalance)
- Optimizer: Adam (lr=0.001)
- Early stopping: patience=10 epochs on validation PR-AUC
States: Normal (N), Anomalous (A)
Transition Matrix (default):
N A
N 0.97 0.03
A 0.15 0.85
How it works:
- Takes LSTM probabilities
p_anom_tas observations - Performs forward update:
prior_t = posterior_{t-1} @ T - Computes posterior:
post_t β prior_t * P(obs_t | state) - Flags anomaly if
P(A) > 0.7for 3+ consecutive steps
Benefits: Reduces false positives by enforcing temporal persistence.
Metrics (both point-level and event-level):
- Precision, Recall, F1 Score
- ROC-AUC
- PR-AUC (Precision-Recall Area Under Curve)
Outputs:
artifacts/metrics.json: Computed metricsartifacts/plots/: ROC curves, PR curves, confusion matrices, time series
All parameters are in config.yaml:
data:
symbols: [SPY, XLF, XLK, VNQ]
start_date: "2010-01-01"
end_date: "2024-12-31"
features:
rolling_window: 60 # correlation window
labels:
corr_threshold: 0.1
delta_threshold: -0.3
model:
hidden_size: 64
learning_rate: 0.001
epochs: 100
markov:
num_states: 2
decision_threshold: 0.7
consecutive_steps: 3Run the entire pipeline in a reproducible Docker container:
# Build image
docker build -t anomaly-detection .
# Run pipeline
docker run -v $(pwd)/data:/app/data \
-v $(pwd)/models:/app/models \
-v $(pwd)/artifacts:/app/artifacts \
anomaly-detection \
make all
# Launch dashboard
docker run -p 8501:8501 \
-v $(pwd)/data:/app/data \
-v $(pwd)/models:/app/models \
-v $(pwd)/artifacts:/app/artifacts \
anomaly-detection \
streamlit run src/viz/dashboard.pyEdit config.yaml:
data:
symbols: [SPY, XLF, XLK, VNQ, QQQ, IWM]Edit config.yaml:
markov:
num_states: 3 # N, A, R (Recovery)Modify config.yaml or override via CLI (future enhancement).
Financial assets often move together (correlation). A correlation breakdown occurs when this relationship suddenly weakens, often signaling:
- Market stress or regime change
- Sector rotation
- Flight to safety (VIX spike)
- Structural market shifts
- Risk monitoring: Flag periods of unusual market behavior
- Portfolio rebalancing: Adjust allocations when correlations break
- Event detection: Identify crisis periods (COVID-19, 2008 crash, etc.)
- Add computation in
src/data/features.py - Update SQL schema in
sql/schema.sql - Retrain model:
make train - Add tests in
tests/test_features.py
- Create module in
src/models/ - Update training pipeline in
src/pipelines/train.py - Add tests in
tests/
- β Audit repo: list files, note issues, TODOs
- β Set up tooling: .gitignore, requirements.txt, pre-commit, Makefile, CI
- β Restructure project with proper src/ layout
- β Create utility modules (config, logging, seed, io)
- β Data ingestion (prices + VIX) β SQL with DuckDB
- β Feature engineering (rolling corr, vol, VIX merges, z-scores)
- β Labeling (correlation breakdown rules)
- β LSTM model (PyTorch) - train & save
- β Markov smoother (T estimation + forward update + decision)
- β Prediction pipeline β SQL predictions
- β Evaluation (metrics: P/R/F1, ROC-AUC, PR-AUC; write F1)
- β Dashboard (Streamlit) with visualizations
- β SQL schema and feature views
- β Tests (unit + e2e) and fix failures
- β Docker setup for reproducibility
- β Docs (README with usage, diagrams)
- β GitHub Actions CI
Major Upgrade - Complete Rewrite
- β¨ LSTM Model: Replaced autoencoder with PyTorch LSTM
- β¨ Markov Smoother: Added HMM-lite temporal smoothing (2-state)
- β¨ DuckDB Pipeline: Complete SQL pipeline for data management
- β¨ Streamlit Dashboard: Interactive visualization dashboard
- β¨ Comprehensive Testing: Unit tests + e2e tests + CI/CD
- β¨ Production Ready: Docker, pre-commit hooks, linting, type hints
- π§ Improved Features: Added VIX delta, z-scores, rolling windows
- π§ Better Labeling: Correlation breakdown with persistence
- π§ Reproducibility: Fixed seeds, config-driven, documented
- π Documentation: Complete README with architecture diagrams
- Basic autoencoder for anomaly detection
- Simple data loading with yfinance
- TensorFlow/Keras implementation
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
Before submitting:
- Run tests:
make test - Format code:
make format - Check linting:
make lint
This project is licensed under the MIT License - see the LICENSE file for details.
Author: James Olaitan
GitHub: @jamesolaitan
- Data source: Yahoo Finance via
yfinance - Frameworks: PyTorch, DuckDB, Streamlit, scikit-learn
- Inspiration: Financial time series analysis and anomaly detection research
β If you find this project useful, please consider giving it a star!