AgenticAICashEquities

An enterprise-style Agentic AI platform that investigates, analyses and explains cash-equity trading and market behaviour. Ask "Why did our AAPL execution quality deteriorate between 14:00 and 15:00?" and it plans the investigation, pulls orders, fills, market data, order-book depth, venue statistics, technology telemetry and runbooks through MCP, computes every number with deterministic quant analytics, lets specialist agents interpret the evidence, has an independent critic challenge the findings, and writes an auditable report in which every claim points at an evidence record. Python · MCP · LLM · multi-agent harness · policy engine · RAG · FastAPI.

Measured, not claimed

Test suite               212 tests green — 101 unit · 28 integration · 17 MCP (incl. a real stdio round-trip) · 52 agent (22 review regressions) · 10 adversarial · 4 evaluation
Execution evaluation      50 / 50 primary cause correct · 100% ground-truth coverage · 2% false-positive rate (one scenario) · 0 unresolved evidence · 0 narrative number warnings
Research evaluation       21 / 21 verdicts correct (Stage 2) · 100% expected-flag coverage · 0 unresolved evidence · 0 narrative number warnings
Investigation            ≈0.9 s end to end with the deterministic LLM: plan → 15 tool calls in parallel batches → 5 specialist agents → critic → evidence validation → audited report
Capability surface        8 MCP servers · 37 tools, all read-only except one (paper order staging, HIGH risk, human-approved) · schemas derived from Python signatures · in-process or FastMCP over stdio from one definition
Harness                  11-state machine · 12 agents (8 investigation + 4 research) · policy → approval → retry/timeout → tool → evidence on every call · governance steps the plan cannot drop or reorder · arguments pinned to the task's symbol/signal, dataset and window
Synthetic market          per execution scenario: 14,400 1-second NBBO quotes · ≈22k prints on 5 venues · 1,440 five-level books · 242 orders · ≈435 fills · 1,680 telemetry points; per research dataset: 30-name, 4-year daily universe (1,008 trading days) — both seeded, byte-reproducible
Analytics                60+ pure functions: VWAP · TWAP · Perold IS with opportunity cost · slippage · effective spread · impact · volatility · depth · attribution over 8 causes · (Stage 2) rank-IC signal statistics · event-driven backtest with a cost model · portfolio risk · deterministic research verdict
Knowledge (RAG)          8 runbook/policy documents · 34 chunks · dependency-free hashed TF-IDF · served as DOCUMENT evidence through MCP
Code                     ≈14.4k lines of typed Python in src/ceap (122 files) · ≈4.0k lines of tests · ruff clean · mypy clean · Python 3.12 in CI, 3.11+ supported
The LLM writes the explanation; the numbers come from deterministic systems. That boundary is enforced in code, not prose. The critic may only lower confidence. Findings whose evidence ids do not resolve are dropped before the report is written. The narrative is audited afterwards: every number must trace to the structured facts handed to the model and every evidence id must exist — the adversarial suite feeds the reporter a fabricated "0.0000 bps / 99.9% fill / EXEC-deadbeef" narrative and checks that all three are flagged. The evaluation numbers above were produced with the offline deterministic model. Run for real for the first time in 0.3.1 (claude-haiku-4-5): verdict accuracy on the research suite dropped to 19/21 with a weak planner alone (incomplete plans, handled safely — no crash, no unresolved evidence) and came back to 21/21 once the planner was a stronger model (CEAP_LLM_PLANNING_MODEL=claude-sonnet-5); that same run also caught two real bugs the offline mock had been hiding (see CHANGELOG 0.3.1). The one false positive in the execution suite (S50) is a 200 bps drift inside a 3× volatility window scored as a secondary "price movement" — defensible, and reported rather than tuned away.

The architectural boundary

LLMreasoning, planning, narrative — never a metric, never an evidence id
Python analyticsdeterministic computation: VWAP, IS, slippage, impact, attribution
MCPthe capability interface — the only way to reach data
Harnessthe control plane — agents never control the loop
Policy engineauthority: allow / deny / require approval, explained by rule
Evidenceauditability: every finding cites resolvable records

What's inside

Domain model

Framework-free frozen dataclasses and interfaces for the whole vocabulary — Task, Plan, PlanStep, Agent, Tool, ToolRequest/Result, Evidence (10 types), Finding, Quote, Trade, OrderBook, Order, Execution, ExecutionMetrics, PolicyDecision, repositories, reports. Nothing here imports MCP, an LLM SDK or a web framework.

Deterministic quant analytics

Pure NumPy functions with known-answer tests: VWAP/TWAP, Perold implementation shortfall (execution + opportunity legs, sign-correct for sells), arrival/VWAP/per-fill slippage, effective spread, permanent vs temporary impact, square-root impact estimate, realised and annualised volatility, drift/jump detection, depth, imbalance, stale/crossed-quote diagnostics.

Cause attribution

Window vs baseline scoring over a fixed catalogue — volatility, spreads, liquidity, venue degradation, technology latency, market-data anomaly, large-order impact, price movement — with documented thresholds, saturating scores, a materiality cut-off and guards (platform-wide rejects are not blamed on a venue; drift under high vol is discounted).

Synthetic cash-equity market

Seeded GBM mid path, tick-rounded NBBO with log-normal spread and size noise, Poisson prints across XNAS/ARCA/BATS/IEX/DARK1, five-level books, baseline and window VWAP parents with 30-second child slices, fills that cross the spread and walk the book, latency, rejects, engineering metrics/logs/deployments, positions and limits.

50 evaluation scenarios

Ten templates — normal, high volatility, wide spreads, low liquidity, venue degradation, technology latency, market-data anomaly, large parent order, unexpected price move, mixed market + technology — across AAPL, MSFT, NVDA, AMZN and META with structured ground truth; effects are injected only inside 14:00–15:00 so the prior hour is a clean baseline.

MCP servers

market_data (quotes, trades, book, statistics, reference), execution (parent/child orders, fills, TCA metrics, venue statistics, strategy config, plus the one non-read-only tool — paper order staging), risk (position, exposure, limit check, stress, plus recomputed portfolio exposure/limits/stress for research), engineering (logs, metrics, deployments, latency), knowledge (RAG), and (Stage 2) research_data, alpha, backtest. One definition serves in-process calls and a real FastMCP stdio server; annotations carry read-only, risk level and required capabilities.

MCP client & adapter

MCPClient abstraction with in-process and stdio implementations (official SDK). MCPToolAdapter turns discovered descriptors into domain tools; every invocation yields an evidence record with the arguments, correlation id and a SHA-256 digest of the payload, so the audit trail exists before any agent interprets the data.

Agent harness

Explicit state machine (CREATED → PLANNING → VALIDATING_PLAN → EXECUTING ⇄ AWAITING_APPROVAL → CRITIQUING → VALIDATING_EVIDENCE → FINALISING → COMPLETED), a policy-gated executor with bounded retry, per-step timeout and cooperative cancellation, asyncio.TaskGroup batching of independent tool calls, memory, tracing — and critic/validation/finalise appended whenever a plan omits them.

Planner

The model proposes a JSON plan restricted to the discovered catalogue; unknown tools, agents, step types and arguments are stripped and recorded, the dataset selector is injected only where the schema accepts it, unusable output falls back to a canonical plan, and the harness validates the result again — including a policy pre-check of every tool call before anything runs.

Specialist agents

Market (what happened in the market?), Execution (what happened to our orders?), Quant (what does the data show and why?), Risk (unusual exposure or limit usage?), Engineering (did technology behave normally?), and (Stage 2) Research, Alpha, Backtest, Portfolio risk. Each reads the plan's tool outputs from memory, fetches anything missing through the same policy path, and returns findings with evidence ids plus CALCULATION evidence for its own derivations.

Critic

Deterministic checks first: every cited evidence id must resolve; an anomaly claim must be corroborated by the attribution score; cross-agent contradictions (quant blames technology, engineering says latency is normal) are flagged; single-evidence findings are capped. An optional LLM critique then runs and can only lower confidence.

Reporter with audits

Structured facts go to the model; the narrative comes back in the report's section structure. A number audit checks every figure against the facts (tolerant of rounding and percentage forms) and an evidence-id audit checks every cited id; discrepancies are attached to the report as warnings rather than silently accepted.

Policy engine & approvals

Ordered rules — deny list, read-only, required capabilities, argument guards, symbol universe, risk level — returning ALLOW / DENY / REQUIRE_APPROVAL with the rule that fired. Roles (viewer, trader, quant, engineer, admin) map to capabilities. Approval gateways: automatic (dev), queued with timeout (human decides via the API), deny.

RAG knowledge base

Eight enterprise documents — VWAP runbook, TCA methodology, venue configuration, trading limits, execution policy, market-data architecture, incident runbook, algorithm documentation — chunked by heading, embedded with a dependency-free hashed TF-IDF embedder, and exposed through the knowledge MCP server so retrieved passages become DOCUMENT evidence.

API, CLI, observability

FastAPI gateway with API-key auth and capability checks (202-accepted investigations, report, full result, trace, cancel, approvals), a ceap CLI (investigate · scenarios · evaluate · generate-data · serve), Prometheus text metrics, JSON-lines logging and an in-memory tracer that mirrors to OpenTelemetry when configured.

Adversarial suite

Prompt injection in the question, rogue plans with unknown/mutating tools and malformed steps, unparsable model output, a critic that tries to raise confidence, fabricated numbers and evidence ids in the narrative, oversized and out-of-universe tool arguments, (Stage 2) a rogue plan that schedules order staging first or reaches outside the universe, a hand-built staging step for a principal without trading:execute — each mapped to a control in the threat model.

Stage 2: research workflow (0.3.0)

Research Agent → Alpha Analysis → Backtest Engine → Risk Agent → Critic → Human Approval on the same harness, policy engine, approval gateway and evidence model: rank-IC statistics, an event-driven backtest with a cost model and walk-forward split, a recomputed target portfolio checked against limits, a deterministic verdict with flags, a human approval gate that sees the assessment, and an optional second gate before paper order staging — the platform's only non-read-only tool. 21 research scenarios with ground truth: 21/21 on verdict.

What an investigation looks like

$ ceap investigate "Why did our execution quality for AAPL deteriorate between 14:00 and 15:00?" --dataset T06

AAPL EXECUTION INVESTIGATION 14:00-15:00 London

EXECUTIVE SUMMARY
Headline execution cost did not deteriorate versus the baseline (implementation shortfall delta
-35.9 bps, slippage versus interval VWAP delta +0.4 bps); however the evidence identifies
technology latency as a material anomaly during the window. ...

PRIMARY OBSERVATIONS
1. Primary anomaly: technology latency / rejects in the execution path (score 0.97; execution
   latency ratio vs baseline = 9.98 (threshold 3.0); reject rate = 10.0%). [confidence 0.94]
2. Order-gateway acknowledgement latency was 10.0x the baseline (p99 9828 us, SLO breached). [0.91]
3. Deployment CHG-40388 (smart-order-router 2.14.1: Routing latency budget and venue timeout
   changes) went live at 2026-09-18T13:52:00+01:00 - shortly before the window. [0.85]
...
TECHNOLOGY
Execution latency: Elevated (ratio 9.98 vs baseline)   Reject rate: Elevated (10.0%)
Deployments in scope: 1; error logs: 41

EVIDENCE
- CHANGE-3a3ac7ec  - ENG-1302fd13  - EXEC-5672d0d8  - TCA-16395dc6  ...

Part of a wider portfolio

intraday-alpha-platform

The polyglot research-to-production trading platform this project sits alongside: market data → order books → 205-feature factory → 24 alphas → validation → ML → portfolio → fail-closed risk → execution/SOR → TCA, golden-tested across Python, C++, Rust and Java. GitHub →

quant-portfolio

The end-to-end quantitative finance portfolio: project areas built in Python with C++ and Rust performance twins, golden-vector cross-language validation, a learning guide and a cookbook. GitHub →

quantfinlib

A zero-dependency quantitative finance platform for the JVM — research, validation, execution and connectivity, with CI on every push. GitHub →

Quick start

git clone https://github.com/AshJha0/AgenticAICashEquities && cd AgenticAICashEquities
python -m venv .venv && source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e ".[dev]"

# an investigation from the CLI — offline, deterministic model, ~1 s
ceap investigate "Analyse our AAPL execution between 14:00 and 15:00 and explain why implementation shortfall increased." --dataset T06

# a signal research proposal (Stage 2) — offline, deterministic model
ceap research "Does 12-1 momentum work on R01? Evaluate it out-of-sample with costs." --role quant

# the whole suite: unit, integration, MCP (incl. stdio), agent, adversarial, 50 + 21 scenario evaluations
pytest

# evaluation tables against structured ground truth
ceap evaluate --suite all

# the API — docs at http://127.0.0.1:8000/docs
ceap serve
curl -s -X POST http://127.0.0.1:8000/investigations -H "X-API-Key: dev-trader-key" \
     -H "Content-Type: application/json" \
     -d '{"question": "Why did AAPL execution deteriorate between 14:00 and 15:00?", "dataset": "T05"}'

# real MCP over stdio: the five Stage-1 servers as subprocesses, tools discovered
python scripts/run_stdio_mcp_demo.py

# use a real model (optional): pip install -e ".[llm]" and export ANTHROPIC_API_KEY=...
# for Stage 2, also set CEAP_LLM_PLANNING_MODEL to a stronger planner than the narrator model