Bayesian system-dynamics pipeline for market regime classification
Project description
Financial Dynamics Model
Bayesian System-Dynamics Pipeline for Market Regime Classification
Transforms raw OHLCV data into explainable regime probabilities for quantitative trading and risk management.
Live Demo | Documentation | Install | API Reference
English | 中文 | 日本語 | 한국어 | Español | Português
| 80.6% Accuracy |
229 Unit Tests |
5 Pipeline Phases |
4 Market Regimes |
12 3D Viz Layers |
Why Financial Dynamics?
Most regime detection tools are either black-box neural networks or simplistic threshold rules. Financial Dynamics sits in the sweet spot: fully transparent Bayesian inference with production-grade engineering.
Every probability is traceable. Every transition is explainable. Every signal has a clear mathematical origin.
┌─────────────────────────────────┐
│ Financial Dynamics Model │
└────────────────┬────────────────┘
│
┌───────────────────────────┼───────────────────────────┐
│ │ │
┌────────▼────────┐ ┌────────▼────────┐ ┌────────▼────────┐
│ Python API │ │ Streamlit App │ │ CLI Tools │
│ │ │ │ │ │
│ pipeline.run() │ │ Interactive 3D │ │ run_pipeline │
│ pipeline.step() │ │ Live Charts │ │ run_backtest │
│ pipeline.fore- │ │ Signal Feed │ │ run_calibrate │
│ cast() │ │ Forecasts │ │ run_benchmark │
└─────────────────┘ └──────────────────┘ └─────────────────┘
Installation
# Core library
pip install financial-dynamics
# With live data (yfinance)
pip install financial-dynamics[data]
# Full dashboard (Streamlit + Plotly + yfinance)
pip install financial-dynamics[dashboard]
# Everything including dev tools
pip install financial-dynamics[all]
Or from source:
git clone https://github.com/jmiaie/financial-dynamics-model.git
cd financial-dynamics-model
pip install -e ".[all]"
Quick Start
Interactive Dashboard
streamlit run app.py
Load any ticker (SPY, QQQ, AAPL, BTC-USD) and watch regime classification in real-time. Charts update instantly, forecasts auto-compute, signals fire as regimes shift.
Try it now: financial-dynamics-model.streamlit.app
Python API
from financial_dynamics import FinancialDynamicsPipeline
from financial_dynamics.data_loader import fetch_ohlcv
# Fetch data & run pipeline
df = fetch_ohlcv("SPY", period="1y", interval="1d")
pipeline = FinancialDynamicsPipeline()
results = pipeline.run(df)
# Current regime + confidence
current = results["risk_adjusted_regime"].iloc[-1]
confidence = results["post_prob_CALM_TREND"].iloc[-1]
print(f"Regime: {current} ({confidence:.1%} confidence)")
# Forecast next 10 bars
forecast = pipeline.forecast(horizon=10)
print(f"Expected duration: {forecast.expected_duration:.1f} bars")
print(f"Path: {' → '.join(r.name for r in forecast.most_likely_path[:5])}")
CLI
python scripts/run_pipeline.py --symbol SPY --period 1y --interval 1d
python scripts/run_backtest.py --data historical.csv --labels regimes.csv --rolling
python scripts/run_calibration.py --output calibrated.yaml
python scripts/run_benchmark.py --config config/default.yaml
Pipeline Architecture
╔══════════════════════════════════════════════════════════════╗
║ RAW OHLCV DATA ║
╚══════════════════════════╦═══════════════════════════════════╝
▼
┌──────────────────────────────────────────────────────────────┐
│ PHASE 0 │ Feature Engineering │
│ │ 5D normalized: vol · trend · drawdown · corr · shock │
└──────────────────────────┬───────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ PHASE 1 │ Centroid Classification │
│ │ P(Sᵢ|Xₜ) = exp(−‖Xₜ − Cᵢ‖ / τ) / Z │
└──────────────────────────┬───────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ PHASE 2 │ Bayesian Markov Transitions │
│ │ P_post = P_centroid × T[prev, :] / Z │
│ │ Dirichlet prior · online learning │
└──────────────────────────┬───────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ PHASE 3 │ Temporal Stabilization │
│ │ Hysteresis · persistence · majority vote │
└──────────────────────────┬───────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ PHASE 4 │ Risk Conditioning │
│ │ Risk-Off confirmation · overextension · chop loop │
└──────────────────────────┬───────────────────────────────────┘
▼
╔══════════════════════════════════════════════════════════════╗
║ REGIME + CONFIDENCE + FORECAST ║
╚══════════════════════════════════════════════════════════════╝
Market Regimes
| Regime | Characteristics | Feature Signature | Trading Signal |
|---|---|---|---|
|
Calm Trend Low risk, directional |
Low volatility, strong uptrend, minimal drawdown, stable correlations | [0.1, 0.8, 0.05, 0.1, 0.1] |
Long accumulation |
|
Volatile Trend High energy, directional |
High volatility, directional momentum, recoveries from dips | [0.8, 0.7, 0.3, 0.5, 0.6] |
Trend-following |
|
Chop Low energy, directionless |
Low volatility, weak trend, mean-reverting, range-bound | [0.4, 0.2, 0.15, 0.3, 0.3] |
Range trading |
|
Risk-Off High risk, defensive |
High volatility, deep drawdowns, shock clusters, stress contagion | [0.9, 0.3, 0.8, 0.9, 0.9] |
Hedging / defensive |
3D Phase-Space Attractor Field
The interactive 3D visualization projects the 5D feature space onto 3 principal components, revealing the geometric structure of market regimes:
|
Structural Layers
|
Dynamic Layers
|
10 interactive toggles — enable/disable each layer independently. Drag to rotate, scroll to zoom, hover for details.
Configuration
All parameters in config/default.yaml:
features:
volatility_span: 20 # EWMA lookback
trend_window: 14 # Linear regression window
drawdown_window: 60 # Rolling peak window
normalization_method: zscore # zscore | minmax
regimes:
temperature: 1.0 # Softmax temperature (lower = sharper)
transitions:
prior_strength: 10.0 # Dirichlet prior concentration
learning_rate: 0.05 # Bayesian update speed
stabilization:
hysteresis_threshold: 0.15 # Min probability gap to flip
min_persistence_bars: 5 # Bars before confirming change
majority_vote_window: 10 # Rolling vote window
risk:
riskoff_confirmation_count: 3 # Stressors needed for Risk-Off
overextension_decay: 0.02 # Regime fatigue rate
Testing
pytest tests/ -v # All 229 tests
pytest tests/test_phase0_features.py -v # Feature engineering
pytest tests/test_pipeline_integration.py # End-to-end
pytest tests/test_stress.py # Numerical stability
pytest tests/test_visualization.py # 3D rendering
Test Coverage by Module
| Module | Tests | Coverage |
|---|---|---|
| Phase 0 — Features | 35 | Core pipeline |
| Phase 1 — Regimes | 20 | Core pipeline |
| Phase 2 — Transitions | 25 | Core pipeline |
| Phase 3 — Stabilization | 30 | Core pipeline |
| Phase 4 — Risk | 22 | Core pipeline |
| Pipeline Integration | 18 | End-to-end |
| Visualization | 16 | 2D + 3D |
| Signals | 12 | Detection |
| Stress / Numerical | 20 | Edge cases |
| Calibration + Others | 31 | Tooling |
Project Structure
src/financial_dynamics/
├── pipeline.py # Orchestrator (batch + streaming)
├── types.py # Regime, FeatureVector, BarState
├── config.py # Typed config + YAML loader
├── phase0_features/ # EWMA vol, trend, drawdown, corr, shock
├── phase1_regimes/ # Softmax centroid classification
├── phase2_transitions/ # Dirichlet-Bayesian Markov learning
├── phase3_stabilization/ # Hysteresis, persistence, majority vote
├── phase4_risk/ # Risk-Off confirmation, overextension
├── visualization/ # 2D/3D phase-space, dashboard, trajectory
├── calibration/ # Centroid fitting, hyperparameter tuning
├── backtesting/ # Rolling-window evaluation
├── benchmarks/ # Baseline classifiers
├── forecasting/ # k-step regime forecasts
├── signals/ # Regime change / risk detection
├── data_loader.py # yfinance integration
└── persistence/ # State serialization
app.py # Streamlit interactive dashboard
config/default.yaml # All tunable parameters
Use Cases
|
Hedge Funds & Prop Desks
Quant Researchers
|
Risk Management
Fintech & Robo-Advisors
|
Deployment
Docker
docker build -t financial-dynamics .
docker run -d -p 8501:8501 --restart unless-stopped financial-dynamics
Custom Domain (fdm.micapai.com)
See DEPLOYMENT_GUIDE.md for Porkbun DNS + Streamlit Cloud setup.
Documentation
| Resource | Description |
|---|---|
| DEPLOYMENT_GUIDE.md | Streamlit Cloud, Docker, custom domain |
| STREAMLIT_QUICK_START.md | Run the dashboard locally |
| config/default.yaml | All tunable parameters |
scripts/run_pipeline.py --help |
CLI reference |
Contributing
Contributions welcome. Please open an issue first to discuss major changes.
git clone https://github.com/jmiaie/financial-dynamics-model.git
cd financial-dynamics-model
pip install -e ".[all]"
pytest tests/ -v
License
Built by Micap.AI
Python · NumPy · Pandas · SciPy · scikit-learn · Streamlit · Plotly · yfinance · Bayesian inference · Markov chains
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file financial_dynamics-1.0.0.tar.gz.
File metadata
- Download URL: financial_dynamics-1.0.0.tar.gz
- Upload date:
- Size: 40.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c6f8d8895c55f93d801148ab01ad4c744c41c3e5dc6c8f702c6af8e8954fcf1f
|
|
| MD5 |
7215ec90d710cf66151dd14355029a31
|
|
| BLAKE2b-256 |
a131fa845af14d7a370854651e9194ab2acffc287f79d995fe66785408e6297f
|
File details
Details for the file financial_dynamics-1.0.0-py3-none-any.whl.
File metadata
- Download URL: financial_dynamics-1.0.0-py3-none-any.whl
- Upload date:
- Size: 61.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0cdab69657bf0661489495a429babb7586fcd187e0bbd8d2c8fade08b5b170df
|
|
| MD5 |
7781961d8dfe351f78e63246c9449df5
|
|
| BLAKE2b-256 |
87e5a2c958c1119b80569ce06affe19021aa1c2cd3f8ad9a77bf8266ee20887b
|