# mega-slaking/systematic_trading_model architecture

> Architecture diagram of the GitHub repository mega-slaking/systematic_trading_model, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-16). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/mega-slaking/systematic_trading_model
- Repository: https://github.com/mega-slaking/systematic_trading_model

## Overview

#### Purpose and Entrypoints
A systematic trading research platform for configurable ETF strategies, centered on TLT/AGG/SHY rotation. It produces lookahead-safe decisions, simulates execution and accounting, persists results to SQLite, and exposes analytics through FastAPI and a React SPA.

Primary entrypoints:
- Batch registry backtests: `run_backtest.py`
- Live decision run: `main.py`
- API server: `api/main.py`
- React SPA bootstrap: `frontend/src/main.tsx`
- Retired/frozen alternative UI: `streamlit/app.py`

#### Strategy and Decision Pipeline
The strategy registry provides immutable `StrategyConfig` presets, including the selected live strategy and persisted dashboard override. Per date, the engine consumes only prior information and transforms a typed `Decision` through allocation, risk sizing, and constraints.
- `src/strategy/config.py`
- `src/strategy/presets.py`
- `src/engine/run.py`
- `src/decision/pipeline.py`
- `src/decision/models.py`

The current conviction path uses the deterministic, replayed TLT tracker state machine; legacy allocation remains available for controlled comparisons.
- `src/strategy/tlt_tracker.py`
- `src/legacy/base_allocator_engine.py`
- `src/decision/constraint_engine.py`

#### Data, Signals, and Risk Features
SQLite is the durable boundary for ETF prices, raw macro data, volatility features, and backtest outputs. Ingestion supports ETF and FRED macro fetches; macro derivations are calculated at runtime rather than persisted as derived fields.
- `src/storage/db_reader.py`
- `src/storage/db_writer.py`
- `src/api_fetch/fetch_etf_prices.py`
- `src/api_fetch/fetch_macro_data.py`
- `src/signals_macro/macro_features.py`

Price and macro signals feed strategy decisions. Volatility and covariance are separate risk inputs: volatility supports point-in-time sizing plus reusable lagged diagnostic surfaces; covariance uses precomputed returns and scenario-shared caching, with an optional pybind11 C++ kernel.
- `src/signals_price/price_signal_engine.py`
- `src/signals_macro/macro_signal_engine.py`
- `src/volatility/feature_surface.py`
- `src/covariance/returns_view.py`
- `src/cpp/covariance.cpp`

#### Backtest, Execution, and Accounting
`run_backtests()` iterates selected registry strategies. The backtest context provides prices, macro data, cached risk views, and trace capture; the engine emits target weights, execution converts them into ordered trades, and valuation/accounting derive daily NAV and metrics. Results, decision traces, regime traces, and volatility surfaces are persisted only after successful completion.
- `run_backtest.py`
- `src/backtest/engine.py`
- `src/backtest/portfolio.py`
- `src/execution/rebalance_v2.py`
- `src/accounting/valuation.py`
- `src/accounting/tearsheet_builder.py`

The `EngineContext` protocol is the boundary shared by batch backtest and live operation.
- `src/context/protocol.py`
- `src/context/backtest.py`
- `src/context/live.py`

#### API and Job Boundary
FastAPI provides `/api/v1` analytics over persisted SQLite data, with router → service → schema separation and explicit DataFrame/dataclass serialization to handle dates and non-finite values.
- `api/main.py`
- `api/routers/backtest_results.py`
- `api/services/tearsheet.py`
- `api/serialization/frames.py`

Backtests triggered from the UI are the controlled write path: a single subprocess job worker serializes SQLite writers, reports stdout progress, supports cancellation, and refreshes cached analytics after completion.
- `api/routers/jobs.py`
- `api/services/jobs.py`
- `api/backtest_worker.py`

#### Frontend and External Runtimes
The React/Vite SPA uses typed API models, TanStack Query, Plotly/Recharts visualization, URL-synced selections, and client-side themes. Pages consume API hooks rather than engine code directly.
- `frontend/src/App.tsx`
- `frontend/src/api/client.ts`
- `frontend/src/api/hooks.ts`
- `frontend/src/pages/StrategiesPage.tsx`
- `frontend/src/pages/VolatilityPage.tsx`

Material runtime dependencies are Python/FastAPI/Uvicorn, SQLite, React/Vite/TypeScript, Plotly, optional `arch` for GARCH, FRED for macro ingestion, and optional C++/pybind11 covariance acceleration.

Main entry points: [`src/decision/pipeline.py`](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/decision/pipeline.py) (Decision pipeline), [`src/backtest/engine.py`](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/backtest/engine.py) (Backtest engine), [`api/main.py`](https://github.com/mega-slaking/systematic_trading_model/blob/main/api/main.py) (FastAPI analytics), [`src/signals_price/price_signal_engine.py`](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/signals_price/price_signal_engine.py) (Price & macro signals)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_data["Data &amp; Risk"]
  node_sqlite[("SQLite store<br/>durable data store")]
  node_ingestion["ETF &amp; macro ingestion<br/>data fetchers"]
  node_macro_features["Macro features<br/>runtime derivations<br/>[macro_features.py]"]
  node_market_signals["Price &amp; macro signals<br/>signal engines"]
  node_risk_views["Volatility &amp; covariance<br/>risk feature views<br/>[feature_surface.py]"]
  node_cpp_covariance{{"Optional C++ covariance kernel<br/>pybind11 accelerator<br/>[covariance.cpp]"}}
end

subgraph group_core["Strategy &amp; Simulation"]
  node_strategy_registry["Strategy registry<br/>immutable strategy configs<br/>[config.py]"]
  node_decision_pipeline["Decision pipeline<br/>allocation and risk sizing<br/>[pipeline.py]"]
  node_tlt_tracker["TLT tracker<br/>replayed state machine<br/>[tlt_tracker.py]"]
  node_constraints["Constraints<br/>constraint engine"]
  node_contexts["Engine contexts<br/>shared protocol and adapters<br/>[protocol.py]"]
  node_backtest_engine["Backtest engine<br/>simulation orchestrator<br/>[engine.py]"]
  node_execution_accounting["Execution &amp; accounting<br/>rebalance, NAV, metrics<br/>[rebalance_v2.py]"]
  node_batch_runner["Batch backtest runner<br/>CLI entrypoint<br/>[run_backtest.py]"]
  node_live_runner["Live decision runner<br/>CLI entrypoint<br/>[main.py]"]
end

subgraph group_api["API &amp; Jobs"]
  node_fastapi["FastAPI analytics<br/>API server<br/>[main.py]"]
  node_job_service["Backtest job service<br/>serialized subprocess jobs<br/>[jobs.py]"]
  node_job_worker["Backtest worker<br/>subprocess worker<br/>[backtest_worker.py]"]
end

subgraph group_ui["Frontend"]
  node_react_spa["React/Vite SPA<br/>typed analytics client<br/>[App.tsx]"]
  node_retired_streamlit["Frozen Streamlit UI<br/>retired alternative UI<br/>[app.py]"]
end

node_ingestion -->|"stores raw prices and macro data"| node_sqlite
node_sqlite -->|"raw macro inputs"| node_macro_features
node_sqlite -->|"price and macro history"| node_market_signals
node_macro_features -->|"runtime features"| node_market_signals
node_sqlite -->|"prices and returns"| node_risk_views
node_cpp_covariance -.->|"optional acceleration"| node_risk_views
node_strategy_registry -->|"selected configuration"| node_decision_pipeline
node_tlt_tracker -->|"conviction state"| node_decision_pipeline
node_market_signals -->|"signals"| node_decision_pipeline
node_risk_views -->|"sizing inputs"| node_decision_pipeline
node_decision_pipeline -->|"candidate decision"| node_constraints
node_contexts -->|"backtest context"| node_backtest_engine
node_constraints -->|"target weights"| node_backtest_engine
node_backtest_engine -->|"daily targets and prices"| node_execution_accounting
node_execution_accounting -->|"NAV, metrics, traces, surfaces"| node_sqlite
node_batch_runner -->|"iterates registry strategies"| node_backtest_engine
node_live_runner -->|"live context"| node_contexts
node_react_spa -->|"typed analytics requests"| node_fastapi
node_fastapi -->|"reads persisted analytics"| node_sqlite
node_fastapi -->|"submits UI backtests"| node_job_service
node_job_service -->|"single serialized subprocess"| node_job_worker
node_job_worker -->|"runs backtest"| node_backtest_engine

click node_ingestion "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/api_fetch/fetch_etf_prices.py"
click node_macro_features "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/signals_macro/macro_features.py"
click node_market_signals "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/signals_price/price_signal_engine.py"
click node_risk_views "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/volatility/feature_surface.py"
click node_cpp_covariance "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/cpp/covariance.cpp"
click node_strategy_registry "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/strategy/config.py"
click node_decision_pipeline "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/decision/pipeline.py"
click node_tlt_tracker "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/strategy/tlt_tracker.py"
click node_constraints "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/decision/constraint_engine.py"
click node_contexts "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/context/protocol.py"
click node_backtest_engine "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/backtest/engine.py"
click node_execution_accounting "https://github.com/mega-slaking/systematic_trading_model/blob/main/src/execution/rebalance_v2.py"
click node_batch_runner "https://github.com/mega-slaking/systematic_trading_model/blob/main/run_backtest.py"
click node_live_runner "https://github.com/mega-slaking/systematic_trading_model/blob/main/main.py"
click node_fastapi "https://github.com/mega-slaking/systematic_trading_model/blob/main/api/main.py"
click node_job_service "https://github.com/mega-slaking/systematic_trading_model/blob/main/api/services/jobs.py"
click node_job_worker "https://github.com/mega-slaking/systematic_trading_model/blob/main/api/backtest_worker.py"
click node_react_spa "https://github.com/mega-slaking/systematic_trading_model/blob/main/frontend/src/App.tsx"
click node_retired_streamlit "https://github.com/mega-slaking/systematic_trading_model/blob/main/streamlit/app.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_sqlite,node_ingestion,node_macro_features,node_market_signals,node_risk_views,node_cpp_covariance toneBlue
class node_strategy_registry,node_decision_pipeline,node_tlt_tracker,node_constraints,node_contexts,node_backtest_engine,node_execution_accounting,node_batch_runner,node_live_runner toneAmber
class node_fastapi,node_job_service,node_job_worker toneMint
class node_react_spa,node_retired_streamlit toneRose
```

## Components

### Data & Risk

- **SQLite store**: durable data store · Prices, macro inputs, risk outputs, and completed backtests.
- [ETF & macro ingestion](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/api_fetch/fetch_etf_prices.py): data fetchers · `src/api_fetch/fetch_etf_prices.py`
- [Macro features](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/signals_macro/macro_features.py): runtime derivations · Derived macro fields are computed from stored raw data. · `src/signals_macro/macro_features.py`
- [Price & macro signals](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/signals_price/price_signal_engine.py): signal engines · `src/signals_price/price_signal_engine.py`
- [Volatility & covariance](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/volatility/feature_surface.py): risk feature views · Point-in-time sizing and scenario-cached covariance inputs. · `src/volatility/feature_surface.py`
- [Optional C++ covariance kernel](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/cpp/covariance.cpp): pybind11 accelerator · `src/cpp/covariance.cpp`

### Strategy & Simulation

- [Strategy registry](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/strategy/config.py): immutable strategy configs · Provides presets, live selection, and dashboard override. · `src/strategy/config.py`
- [Decision pipeline](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/decision/pipeline.py): allocation and risk sizing · Transforms typed decisions using only prior-date information. · `src/decision/pipeline.py`
- [TLT tracker](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/strategy/tlt_tracker.py): replayed state machine · Current deterministic conviction path. · `src/strategy/tlt_tracker.py`
- [Constraints](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/decision/constraint_engine.py): constraint engine · `src/decision/constraint_engine.py`
- [Engine contexts](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/context/protocol.py): shared protocol and adapters · Unifies batch backtest and live operation. · `src/context/protocol.py`
- [Backtest engine](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/backtest/engine.py): simulation orchestrator · Captures traces and persists only successful runs. · `src/backtest/engine.py`
- [Execution & accounting](https://github.com/mega-slaking/systematic_trading_model/blob/main/src/execution/rebalance_v2.py): rebalance, NAV, metrics · Converts targets to ordered trades and daily valuation. · `src/execution/rebalance_v2.py`
- [Batch backtest runner](https://github.com/mega-slaking/systematic_trading_model/blob/main/run_backtest.py): CLI entrypoint · `run_backtest.py`
- [Live decision runner](https://github.com/mega-slaking/systematic_trading_model/blob/main/main.py): CLI entrypoint · `main.py`

### API & Jobs

- [FastAPI analytics](https://github.com/mega-slaking/systematic_trading_model/blob/main/api/main.py): API server · Router-service-schema analytics over persisted results. · `api/main.py`
- [Backtest job service](https://github.com/mega-slaking/systematic_trading_model/blob/main/api/services/jobs.py): serialized subprocess jobs · Controlled UI write path with progress, cancellation, and cache refresh. · `api/services/jobs.py`
- [Backtest worker](https://github.com/mega-slaking/systematic_trading_model/blob/main/api/backtest_worker.py): subprocess worker · `api/backtest_worker.py`

### Frontend

- [React/Vite SPA](https://github.com/mega-slaking/systematic_trading_model/blob/main/frontend/src/App.tsx): typed analytics client · Pages use API hooks and URL-synced selections. · `frontend/src/App.tsx`
- [Frozen Streamlit UI](https://github.com/mega-slaking/systematic_trading_model/blob/main/streamlit/app.py): retired alternative UI · `streamlit/app.py`

## Connections

- ETF & macro ingestion → SQLite store: stores raw prices and macro data
- SQLite store → Macro features: raw macro inputs
- SQLite store → Price & macro signals: price and macro history
- Macro features → Price & macro signals: runtime features
- SQLite store → Volatility & covariance: prices and returns
- Optional C++ covariance kernel → Volatility & covariance: optional acceleration
- Strategy registry → Decision pipeline: selected configuration
- TLT tracker → Decision pipeline: conviction state
- Price & macro signals → Decision pipeline: signals
- Volatility & covariance → Decision pipeline: sizing inputs
- Decision pipeline → Constraints: candidate decision
- Engine contexts → Backtest engine: backtest context
- Constraints → Backtest engine: target weights
- Backtest engine → Execution & accounting: daily targets and prices
- Execution & accounting → SQLite store: NAV, metrics, traces, surfaces
- Batch backtest runner → Backtest engine: iterates registry strategies
- Live decision runner → Engine contexts: live context
- React/Vite SPA → FastAPI analytics: typed analytics requests
- FastAPI analytics → SQLite store: reads persisted analytics
- FastAPI analytics → Backtest job service: submits UI backtests
- Backtest job service → Backtest worker: single serialized subprocess
- Backtest worker → Backtest engine: runs backtest
