How mega-slaking/systematic_trading_model works
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: pipeline.py Decision pipeline · engine.py Backtest engine · main.py FastAPI analytics · price_signal_engine.py Price & macro signals
Components 20
Data & Risk
- SQLite store · Prices, macro inputs, risk outputs, and completed backtests.
- ETF & macro ingestion
src/api_fetch/fetch_etf_prices.py - Macro features · Derived macro fields are computed from stored raw data.
src/signals_macro/macro_features.py - Price & macro signals
src/signals_price/price_signal_engine.py - Volatility & covariance · Point-in-time sizing and scenario-cached covariance inputs.
src/volatility/feature_surface.py - Optional C++ covariance kernel
src/cpp/covariance.cpp
Strategy & Simulation
- Strategy registry · Provides presets, live selection, and dashboard override.
src/strategy/config.py - Decision pipeline · Transforms typed decisions using only prior-date information.
src/decision/pipeline.py - TLT tracker · Current deterministic conviction path.
src/strategy/tlt_tracker.py - Constraints
src/decision/constraint_engine.py - Engine contexts · Unifies batch backtest and live operation.
src/context/protocol.py - Backtest engine · Captures traces and persists only successful runs.
src/backtest/engine.py - Execution & accounting · Converts targets to ordered trades and daily valuation.
src/execution/rebalance_v2.py - Batch backtest runner
run_backtest.py - Live decision runner
main.py
API & Jobs
- FastAPI analytics · Router-service-schema analytics over persisted results.
api/main.py - Backtest job service · Controlled UI write path with progress, cancellation, and cache refresh.
api/services/jobs.py - Backtest worker
api/backtest_worker.py
Frontend
- React/Vite SPA · Pages use API hooks and URL-synced selections.
frontend/src/App.tsx - Frozen Streamlit UI
streamlit/app.py
Connections 22
- 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