Context
A personal fund for the Nairobi Securities Exchange (NSE), run as a committee rather than a chatbot. I built it on LangGraph as two graphs. The firm graph runs daily operations: it marks the book, keeps an equity curve, runs risk checks and dockets up to two names for review. The hedge_fund graph is the 13-seat committee that reviews one ticker at a time.
The fund trades on a paper ledger in Kenya shillings. My broker app has no public API, so “live” means the committee produces an approved ticket and I place it by hand. The fund’s rules live in playbook/ as an Investment Policy Statement, per-seat doctrine and a chair’s checklist. Every prompt is built from those files at run time, uncached, so an amendment binds the next run.
The problem
One model asked “should I buy this?” gives one confident opinion with no dissent and no sizing discipline. Independent views from narrow lenses, someone paid to attack the consensus, a chair who has to explain why the losing side lost, and sizing done by code a model cannot talk its way around.
Design
The committee graph has a fixed shape:
- Load context. One node fetches prices and the portfolio. Price providers are tried in order: a scraped NSE board, a second scraped source, my manual prices (which override everything), then cached prices flagged as stale.
- Twelve specialists in parallel.
graph.pyadds one node per seat with an edge fromload_contextand an edge intocro_review, so all twelve must finish before the review starts. They write to oneanalyseslist through anoperator.addreducer. Seats include Kenya macro, FX flows, banking, valuation, dividends and liquidity. Each returns a PydanticAnalystView: rating, confidence from 0 to 100, thesis, key risks and data gaps. - Chief Risk Officer. The CRO reads all twelve briefs and must fill
strongest_thesis_attackedandgroupthink_warnings: shared assumptions that could fail together. - Portfolio Manager chair. The PM gets all 13 briefs and returns a
PMDecision: action, allocation, conviction, rationale and a requireddissent_summarynaming the strongest dissent and why it lost. Dissent is not scored numerically. The prompt tells the chair to weigh argument quality and data freshness, not to average ratings, and to say so if the CRO broke the strongest thesis. - Risk gate, then approval. A conditional edge sends approved tickets to a
human_approvalnode that callsinterrupt(). Anything else goes straight to the report.
The web app compiles the same graph with a SQLite checkpointer, so a paused ticket survives restarts. I approve or reject with one tap from a push notification.
Guardrails
The risk gate in nodes.py is plain Python. No model call touches the numbers.
- No price, no trade. If no live, manual or cached price exists, the trade is blocked.
- BUY sizing. The PM’s allocation is clipped to the single-trade cap (20% of equity by default), then to the position cap (25%), then to a cash buffer that always keeps 5% of equity in cash. Quantity is floored after commission (1.85% per side by default) and rounded down to the 100-share board lot. A smaller order is allowed as an odd lot with a liquidity warning. Zero shares is blocked.
- SELL sizing. Selling a position I do not hold is blocked. The quantity is capped at what is held.
- Seat failure. If a specialist or CRO call fails, that seat records a HOLD with zero confidence and “analyst call failed” as a data gap. The run continues and the gap is visible in the report.
- Firm-level checks. The daily ops graph flags a drawdown of 15% or more and halts new buys until a holdings review. It also flags concentration drift and held names priced from stale data. In the live committee this halt is a flag and a task for me, not a gate inside
risk_gate. The v4 backtest profile enforces it mechanically.
Evals and results
- Offline self-test.
selftest.pyruns ten sections with stubbed models and isolated state: doctrine injection, approve, reject and HOLD paths, risk-gate clipping, ledger and commission math, deposit accounting, the drawdown halt, the task ledger, the web app (including auth and a path-traversal guard) and the scheduler. - Mechanical stress backtest.
stress_backtest.pyreplays a quarter of real daily closes from six US, six German and six Japanese stocks through the realrisk_gateand ledger, driven by rule-based stand-in policies. An adversary fires illegal orders every day: an allocation of 500%, a sale of a stock not held, a buy with no price, and billion-share orders sent straight at the ledger. A run is GREEN only with zero invariant violations. - Blinded committee backtest. The real 13-seat graph trades real US, German and Japanese history it cannot recognise. Tickers become call-signs, prices are rescaled per ticker and dates move to a synthetic calendar. Each call is capped at seven minutes, and runs resume per market so finished committee calls are not paid for twice. A metrics panel reports Sharpe, Sortino, Calmar, win rate, turnover and fee drag from deposit-adjusted returns. 2026 is held out as a final test.
- Calibration.
calibrate.pyjoins each decision with the ticker’s 4-week forward return. The 2023 baseline scored 151 decisions. BUYs were followed by +3.1% on average against +1.4% for HOLDs, SELLs came too early (+1.8% forward), and conviction never went above 70. That summary is fed back into the chair’s prompt, and the policy gained a no-trade band and a rule that HOLD is not free.
What is not measured: the committee’s live track record on the NSE, because the fund is still in paper commissioning. Every committee A/B so far compares single samples of a stochastic process. I wrote a variance run of identical v3 profiles to measure that spread, but its results are not in the repo. The backtest and calibration commits are in my local history and not yet pushed to the public repo.
A failure I handled
The fund quietly stopped reading live NSE prices. The main price source changed its markup to unquoted attributes, with the ticker only in the URL slug. My regex matched zero rows, so every run fell back to my manual prices without an error.
I rewrote the pattern for the new markup. It now parses the full 71-counter board and requires a bare <td> after the anchor, which skips the “movers” tables that use <td class=r>. In the same commit I fixed a self-test leak: the test removed WEBAPP_PASSWORD before importing the web app, but the app’s load_dotenv() put it back on any machine with real credentials. The test now scrubs it again after the import.
Stack
Python, LangGraph, LangChain init_chat_model, Pydantic structured output, LangSmith, FastAPI, SQLite checkpointer, APScheduler, ntfy push notifications, launchd, Yahoo chart API for backtest data.