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.
src/ceap (122 files) · ≈4.0k lines of tests · ruff clean · mypy clean · Python 3.12 in CI, 3.11+ supported
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
$ 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 ...
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 →
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 →
A zero-dependency quantitative finance platform for the JVM — research, validation, execution and connectivity, with CI on every push. GitHub →
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