Skip to content

Bahi

Equity research with a tamper-evident record

  • Equity research system
  • Python
  • Temporal
  • Postgres
  • FastAPI
  • Next.js

Overview

Bahi is a research workbench for an equity analyst working on India's Nifty 50; five companies are fully built so far. A planner model with four sub-agents answers from filings and daily prices. The model never writes a number. Every figure comes from one of 25 registered calculations, a checker computes it again by another route, and a recommendation waits for the analyst's signature.

Every step of a run, from each model call to the signature, is written to an append-only, hash-chained record in Postgres that can be checked later, offline if needed. The build put that record and the agents' discipline first and kept the research itself small. It shares the append-only record and the planted-error test with FinScientist, though no code.

How it works

The tamper-evident record

Each step is written to the record as it happens, so a later change to any entry or stored payload, in the database or on disk, can be detected.

Fig. 01 · A step becomes evidence
How a step becomes evidenceA step's payload is stored under its SHA-256. Its entry joins a chain in which every hash covers the previous one. Postgres recomputes each hash on insert and refuses edits and deletes. New entries are summarised by a signed Merkle root. A verifier recomputes the chain and finds a changed row, and one run exports as a bundle that verifies offline with the public key.STEPmodel, tool, gate or signaturePAYLOAD STOREsha256 key · written onceENTRY 40prev 0b4d…hash 7c1e…ENTRY 41prev 7c1e…hash 3a90…ENTRY 42prev 3a90…hash d52f…ENTRY 43prev d52f…hash 91b8…INSERT TRIGGERrecomputes each hash on insert;refuses UPDATE, DELETE, TRUNCATEEDIT ATTEMPTUPDATE row 41, any rolerejectedCHECKPOINTMerkle root,ed25519VERIFYhashes,links,rootsRUN EXPORTproofs,payloadsOFFLINEpublic keyonly
  1. 01 Store and chain

    Every model call, tool call, gate decision and signature is a step. Its full prompt or output is stored under the SHA-256 of its bytes, written once and made read-only. The step's entry holds hashes and a payload key, not text; its own hash covers the previous entry's, so each new entry fixes everything written before it.
  2. 02 Refuse

    In Postgres an insert trigger recomputes the hash itself and checks that the entry extends the chain. Other triggers refuse UPDATE, DELETE and TRUNCATE for every role, the owner's included.
  3. 03 Checkpoint

    New entries are folded into a Merkle root, signed with ed25519 and written to write-once storage. This runs hourly as a separate command that is not started by default, and before every export.
  4. 04 Verify

    diary verify recomputes every hash, link and signed root. A row changed outside the database's rules no longer matches the chain after it or the signed root, and the check fails.
  5. 05 Export

    One run exports as a bundle of its entries, Merkle proofs into signed checkpoints, and payloads. It verifies offline with only the public key.

From filing to facts

The Library is built from company filings by a reader that is not trusted, so its answers pass the same checks whether a model API or a Claude Code session produced them.

Fig. 02 · A filing becomes facts
Reading a filing without trusting the readerA schematic statement page is hashed and its words are read from the text layer or OCR. Each statement page becomes a task for a reader. Every value the reader returns must be found on its row in the page's words, and the page's accounting identities must hold. A published fact keeps its page position and the date it became known, and an as-of query returns only facts known by that date.doc_id = sha256(file)known fromOct 25Jan 26Apr 26Q2 FY26Q3 FY26Q4 FY26as of 2 Apr 2026PAGE WORDStext layer orlocal OCRTASKone perstatement pageREADERmaps rowsto metricsON ITS ROWfound in thepage's wordselse droppedIDENTITIESassets = equity + liabilities;totals add upFACTdoc, page, box, printed value,period and known-from dateAS-OF QUERYSQL function; as_of required;nothing known later
  1. 01 Hash

    A filing is stored under the SHA-256 of its bytes. Its page words come from the PDF's text layer, or from OCR run on the machine when the page is a scan.
  2. 02 Read

    Each statement page becomes one task. A reader maps the page's rows and columns to metrics. For the five built companies this reading was done in a Claude Code session, not by a model API.
  3. 03 Find and balance

    Every value must be found on the row the reader named, in the page's own words; a value that is not there is dropped rather than kept. Then the page's accounting identities must hold: total income is revenue plus other income, the profit lines follow from each other, assets equal equity plus liabilities, expenses add up.
  4. 04 Publish

    A fact keeps its document, page, position and value as printed, the period it covers and when it became known. A restatement closes the old fact's range; nothing is deleted.
  5. 05 As of

    Runs read facts only through SQL functions that require a date and return nothing known after it. Publication dates are estimates that can be late but never early.

One research run

A research run is one Temporal workflow in which the planner chooses the steps, but fixed checks sit between it and every tool, and between its draft and the analyst.

Fig. 03 · No number without a calculation
No number without a calculationA planner's tool calls pass a gate before they run. Numbers come from registered calculations that a checker recomputes in SQL. The writer drafts prose with slots for values and a lint refuses typed digits. A checker failure or a recommendation stops the run for the analyst, who signs, and the run is sealed.PLANread the factscompute marginslook for a bear casedraft the answerPRE_TOOL GATEallowed in this mode?budget left?on an open plan item?as_of set by the runPYTHON CALCregistered,versionedSQL CHECKPostgresnumericCHECKERoutputs agree; identities holdWRITERprose with a slot per valueMargin rose to{{calc:…}}typed:18.4%NUMBER LINTdigit outside a slot: blockedANALYSTchecker stop or recommendationSIGNSHA-256 ofthe decisionSEALrun_sealedentry
  1. 01 Plan

    A planner model writes a plan of four to ten items. It can hand a task to one of four sub-agents (reader, quant, skeptic, writer), each with its own short context and a typed result.
  2. 02 Gate

    Every tool call passes a gate: is the tool allowed in this mode, is budget left, does it serve an open plan item, has it been repeated too often. The run's as-of date replaces any the model sent.
  3. 03 Recheck

    Numbers come only from registered, versioned calculations. The checker computes each one again in SQL and runs the accounting identities on its inputs. A mismatch blocks.
  4. 04 Lint

    The writer drafts prose with a slot for each value. Before anything is shown, a lint blocks any digit outside a slot, and every slot must name a calculation that passed the checker.
  5. 05 Stop and seal

    A checker failure, a recommendation or a trade level stops the run for the analyst, who decides what happens next; nothing is corrected automatically. The analyst signs with a SHA-256 of the decision, tamper evidence rather than a proof of identity, and the run is sealed in the record from Fig. 01.

What this doesn't cover

  • It is a research tool, not a trading system: it places no trades and has no portfolio, backtest or returns, and its recommendations use a placeholder scale that the analyst has to sign. Nothing on this page is investment advice.
  • Five companies are fully read into the Library (Bharti Airtel, UltraTech Cement, Larsen & Toubro, Hindustan Unilever, Infosys) and ten more partly; reading new filings is switched off for now. The data is free: Yahoo Finance prices through an unofficial client, for personal, non-commercial use and open to later revision; Wikipedia's current index list, so screens over past dates carry survivorship bias; and filing dates that are estimated, not taken from an exchange.
  • Little is validated at scale. Of 34 scripted agent tasks, 7 have been run with real models, once each, and 5 passed. The checker catches all 266 planted errors, which the code generates, but the 266 labels that score page reading were made by Claude Code and no person has checked them. Cash-flow, segment and earnings-per-share checks from the plan are not built. The project has 453 Python test functions and 18 browser tests; I did not re-run them.
  • It is not production-ready: there is no real login, one-off code is sandboxed in Python only, storage is local write-once files rather than locked cloud storage, and the hourly checkpointer is a separate command that is not started by default. Every figure here is a schematic drawing.