Skip to content

About

Auditable multi-agent market regime & risk committee copilot powered by regimelab and LangGraph.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

regime-desk

CI Python 3.12+

Auditable Multi-Agent Market Regime & Risk Committee Copilot combining strict point-in-time (PIT) quantitative ML (regimelab) with a LangGraph state machine. Every allocation memo is grounded in bi-temporal policy RAG and verified by a $0 deterministic Python Risk Auditor before release.


Business Problem

In institutional Asset Management and Market Risk Committees, asset allocation recommendations cannot rely on unconstrained LLM prose:

  • Look-ahead bias: pulling model fits, policy amendments, or historical decisions from after asof_date invalidates governance backtests.
  • Hallucinated metrics & sign flips: confusing VIX term-structure backwardation (-0.072) with contango (+0.072) or inventing tail-risk VaR breaches risk limits.
  • Unpriced token burn: running a frontier reasoning model on routine status checks wastes latency and budget.

regime-desk solves this by keeping all quantitative inference inside regimelab (deterministic, cached, read-only tools) and wrapping three bounded LangGraph agents behind a $0 deterministic Python Risk Auditor that catches numeric hallucinations, policy limit breaches, and PIT violations before any memo leaves the desk.


Architecture (8-Node LangGraph + Bounded Agents)

flowchart TD
    START((Request)) --> SUP["1. supervisor_router (Deterministic, Cost-Aware)"]
    SUP -->|"New asof / portfolio"| QA["2. quant_analyst (Agent 1: regimelab Tools + Tier Routing)"]
    SUP -->|"Same thread_id follow_up"| RAG["3. policy_rag (Hybrid BM25 + TF-IDF + RRF, PIT Filter)"]
    QA -->|"intent == telemetry_only"| FIN["8. commit_and_finalize (Redact + Episodic Memory)"]
    QA -->|"Committee / Stress Review"| RAG
    RAG --> STRAT["4. portfolio_strategist (Agent 2: Structured CommitteeMemo)"]
    STRAT --> AUD["5. risk_auditor (Deterministic Python Gate, 0 USD)"]
    AUD -->|"Retryable fail & budget left"| STRAT
    AUD -->|"Persistent fail / hard_block / budget hit"| FB["6. safe_fallback (Clamped regimelab Weights)"]
    AUD -->|"PASS + research_brief"| EDIT["7. editorial_brief_agent (Agent 3: POL-EDIT-001)"]
    AUD -->|"PASS + committee_memo"| FIN
    FB --> FIN
    EDIT --> FIN
    FIN --> OUT((FinalCommitteeResponse))

    CKPT[("SqliteSaver (pickle_fallback=False)")] -.-> SUP
    CKPT -.-> FIN
    MEM[("EpisodicMemoryStore (asof_date < current_asof)")] -.-> SUP
    MEM -.-> FIN
Loading

Core Capabilities

  • Clean Quantitative Separation: regimelab>=0.5.1 exposes three cached, read-only tools (get_regime_telemetry, compare_regime_models, simulate_allocation_stress) over deterministic synthetic and Parquet outage/correlation panels (plus opt-in live Yahoo Finance).
  • Bi-Temporal Hybrid RAG: BM25Okapi + L2 TF-IDF cosine + RRF (Protocol VectorEncoder), filtered to effective_date <= asof_date < superseded_date (blocking PIT_SUPERSEDED_POLICY_LEAK), with prompt-injection sanitization and <untrusted_policy_excerpt> isolation.
  • Zero-Token Verification Gate (I1–I8 + Editorial): enforces PIT causality, universe limits (POL-RISK-001/002, POL-CORR-001, POL-DATA-001, POL-MOD-001), exact CitedClaim grounding, adaptive rounding + SIGN_CONTRADICTION checks, and abstention rules.
  • Cost-Aware Routing & Memory: routes calm regimes to gemini-3.5-flash-lite and escalates stress, staleness, or disagreement to gemini-4-hydrogen; persists thread state in SqliteSaver (follow_up reuses quant_bundle) and decisions in EpisodicMemoryStore.

Quickstart (100% Offline, Zero API Keys)

# 1. Install environment with official google-genai SDK extra
uv sync --extra llm

# 2. Run multi-scenario CLI showcase (crisis + multi-turn follow-up + correlation break)
uv run --extra llm regime-desk demo

# 3. Run offline evaluation suite (Real RAG + Deterministic Auditor + Contract E2E)
uv run --extra llm regime-desk eval

FastAPI Service & Live Gemini Mode

# Start REST API with interactive Swagger docs at http://127.0.0.1:8000/docs
uv run --extra llm uvicorn regime_desk.api:app --host 127.0.0.1 --port 8000

Endpoints:

  • GET /health: readiness & active provider metadata (zero secret exposure).
  • POST /v1/analyze: validated committee memo or research_brief execution with thread_id support.
  • GET /v1/threads/{thread_id}: inspect persisted SqliteSaver checkpoint state (200 / 404).

To enable live Gemini calls (via official google-genai SDK, accounting for prompt_token_count, candidates_token_count, and thoughts_token_count):

cp .env.example .env   # Set REGIME_DESK_LLM_PROVIDER=gemini and GEMINI_API_KEY=...
uv run --extra llm regime-desk analyze --asof 2017-08-02 --query "Crisis SPY limit review" --live
uv run --extra llm regime-desk eval --live

Optional live Yahoo Finance market telemetry (--profile yahoo uses a 6-year trailing window ending at --asof; pytest, evals, and CI remain 100% deterministic offline):

# Optional: raise REGIME_DESK_MAX_COST_USD=0.10 to allow frontier self-repair + research_brief
uv run --extra llm regime-desk analyze --asof 2026-11-29 --profile yahoo --format research_brief --live
Sample live run output (2026-11-29, Yahoo Finance + Gemini, PASS 30/30 grounded)
  • Resolved session: 2026-11-27 (asof_not_in_panel disclosed cleanly) | Regime: RISK_OFF | Action: rebalance
  • Target weights: SPY 0% / TLT 30% / GLD 20% / CASH 50% (cited POL-RISK-002#c1, POL-DATA-001#c1, POL-MOD-001#c2, POL-EDIT-001#c1/#c2; repealed POL-RISK-001 excluded)
  • Auditor & Cost: PASS (30/30 grounded numbers, 5 citations) | Cost: $0.0403 (13,706 tokens)

Institutional Market Research Note: RISK_OFF Regime Rebalance

Under the RISK_OFF regime assessment for session date 2026-11-27, primary HMM telemetry indicates a confidence of 1.0000, risk_off_mass of 1.0000, and normalised_entropy of 0.0007. Supporting feature telemetry shows absorption_delta at 1.0307, vix_term_spread at 0.0004, defensive_correlation at 0.1775, and spy_tlt_corr at -0.2026. Cross-model comparison notes a disagreement with GMM which reports NEUTRAL_TRANSITION. The committee recommends rebalancing portfolio weights to SPY 0.00, TLT 0.30, GLD 0.20, and CASH 0.50.

Institutional Research Note Disclaimer: Regime classifications and model diagnostics are model-based research indicators rather than personalized investment advice and do not guarantee future performance.


Evaluation & Benchmarks

Evaluation strictly separates real deterministic component metrics (HybridPolicyRetriever and Python risk_auditor), offline contract checks (ScriptedMockLLM, saved in evals/offline_report.json), and live Gemini runs (GeminiLLMClient). Mock responses are never presented as LLM accuracy.

1. Real PIT Hybrid RAG Benchmark (Offline Policy Corpus, 15 Queries)

Mode Recall@3 MRR Abstention Acc. PIT Leakage
bm25 100.0% 1.0000 93.3% 0.0%
vector 100.0% 1.0000 100.0% 0.0%
hybrid 100.0% 1.0000 100.0% 0.0%

2. Real Deterministic Risk Auditor Benchmark ($0 LLM Cost)

Metric Measured Result
Hallucination & Breach Catch Rate 100.0% (6/6 fault injections caught)
False Positive Rate (Clean Rounded Memos) 0.0% (5 canonical scenarios)
Self-Repair Recovery Rate 100.0% (numeric + fake-citation repairs)
Safe Fallback Activation Rate 100.0% (persistent fault + budget cap)

3. LangGraph E2E Routing & Contract Verification (ScriptedMockLLM)

Note: E2E rows below verify deterministic LangGraph state transitions, budget caps, and schema/policy invariants using ScriptedMockLLM (not live LLM reasoning quality).

Metric Measured Result
Golden Cases Passed 12/12 (100.0%)
Tier Routing Accuracy (light vs frontier) 100.0%
Simulated Cost Savings vs All-Frontier 27.0%
Latency p50 / p95 (ms) 220.0 ms / 8,874.7 ms

Methodological Notes:

  • The 100.0% Recall@3 across the 8 curated risk policy documents acts as a CI regression floor rather than a claim about large-corpus retrieval; the critical production invariants verified here are 0.0% PIT leakage across the 2019-01-01 policy amendment cut and 100.0% abstention accuracy in hybrid mode (where bm25 alone false-accepted an out-of-scope leverage query at 93.3%).
  • Latency splits cleanly between warm cached turns (p50 = 220.0 ms) and cold walk-forward Hamilton Markov-switching regression fits inside compare_regime_models (p95 = 8,874.7 ms), which are cached per (dataset_profile, classifier, train_end) fold.

4. Live Gemini Benchmark (regime-desk eval --live)

Executed live under the default $0.05 cost budget (REGIME_DESK_MAX_COST_USD=0.05) against gemini-3.5-flash-lite (light) and gemini-4-hydrogen (frontier) across all 12 golden cases (including thoughts_token_count cost accounting; full trace in evals/live_benchmark.json):

Metric Measured Live Result
Cases Evaluated 12 (11 passed cleanly, 1 routed to safe_fallback)
Tier Routing Accuracy (light vs frontier) 12/12 (100.0%)
Direct LLM Policy Compliance (Pre-Fallback) 91.7% (11/12)
Effective Output Policy Compliance (Post-Fallback) 100.0% (12/12)
Numeric Grounding (Approved Memos / All Checked) 100.0% (219/219) / 98.8% (250/253)
Avg Cost / Run (USD, incl. thoughts_tokens) $0.032994
Cost Savings vs All-Frontier Routing 19.1%
Latency p50 / p95 (ms) 23,976.9 ms / 42,666.3 ms
Live Self-Repairs / Safe Fallbacks 2 / 1
  • Guardrails verified live: case_09_adversarial_100_spy was intercepted into deterministic safe_fallback weights (CLAIM_VALUE_MISMATCH + BUDGET_EXCEEDED), and case_03_crisis_risk_off_2017 auto-repaired cleanly on retry 2.
  • Exact 250/253 breakdown: all 3 unverified claims belong exclusively to case_09_adversarial_100_spy (31/34 checked figures flagged with CLAIM_VALUE_MISMATCH before BUDGET_EXCEEDED routed to safe_fallback); across the 11 approved memos, numeric grounding was 219/219 (100.0%).
  • Latency profile (p50 ~24.0 s / p95 ~42.7 s): driven by gemini-4-hydrogen reasoning thoughts_tokens on escalated frontier cases (light tier cases finished in 3.6 s–7.6 s), which is an expected trade-off for an asynchronous Market Risk Committee workflow.

Design Decisions & Trade-Offs

  • 3 bounded role-specialized agents vs. 6 unconstrained conversational agents: Only quant_analyst (tool selection), portfolio_strategist (structured synthesis), and conditional editorial_brief_agent (POL-EDIT-001) call LLMs. Routing, PIT policy retrieval, risk verification, and safe fallback stay deterministic Python to maximize auditability and keep latency and token cost predictable.
  • Read-only Python adapters over regimelab vs. LLM code generation: Rather than executing LLM-generated backtest code in a sandbox, quant_analyst invokes typed, cached, side-effect-free regimelab adapters with pinned asof_date and dataset_profile, eliminating look-ahead leakage and code-injection risk.
  • BM25 + TF-IDF cosine + RRF behind Protocol VectorEncoder vs. shipping torch/sentence-transformers: Keeps container builds fast and CI dependencies lean (no multi-GB GPU/PyTorch stack) for crisp technical banking policy terms (SPY, ^VIX3M, POL-RISK-002, defensive_correlation), while leaving a clean Protocol swap-in point for neural embeddings if corpus scale grows.
  • Intentional Non-Goals: No custom React frontend (FastAPI Swagger + Typer CLI focus), no autonomous broker execution, and enterprise perimeter controls (OAuth2/OIDC, mTLS, distributed OpenTelemetry) are delegated to platform ingress/sidecars.

Security & Governance

See SECURITY.md for the complete threat model covering indirect prompt injection, numeric hallucination & limit enforcement, secret redaction (SecretStr, redact_secrets(), CI gitleaks), PIT causality checks, checkpoint allowlisting (pickle_fallback=False), and non-root containerization (Dockerfile).

About

Auditable multi-agent market regime & risk committee copilot powered by regimelab and LangGraph.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages