Future with Shivank · AI Agents in Finance · Section 5

Future with Shivank · Hands-on track · Section 5

Deep Search Build an analyst-grade research agent that plans, digs, double-checks and writes the memo

In Section 4 the workflow was fixed in advance: the same five agents, the same three phases, for every stock. A deep search agent goes one step further: it writes its own research plan for whatever question you ask, runs the plan in parallel, checks its numbers with plain Python, and if something is missing it re-plans and tries again — before writing a structured investment memo.

🏦 Monday, 9 am at Future with Shivank Bank. A portfolio manager pings the research desk: "Should we increase our NVIDIA position given the AI spending cycle? How does it compare with AMD and Intel on growth, margins and risk?" A human analyst would need a day: plan the questions, pull filings, read news, cross-check numbers, write the memo. Our agent does the first draft in about 30 seconds.
7sub-tasks the planner writes for this question
5 at oncetasks run in parallel in the first wave
~30 sfrom question to a saved memo
~$0.15per research run (~28k tokens)
🧠 Analogy💰 Finance corner⚠️ Watch out💡 Tip🧪 Simulation (click it!)

Section 5 · Part 1 — The idea

From "answer a question" to "do the research"

5.1What is deep search?

Deep search (also called deep research) is an agent that plans a research strategy, gathers information from many sources in several rounds, checks what it found, and writes a structured report. It is not a faster search engine; it is an automated junior analyst.

🧠 Analogy — the librarian vs the research analyst

Basic RAG is asking a librarian: "find me the page that mentions NVIDIA's revenue." One trip to one shelf, one answer.
Deep search is hiring a research analyst: they write a to-do list, send juniors to five different sources at once, check that the numbers agree, notice "we're missing AMD's figures", go back for them, and only then write the memo.

Basic RAG — one pass Question Retrievenearest chunks Generate Answershort text + citations Deep search — a loop Question Plansub-tasks Executemany tools, in parallel Validatecode checks Reportstructured memo passes gap or error found → re-plan and try again
RAG answers in one straight line. Deep search runs a loop — and only writes the report once its own checks pass (or it has run out of retries).
Basic RAGDeep search agent
PlanningNoneWrites its own research plan with sub-tasks
SourcesOne pre-built vector storeLive APIs, SEC filings, news, databases
MathsCan't compute over what it findsCalculates growth, margins, P/E through tools
CheckingNoneValidates, cross-checks, finds gaps
OutputA short answerA multi-section research memo
Time1–5 seconds30 seconds to a few minutes

RAG is perfect for "What was NVIDIA's revenue in 2024?" It breaks on "Compare NVIDIA, AMD and Intel on growth, competition and risk, and write a memo" — three companies, several data types, calculations, cross-checks, a structured write-up.

💰 Why finance is the perfect home for deep search
  • Many sources are normal: filings, earnings calls, prices, ratios, news, macro data — no single database has them all.
  • Accuracy is non-negotiable: a wrong number can mean a wrong trade or a regulatory problem, so built-in checking matters.
  • Speed is an edge: read a fresh quarterly filing and flag surprises in minutes, not hours.
  • Scale is the bottleneck: an analyst can research 2–3 companies deeply in a day; an agent can cover an entire index and let the analyst focus on decisions.

You've probably used the consumer versions: Gemini Deep Research (Dec 2024), OpenAI Deep Research (Feb 2025) and Perplexity's deep research mode all made this pattern mainstream. The underlying method — plan, search, check, write — is simply how good analysts and investigative journalists have always worked.

5.2Anatomy of a deep search agent

Every deep search agent, whatever the framework, runs the same four-phase loop:

  1. Plan — split the question into sub-tasks with explicit dependencies. Good tasks are measurable ("fetch AMD revenue") not vague ("understand AMD").
  2. Execute — run each sub-task with the right tool; independent tasks run at the same time; findings are written to a scratchpad.
  3. Validate — check consistency (do two sources agree?), completeness (all three companies?), reasonableness (is 500% growth real or a parsing mistake?) and gaps.
  4. Synthesize or re-plan — if checks pass, write the report; if not, go back to step 1 knowing exactly what's missing.
ComponentIts jobOffice analogy
PlannerTurns the question into sub-tasks + dependenciesTeam lead writing the to-do list on a whiteboard
Tool executor (researcher)Calls APIs, filings search, web searchJunior analysts sent out to fetch data — several at once
ValidatorChecks completeness, ranges, contradictionsThe auditor with a printed checklist
SynthesizerWrites the final structured reportThe senior analyst who writes the memo
OrchestratorRuns the loop, decides when to retryThe project manager
Scratchpad / context managerLogs every step; keeps the token budget under controlThe case file — and the habit of summarising it

Three ways to arrange those parts

① One agent, ReAct loopsimplestOne LLM plans, fetches, checks and writes in one long conversation. Easy to build — but the context overflows on big questions, nothing runs in parallel, and checking is often skipped. Good for: one-company questions, learning.
② Specialist agentse.g. DexterPlanner, action, validation and answer agents, each with its own prompt and context. Clean and debuggable, but more tokens. Good for: thorough analysis where quality beats cost.
③ Orchestrator + task graphe.g. AI AlliancePlan once as a dependency graph, run tasks through standard tools (MCP), verify each step with code, re-plan only on failure. More setup. Good for: production.

Our project is a hybrid of ② and ③: separate planner / researcher / validator / synthesizer roles, a dependency graph with parallel waves, and a validator written in plain Python.

The story that proves the point: three attempts at the same agent

The open-source AI Alliance team documented building a finance deep-research agent three times. It's the most useful story in this whole section:

Attempt 1 · Too simplefailedOne LLM with tools. When a tool errored, it invented the numbers. Long contexts made it "forget" earlier findings. Sometimes brilliant, sometimes nonsense.
Attempt 2 · Too cleverworse!Dynamic roles, LLM checkers at every step, automatic prompt rewriting. The LLM checker approved made-up data and rejected correct data; coordination ate more tokens than the research.
Attempt 3 · Just rightworkedPlan up front as a task graph. Verify each step with simple Python checks ("is this margin between −50% and 100%?"). Re-plan only when something fails. Reliability jumped.
💡 The lesson to write on the board

Use code to check numbers; use the LLM to reason and write. An LLM asked "does this look right?" can be talked into a plausible wrong number. if operating_margin > gross_margin: can't. (Same lesson as Section 4's peer verdict.)

5.3Financial data: the real challenge

Building a deep search agent is as much data engineering as AI. Fintool's founder has called financial data "adversarial" — it actively resists being read by machines — and estimates data clean-up is about 80% of the engineering work. Once the data is clean, the LLM reasoning is the easy part.

Kind of dataExamplesHow hard?
StructuredPrices, revenue, EPS, ratios via APIsEasy — clean JSON. Watch rate limits, freshness, cost.
Semi-structuredSEC filings, earnings-call transcripts, newsHard — messy HTML, speaker labels, duplicates. Each source needs its own parser.
UnstructuredAnalyst PDFs, web pages, ESG reportsHardest — PDF tables break, paywalls, scraping.
MacroInterest rates, inflation, jobs dataEasy to fetch, hard to connect to one company.

Trap 1 · A real-looking 10-K table

What a human reads

Revenue (in millions)202420232022
Products$89,394$78,932$68,412
Services(1)24,63122,31419,876
Total revenue$114,025$101,246$88,288

What a naive parser trips on

Revenue (in millions) ← unit lives in a header Products $89,394 … ← "$" on some numbers only Services(1) 24,631 … ← "(1)" looks like −1! Total revenue $114,025 … (1) Includes AppleCare … ← footnote, not data

Other classics: negatives written as (1,234), the same document mixing $1,234.5M, 1.2B and 1,234,500 thousand, units that change mid-table without warning, merged cells. Now imagine dozens of such tables per filing.

Trap 2 · "Q1 2024" means different months for different companies

Companies pick their own financial year. Compare "Q1 2024" across them naively and you compare different months — a silent error: the output looks perfectly plausible and is wrong.

🧪 Simulation · fiscal calendar translator

Drag to any month — see what each company calls it

Nov 2023
💰 Why this matters for our project

NVIDIA's year ends in late January, so its "FY2024" revenue of $60.9B mostly happened in calendar 2023. AMD and Intel use calendar years. A careful agent says which periods it is comparing — and production systems convert everything to calendar quarters before the LLM ever sees it.

Five rules production teams follow

  1. Use APIs when they exist — don't scrape what you can query.
  2. Score your confidence in extracted values; send low-confidence ones for checking.
  3. Normalise units and periods early, in code. Don't leave it to the LLM — it will slip.
  4. Cache aggressively — a filed quarter never changes.
  5. Hand the LLM clean data, not raw text:
✗ Raw text to the LLM

"NVIDIA Corp 10-K FY2024... Revenue... see Note 3... $60,922M... includes revenue from... (in millions except per share data)..."

✓ Clean, labelled data

{"ticker": "NVDA", "metric": "revenue", "period": "FY2024", "value": 60922, "unit": "millions_usd", "source": "10-K", "filing_date": "2024-02-21"}

How tools get wired in — three patterns you'll meet: direct tools (one Python function per source — what our lab uses, simplest to read), a meta-tool (one financial_search(query) that routes internally to the right source — keeps the agent's tool list short), and MCP servers (standard plug-in tools any framework can discover — best for sharing across teams).


Section 5 · Part 2 — Build it, step by step

The project: a research desk, written in Python

5.4The project & its map

Our agent gets one real research question from the portfolio manager:

❓ "Analyze NVIDIA's financial performance and competitive position in the AI chip market. Compare with AMD and Intel on revenue growth, profitability, and key risk factors. Produce a structured investment research memo."

Why can't one LLM call — or the basic RAG you built on AWS — answer this well? Because the question quietly hides five different jobs:

Three companiesEach one needs its own numbers fetched.
Several data typesFinancial statements, share prices, annual filings, news.
MathsGrowth, margins and P/E must be calculated, never guessed.
Cross-checkingNumbers from different places must agree.
A memo, not a paragraphFixed sections the PM can scan in two minutes.

Three decisions before writing any code

① How we call the LLMraw firstWe build every piece with the plain OpenAI client, so you see exactly what happens. In the lab (5.11) we swap in PydanticAI — only the LLM calls change, nothing else.
② Where data comes from3 sourcesFinancial Datasets API for numbers and prices · SEC EDGAR for the risk section of annual reports · Tavily web search for news from trusted sites.
③ Who checks the numberscode, not LLMPlain Python checks: ranges, consistency, completeness. The LLM is used for planning, reasoning and writing — never to answer "does this number look right?"
🧠 Analogy — the research desk at Future with Shivank Bank

Picture the desk on Monday morning. The desk head (planner) writes a to-do list on the whiteboard, with arrows meaning "do this after that". Runners (researcher + tools) grab every card that can start — all at once — and pin what they find to a shared board. A compliance checker (validator) walks the board with a calculator and a checklist. A memo writer (synthesizer) turns the board into the memo. The desk manager (orchestrator) decides: "good enough, write it" or "something's missing — plan again".

JobDesk roleFileUses an LLM?
Turn the question into tasksDesk headplanner.py✅ yes — structured output
Fetch numbers, filings, newsRunnerstools/*.py❌ no — plain API calls
Run the tasks in the right orderRunner coordinatorresearcher.pyOnly for "thinking" tasks 6 & 7
Check the findingsCompliancevalidator.py❌ never
Write the memoMemo writersynthesizer.py✅ yes — structured output
Run the loop, decide to retryDesk managerdeep_search_agent.py❌ no — a for loop
💡 Count the ❌

Half of this "AI agent" is ordinary Python. That's on purpose: code is cheap, fast and gives the same answer every time. Use the LLM only where you need judgement or language.

The map: one full run

Wave 1 · no dependencies → all at once Wave 2 Wave 3 Your question+ NVDA, AMD, INTC PlannerLLM writes 7 tasks 1 · NVIDIA metricsfinancial_api · needs — 2 · AMD metricsfinancial_api · needs — 3 · Intel metricsfinancial_api · needs — 4 · Risk factors (10-Ks)sec_filing · needs — 5 · AI-chip market newsweb_search · needs — 6 · CompareLLM · needs 1, 2, 3 7 · Draft memoLLM · needs 4, 5, 6 Validatorplain Python checks SynthesizerLLM → the memo valid gap or error → re-plan (up to 2 more tries)
The plan is a dependency graph: an arrow means "must finish first". Tasks 1–5 need nothing, so they run together. Task 6 can only compare once all three companies' numbers are in. Task 7 writes a draft once the comparison, risks and news are ready. The dashed arrow is the re-plan path.
🧪 Simulation · follow one full run

Click through the run and watch the variables change

Gold on the map = what's happening at this step. The boxes in the panel are the real variable names from the code you're about to read — a gold box changed at this step.

Why "all at once" matters

🧠 Analogy — one chef, five ovens

A chef with five ovens doesn't stand in front of oven 1 until the cake is done before putting the bread in oven 2. She fills all five, then waits for the slowest dish. Tool calls are the same: most of their time is spent waiting for a server on the internet. While one call waits, Python can start the others. That's what async / await and asyncio.gather give us.

🧪 Simulation · one after another vs all at once

Wave 1 has one metrics task per company (≈2 s each), plus the filings task (≈4 s) and the news task (≈5 s). Add companies and watch both timelines. Timings are illustrative.

3
⚠️ Real-world catch: rate limits

APIs limit how many calls you may make per second. With 50 companies, "all at once" can earn you 429 Too Many Requests. The usual fix is a small "only N at a time" gate called asyncio.Semaphore — like letting only five customers into the bank branch at once.


5.5The data models — the forms everyone fills in

🧠 Analogy — bank forms

Banks run on forms. A loan application has fixed boxes — name, amount, tenure — and the clerk won't accept "amount: banana". Pydantic models are the agent's forms. Every part hands the next part a filled-in form, and Python refuses a form with a missing or wrong box. That's what stops one confused component from quietly poisoning the next.

Planner ResearchPlan Researcher results: dict[int, str] 7 × SubTask inside CompanyMetrics → JSON text inside Validator ValidationResult Synthesizer ResearchReport errors · warnings · gaps the memo — saved as JSON
Pills = forms (Pydantic models), boxes = the parts that fill them in. Read it like a relay race: each runner hands over a baton of a fixed shape.
Python · common.py · all the forms in one file
# common.py — the "forms" that every part of the agent fills in
from enum import Enum
from pydantic import BaseModel, Field


class TaskStatus(str, Enum):         # the 4 stickers a task can wear
    PENDING = "pending"              # not started yet
    RUNNING = "running"              # a tool is working on it
    COMPLETED = "completed"          # finished, result saved
    FAILED = "failed"                # the tool raised an error


class SubTask(BaseModel):
    """A single research sub-task within a plan."""
    id: int                                          # 1, 2, 3 …
    description: str                                 # the job, in plain English
    data_sources: list[str] = Field(
        description="Tools: 'financial_api', 'sec_filing', 'web_search'"
    )
    dependencies: list[int] = Field(default_factory=list)  # ids to wait for
    status: TaskStatus = TaskStatus.PENDING          # only OUR code changes this


class ResearchPlan(BaseModel):                       # what the planner returns
    question: str
    sub_tasks: list[SubTask]


class CompanyMetrics(BaseModel):                     # one company, clean numbers
    ticker: str
    revenue: float | None = None             # $ millions
    revenue_growth: float | None = None      # % vs the year before
    eps: float | None = None                 # earnings per share, $
    gross_margin: float | None = None        # %
    operating_margin: float | None = None    # %
    pe_ratio: float | None = None            # price ÷ EPS
    market_cap: float | None = None          # $


class ValidationResult(BaseModel):                   # the checker's report card
    is_valid: bool
    errors: list[str] = Field(default_factory=list)     # impossible numbers
    warnings: list[str] = Field(default_factory=list)   # odd but possible
    gaps: list[str] = Field(default_factory=list)       # missing pieces


class ResearchReport(BaseModel):                     # the final memo
    title: str
    executive_summary: str
    key_metrics_table: str
    competitive_analysis: str
    risk_factors: list[str]
    conclusion: str
    sources: list[str]
    confidence_score: float = Field(description="Between 0 and 1")
  1. TaskStatus(str, Enum) — the four stickers. An Enum is a fixed menu of allowed values, so a typo like TaskStatus.COMPLETD crashes immediately instead of silently never matching. Mixing in str makes each sticker also a normal string, so it prints and saves to JSON as "completed".
  2. Field(description=...) on data_sources isn't just a comment for humans: it's sent to the LLM as part of the form's instructions. That's how the planner learns the only three tool names it may use.
  3. default_factory=list means "if nobody fills this in, start with a fresh empty list". An empty dependencies list means "this task can start straight away".
  4. status defaults to PENDING. The LLM simply writes "pending"; from then on only our code moves the sticker forward.
  5. float | None = None reads "a number, or honestly unknown". A missing value stays None — never 0. An unknown margin and a 0% margin are very different facts, and the validator treats them differently.
  6. ValidationResult has three buckets — errors, warnings, gaps — that you'll meet in 5.9. ResearchReport is the memo template: every memo has the same sections, so the PM always knows where to look.

What a filled-in plan looks like

This is the kind of ResearchPlan the planner returns for our question (shown as JSON; wording varies run to run):

JSON · the plan for our question (illustrative)
{
  "question": "Analyze NVIDIA's financial performance ... research memo.",
  "sub_tasks": [
    {"id": 1, "description": "Fetch NVIDIA (NVDA) revenue, growth, margins and P/E",
     "data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
    {"id": 2, "description": "Fetch AMD revenue, growth, margins and P/E",
     "data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
    {"id": 3, "description": "Fetch Intel (INTC) revenue, growth, margins and P/E",
     "data_sources": ["financial_api"], "dependencies": [], "status": "pending"},
    {"id": 4, "description": "Extract key risk factors from the latest 10-Ks of NVIDIA, AMD and Intel",
     "data_sources": ["sec_filing"], "dependencies": [], "status": "pending"},
    {"id": 5, "description": "Find recent AI-chip market news on NVIDIA, AMD and Intel",
     "data_sources": ["web_search"], "dependencies": [], "status": "pending"},
    {"id": 6, "description": "Compare revenue growth, profitability and valuation",
     "data_sources": [], "dependencies": [1, 2, 3], "status": "pending"},
    {"id": 7, "description": "Draft the investment memo from metrics, risks and news",
     "data_sources": [], "dependencies": [4, 5, 6], "status": "pending"}
  ]
}
💡 How to read dependencies

"dependencies": [1, 2, 3] on task 6 means "task 6 may start only after tasks 1, 2 and 3 are COMPLETED". An empty list [] means "no waiting — start now". Compare this JSON with the map above: it's the same graph, written as text.

5.6Step 1 · The planner — from one question to a to-do list

🧠 Analogy — the desk head's whiteboard

A good desk head doesn't start researching. She writes the cards: one card per job, which source to use, and arrows for what must wait. A good plan is boring and repeatable — ask the same question twice, get the same cards. That's why the planner runs at temperature 0.

Python · planner.py · create_research_plan
# planner.py — turns ONE question into a to-do list (a ResearchPlan)
from openai import AsyncOpenAI
from common import ResearchPlan

PLANNER_PROMPT = """You are a financial research planner. Given a research
question, decompose it into concrete sub-tasks that can be executed by tools.

Available data sources:
- financial_api: Structured financial metrics (revenue, EPS, margins, P/E, market cap)
- sec_filing: SEC filing content (risk factors, business descriptions, MD&A)
- web_search: Recent news, competitive intelligence, analyst commentary

Rules:
1. Each sub-task must have a clear, measurable outcome.
2. Specify which data_sources each sub-task should use.
3. Mark dependencies — which tasks must complete before others can start.
4. Tasks with no dependencies can run in parallel.
5. Always include a final synthesis task that depends on all data-gathering tasks.
6. For multi-company comparisons, create parallel tasks for each company.

Respond with a JSON object matching the ResearchPlan schema."""


async def create_research_plan(question: str) -> ResearchPlan:
    """Generate a structured research plan from a question."""
    client = AsyncOpenAI()                            # ① reads OPENAI_API_KEY
    response = await client.chat.completions.parse(   # ② ask, and force the shape
        model="gpt-4o",
        messages=[
            {"role": "system", "content": PLANNER_PROMPT},
            {"role": "user", "content": question},
        ],
        response_format=ResearchPlan,                 # ③ "fill in THIS form"
        temperature=0,                                # ④ same question → same plan
    )
    return response.choices[0].message.parsed         # ⑤ a ResearchPlan object

How the prompt's six rules show up in the plan

Rule in the promptWhat you see in the plan
1 · Clear, measurable outcome"Fetch AMD revenue, growth, margins and P/E" — not "look into AMD"
2 · Name the data sources"data_sources": ["financial_api"] on tasks 1–3
3 · Mark dependencies"dependencies": [1, 2, 3] on task 6
4 · No dependencies → parallelTasks 1–5 all have [], so they form wave 1
5 · A final synthesis taskTask 7 waits for 4, 5 and 6
6 · One task per companyThree separate tasks 1, 2, 3 — not one "fetch all three" task, so they can run side by side and fail independently

The code, line by line

  1. AsyncOpenAI() creates the async version of the OpenAI client. It finds your key in the OPENAI_API_KEY environment variable — never paste keys into code.
  2. await client.chat.completions.parse(...) — await means "start this, and while we wait for OpenAI's reply, Python may get on with other jobs". We use .parse (not .create) because it's the structured-output version.
  3. response_format=ResearchPlan — the magic line. The SDK turns our class into a JSON schema, the model is constrained to reply in exactly that shape, and the SDK turns the reply back into a real ResearchPlan object.
  4. temperature=0 — the creativity dial at minimum. Same question → (almost) the same plan, which makes runs easy to compare and debug.
  5. response.choices[0].message.parsed — unwrapping the parcel: response is the whole reply envelope → choices[0] the first (and only) answer → message → parsed, our ready-made object.
class ResearchPlan→JSON schema→LLM fills it in→JSON text→ResearchPlan object

What .parse does for you behind the scenes. You write the first and get the last; the middle three steps are automatic.

VariableTypeWhat it holds
questionstr"Analyze NVIDIA's financial performance…"
clientAsyncOpenAIA connection to OpenAI, with your key
responsecompletion envelopeid, token usage, choices list…
response.choices[0].message.parsedResearchPlanThe question + 7 SubTask objects — returned to the caller as plan
⚠️ Two production habits
  • If the model refuses (rare), parsed is None and the reason sits in message.refusal. Check for it before using the plan.
  • Save every plan to a log file. When a memo looks odd next week, the plan is the first thing compliance will ask to see.

5.7Step 2 · The tools — couriers who also translate

🧠 Analogy — a courier who also translates

Each data source is a different office with its own address, its own password and its own paperwork. A tool function is a courier who knows one office: it goes there, shows the password, collects the parcel — and then translates the paperwork into our bank's standard form before handing it back. The rest of the agent never sees the office's messy format.

ToolGoes toNeedsBrings backTypical failures
get_financial_metrics(ticker)Financial Datasets APIAPI keyA clean CompanyMetrics formwrong key (401), unknown ticker (404), too many calls (429)
get_risk_factors(ticker)SEC EDGAR (free, official)your email"Item 1A · Risk Factors" text from the latest 10-Kblocked without an email header; very long text
search_financial_news(query)Tavily web searchAPI key5 recent articles from trusted sitesstale or off-topic results

Tool 1 · get_financial_metrics — the most important one

Python · tools/financial_data.py · get_financial_metrics
# tools/financial_data.py — fetch ONE company's numbers and clean them up
import os
import httpx
from common import CompanyMetrics

BASE_URL = "https://api.financialdatasets.ai"


def _pct(part, whole):
    """part ÷ whole as a percent (1 decimal), or None if we can't work it out."""
    if part is None or not whole:
        return None
    return round(part / whole * 100, 1)


async def get_financial_metrics(ticker: str) -> CompanyMetrics:
    headers = {"X-API-KEY": os.environ["FINANCIAL_DATASETS_API_KEY"]}   # ① password
    async with httpx.AsyncClient(base_url=BASE_URL, headers=headers,
                                 timeout=30) as client:                 # ② open line
        income_resp = await client.get(                                 # ③ 2 years
            "/financials/income-statements",
            params={"ticker": ticker, "period": "annual", "limit": 2},
        )
        price_resp = await client.get("/prices/snapshot",               # ④ price
                                      params={"ticker": ticker})
    income_resp.raise_for_status()           # ⑤ 401 / 404 / 429 / 500 → error
    price_resp.raise_for_status()

    statements = income_resp.json()["income_statements"]   # ⑥ newest year first
    latest = statements[0]
    prior = statements[1] if len(statements) > 1 else None
    snapshot = price_resp.json()["snapshot"]
    price = snapshot.get("price") or snapshot.get("close")

    revenue = latest.get("revenue")                          # in plain dollars
    eps = latest.get("earnings_per_share")
    growth = None
    if revenue and prior and prior.get("revenue"):           # ⑦ growth needs 2 years
        growth = round((revenue / prior["revenue"] - 1) * 100, 1)

    return CompanyMetrics(                                   # ⑧ the clean form
        ticker=ticker,
        revenue=round(revenue / 1_000_000, 1) if revenue else None,  # → $ millions
        revenue_growth=growth,
        eps=eps,
        gross_margin=_pct(latest.get("gross_profit"), revenue),
        operating_margin=_pct(latest.get("operating_income"), revenue),
        pe_ratio=round(price / eps, 1) if price and eps and eps > 0 else None,
        market_cap=snapshot.get("market_cap"),
    )
  1. The password. headers is a small dictionary sent with every request. The key comes from the environment, never from the code.
  2. async with httpx.AsyncClient(...) as client: opens a connection — think of it as a phone call. The with block hangs up automatically when it ends, even if something goes wrong inside. base_url saves typing the address twice; timeout=30 means "give up after 30 seconds instead of waiting forever".
  3. Two years of income statements (limit=2). Why two? Growth needs this year and last year.
  4. Today's price from the price snapshot — needed for P/E.
  5. raise_for_status() turns an HTTP failure (401, 404, 429, 500…) into a Python error. That sounds bad, but it's exactly what we want: the error travels up to run_task, which marks the task FAILED (5.8), which the validator turns into a gap (5.9), which triggers a re-plan. Silent failures are the dangerous ones.
  6. Unpack the parcel. .json() turns the reply into a Python dictionary. statements[0] is the newest year, statements[1] the year before. snapshot.get("price") or snapshot.get("close") means "use price; if it's missing, use close".
  7. Growth is only calculated if both years have revenue — otherwise it stays None.
  8. Translate into our form. Dollars → millions, ratios → percentages, P/E only if earnings are positive.

Before: what the API sends (trimmed)

{ "income_statements": [ { "revenue": 60922000000, "gross_profit": 44301000000, "operating_income": 32972000000, "earnings_per_share": 11.93, … }, { "revenue": 26974000000, … } ] } { "snapshot": { "price": 817.2, … } }

After: what the rest of the agent sees

CompanyMetrics( ticker="NVDA", revenue=60922.0, # $ millions revenue_growth=125.9, # % eps=11.93, gross_margin=72.7, # % operating_margin=54.1, # % pe_ratio=68.5, market_cap=None) # not sent → unknown

Illustrative values for NVIDIA's fiscal year 2024 (which ended in January 2024 — remember the fiscal calendar in 5.3).

NumberFormula in the codeWorked example (NVIDIA)
Revenue growth(revenue / prior - 1) * 100(60,922 ÷ 26,974 − 1) × 100 = 125.9%
Gross margingross_profit / revenue * 10044,301 ÷ 60,922 × 100 = 72.7%
Operating marginoperating_income / revenue * 10032,972 ÷ 60,922 × 100 = 54.1%
P/Eprice / eps817.2 ÷ 11.93 = 68.5×
💰 Finance corner: the four numbers in plain words optional · glance over

Imagine a sweet shop. Revenue is everything customers paid. Gross margin is what's left after paying for the sugar and milk, as a % of revenue. Operating margin is what's left after also paying rent, salaries and electricity — so it is always smaller than gross margin. Revenue growth compares this year's sales with last year's. P/E asks: "how many years of today's profit would I pay to buy one share?" A P/E of 68 means investors pay 68 years' worth of current profits — they expect profits to grow a lot.

⚠️ Three things that bite beginners
  • P/E only when EPS > 0. A loss-making company has negative earnings, and "price ÷ negative number" is meaningless. We store None instead.
  • Field names change. APIs rename fields (price vs close). Before trusting any tool, print one raw response and read it.
  • The two calls run one after the other. They could also run together with asyncio.gather — a nice small exercise once you've finished 5.8.

What happens when a call fails — the error's journey

API says 503→raise_for_status() raises→run_task catches it→task.status = FAILED→validator: a gap→orchestrator: re-plan

One failed courier never crashes the desk. It turns into a note that travels up until someone with the authority to act — the desk manager — decides what to do. You'll make AMD fail on purpose in the simulation in 5.8.

Tool 2 · search_financial_news

Python · tools/web_search.py · search_financial_news
# tools/web_search.py — recent news, from trusted publishers only
import os
from tavily import AsyncTavilyClient

TRUSTED = ["reuters.com", "bloomberg.com", "wsj.com",
           "cnbc.com", "seekingalpha.com", "ft.com"]


async def search_financial_news(query: str) -> str:
    client = AsyncTavilyClient(api_key=os.environ["TAVILY_API_KEY"])
    response = await client.search(
        query,
        topic="news",                # news search, not the whole web
        include_domains=TRUSTED,     # only these publishers
        max_results=5,
    )
    # a list of hits → one readable block of text for the LLM
    return "\n\n".join(
        f"{hit['title']} ({hit['url']})\n{hit['content']}"
        for hit in response["results"]
    )

include_domains=TRUSTED is the important line: it keeps the agent away from random blogs and forums. The last statement is a generator expression inside "\n\n".join(...) — read it as "for every hit, write title (link) and summary, and glue them together with blank lines". The LLM gets one tidy block of text with sources it can cite.

Tool 3 · get_risk_factors (in words)

SEC EDGAR is the US regulator's free filing system. The tool finds the company's latest annual report (the 10-K) and pulls out section Item 1A · Risk Factors — where companies must list what could hurt them (supply chains, export rules, key customers…). Two rules: EDGAR wants a contact email in the request's User-Agent header (that's why .env has SEC_EDGAR_EMAIL), and it allows roughly 10 requests per second. Filings run to 100+ pages, so the tool trims the text before returning it — fewer tokens, lower cost.

5.8Step 3 · The researcher — run the plan in waves

🧠 Analogy — the kitchen ticket rail

In a restaurant kitchen, orders hang on a rail. Every round, the head chef looks at the rail and asks one question: "which tickets can I cook right now?" — the ones whose ingredients are ready. She fires all of them at once, waits for that round to finish, then looks at the rail again. When no ticket is left, service is over. If some tickets are stuck waiting for an ingredient that will never arrive, she stops instead of staring at the rail forever.

Python · researcher.py · execute_plan (the loop)
# researcher.py — run the whole plan, wave by wave
import asyncio
from common import ResearchPlan, TaskStatus


async def execute_plan(plan: ResearchPlan) -> dict[int, str]:
    results: dict[int, str] = {}                      # ① the shared notebook
    tasks_by_id = {t.id: t for t in plan.sub_tasks}   # ② id → task lookup

    while any(t.status == TaskStatus.PENDING for t in plan.sub_tasks):   # ③
        ready = [                                     # ④ who can start now?
            t for t in plan.sub_tasks
            if t.status == TaskStatus.PENDING
            and all(tasks_by_id[d].status == TaskStatus.COMPLETED
                    for d in t.dependencies)
        ]
        if not ready:                                 # ⑤ stuck → stop the loop
            break
        completed = await asyncio.gather(             # ⑥ run the wave together
            *[run_task(t, results) for t in ready]
        )
        for task_id, result in completed:             # ⑦ write it all down
            results[task_id] = result

    return results
  1. results — the shared notebook. A dictionary: key = task id, value = what that task found (as text). It starts empty; by the end it looks like {1: '{"ticker": "NVDA", …}', 2: …, 7: "Draft memo…"}.
  2. tasks_by_id — a phone book. This is a dict comprehension; read it as "for every task t in the plan, file it under t.id". Now tasks_by_id[3] instantly gives task 3, so we can ask "is task 3 done?" in one step.
  3. while any(...) — any() asks "is at least one of these true?". Keep going while at least one task still wears the PENDING sticker.
  4. ready — who can start now? Read it aloud: "every task t that is PENDING and whose every dependency d is COMPLETED".
  5. if not ready: break — the safety exit. Tasks are still pending, but none can start: they're waiting for a task that failed. Without this line the loop would spin forever.
  6. asyncio.gather(*[...]) — fire the whole wave. The list [run_task(t, results) for t in ready] builds one "job" per ready task (nothing runs yet) — run_task is the one-task worker you'll read just below. The * unpacks the list into separate arguments: gather(job1, job2, job3, …). gather runs them together and waits for the slowest. It returns their answers in the same order as the jobs, not in finishing order.
  7. for task_id, result in completed — each answer is a pair like (2, '{"ticker": "AMD", …}'). Python splits the pair into two variables (tuple unpacking), and we write it into the notebook.
💡 The tiny Python fact that makes it work: all([]) is True

Tasks 1–5 have no dependencies, so all(... for d in []) checks an empty list. Python says "all of zero things are done" → True. That's why tasks with no dependencies are ready in the very first round — no special case needed.

Round by round, for our plan

RoundreadyAfter gatherKeys in results
1[1, 2, 3, 4, 5]tasks 1–5 COMPLETED1 2 3 4 5
2[6] — its deps 1, 2, 3 are donetask 6 COMPLETED1 … 6
3[7] — deps 4, 5, 6 are donetask 7 COMPLETED1 … 7
4while any(... PENDING ...) is now False → loop ends → return results

What one runner does: run_task

Python · researcher.py · run_task and helpers (simplified sketch)
# researcher.py — run ONE task with the right tool (same file as execute_plan)
from openai import AsyncOpenAI
from common import SubTask, TaskStatus
from tools.financial_data import get_financial_metrics
from tools.sec_filings import get_risk_factors
from tools.web_search import search_financial_news

NAMES = {"NVDA": "NVIDIA", "AMD": "AMD", "INTC": "INTEL"}


def extract_tickers(text: str) -> list[str]:
    """'Fetch Intel metrics' → ['INTC']"""
    up = text.upper()
    return [tk for tk, name in NAMES.items() if tk in up or name in up]


async def analyze_with_llm(instruction: str, context: str) -> str:
    """For 'thinking' tasks (6 and 7): reason over earlier results."""
    response = await AsyncOpenAI().chat.completions.create(
        model="gpt-4o",
        temperature=0,
        messages=[
            {"role": "system", "content": "You are a financial analyst. "
             "Use ONLY the data given. Quote numbers exactly."},
            {"role": "user", "content": f"{instruction}\n\nDATA:\n{context}"},
        ],
    )
    return response.choices[0].message.content


async def run_task(task: SubTask, results: dict[int, str]) -> tuple[int, str]:
    task.status = TaskStatus.RUNNING
    try:
        if task.dependencies:                                # ① a thinking task
            context = "\n\n".join(f"[Task {d}] {results[d]}"
                                  for d in task.dependencies)
            output = await analyze_with_llm(task.description, context)
        elif "financial_api" in task.data_sources:           # ② numbers
            ticker = extract_tickers(task.description)[0]
            metrics = await get_financial_metrics(ticker)
            output = metrics.model_dump_json()
        elif "sec_filing" in task.data_sources:              # ③ filings
            tickers = extract_tickers(task.description)
            output = "\n\n".join([await get_risk_factors(t) for t in tickers])
        else:                                                # ④ news
            output = await search_financial_news(task.description)
        task.status = TaskStatus.COMPLETED
    except Exception as e:                                   # ⑤ never crash
        task.status = TaskStatus.FAILED
        output = f"ERROR: {e}"
    return task.id, output
  1. Has dependencies → a "thinking" task (tasks 6 and 7). It collects the earlier results it depends on, labels each one [Task 1] …, and asks the LLM to reason over them. No tool call — just analysis.
  2. financial_api → numbers. extract_tickers finds the ticker in the description, the tool fetches a CompanyMetrics, and .model_dump_json() turns the form into JSON text — because the notebook stores text.
  3. sec_filing → filings for every company named in the description.
  4. Anything else → news search, using the task description as the search query.
  5. try / except — never crash. Any error sets the sticker to FAILED and returns "ERROR: …" as the result. Why so careful? If one job inside gather raises an error, gather raises it immediately and you lose the whole round's results. Catching the error inside each job means one broken courier never ruins the round.
🧠 Two bookmarks, one page

run_task changes task.status, and somehow execute_plan sees the change. How? plan.sub_tasks[1], tasks_by_id[2] and the task inside run_task are the same object — three bookmarks pointing at one page. Python variables are name tags, not photocopies. Change the page through one bookmark, and every bookmark shows it.

⚠️ Simplifications to upgrade later
  • extract_tickers is a simple name lookup: "Advanced Micro Devices" would be missed. Sturdier: add a ticker field to SubTask and let the planner fill it in.
  • Task 4 calls the SEC once per company, one after another. Those calls could be gathered too.
🧪 Simulation · the task board

Run the plan round by round — then break something

Each click does exactly one thing the code does. Gold rows = this round's ready list. Try the healthy run first, then make the AMD data API fail and watch the whole safety chain work: FAILED → stuck tasks → break → validator gaps → re-plan.


5.9Step 4 · The validator — a checklist, not an opinion

🧠 Analogy — the compliance checker

Before any memo leaves Future with Shivank Bank, a compliance officer walks the research board with a checklist and a calculator. She never says "looks fine to me". She asks yes/no questions: Is every card done? Is every company covered? Is this margin even possible? Same questions, same answers, every single time. That's our validator — and it contains no LLM at all.

Python · validator.py · validate_research
# validator.py — plain Python checks. No LLM anywhere in this file.
from common import CompanyMetrics, TaskStatus, ValidationResult


def validate_research(plan, results, required_tickers) -> ValidationResult:
    errors, warnings, gaps = [], [], []                  # ① three empty buckets

    # Check 1: did every task finish?
    for t in plan.sub_tasks:
        if t.status != TaskStatus.COMPLETED:
            gaps.append(f"Task {t.id} {t.status.value}: {t.description}")

    # Check 2: does every company appear somewhere in the findings?
    for ticker in required_tickers:
        if not any(ticker.upper() in r.upper() for r in results.values()):
            gaps.append(f"Missing data for {ticker}")

    # Check 3: are the numbers possible? are they plausible?
    for text in results.values():
        try:
            m = CompanyMetrics.model_validate_json(text)     # ② is it a metrics form?
        except ValueError:
            continue                                     #    news, filings… skip
        if m.gross_margin is not None and not -50 <= m.gross_margin <= 100:
            errors.append(f"{m.ticker}: gross margin {m.gross_margin}% is impossible")
        if (m.gross_margin is not None and m.operating_margin is not None
                and m.operating_margin > m.gross_margin):
            errors.append(f"{m.ticker}: operating margin is above gross margin")
        if m.pe_ratio is not None and not 0 < m.pe_ratio <= 150:
            warnings.append(f"{m.ticker}: P/E of {m.pe_ratio} is extreme"
                            " - check earnings")
        if m.revenue_growth is not None and abs(m.revenue_growth) > 300:
            warnings.append(f"{m.ticker}: revenue growth {m.revenue_growth}% - unit error?")

    return ValidationResult(                             # ③ the verdict
        is_valid=not errors and not gaps,
        errors=errors, warnings=warnings, gaps=gaps,
    )

Three buckets, three consequences

Errorsblocks the memoNumbers that are impossible: a 727% margin, operating profit bigger than gross profit. Something upstream is broken; the data can't be trusted.
Warningspassed onNumbers that are possible but unusual: AMD's P/E of 195. The run continues, and the memo must mention it.
Gapstriggers a re-planThings that are missing: a failed task, a stuck task, a company nobody fetched. Go back and get them.

The code, line by line

  1. Three empty lists — one per bucket. Each check drops messages into them.
  2. Check 1: != COMPLETED, not == FAILED. When AMD's task fails, tasks 6 and 7 never run — they stay PENDING forever. A check for "failed" would miss them. "Anything not completed is a gap" catches both. t.status.value turns the sticker into its text, "failed" or "pending".
  3. Check 2: is every ticker mentioned somewhere? For each ticker, look through all results (uppercased so case doesn't matter). any(...) stops at the first hit.
  4. Check 3, the trick: CompanyMetrics.model_validate_json(text) means "try to read this text as a metrics form". News and filing text isn't that JSON, so it raises an error (a kind of ValueError) and continue skips to the next result. The form itself tells us which results are metrics!
  5. The verdict: is_valid = not errors and not gaps. Notice: warnings never block. They're information for the reader, not a reason to redo the work.
RuleWhy it's thereBucketExample it catches
Gross margin outside −50%…100%Above 100% would mean costs were negative. Usually a decimal slipped.errorNVDA 727.0 instead of 72.7
Operating margin > gross marginOperating profit = gross profit minus more costs. It can't be bigger.errorIntel: gross 41.5%, operating 48.0%
P/E ≤ 0 or above 150Possible when earnings collapse — but the reader must know.warningAMD 195.3 after a weak year
Revenue growth beyond ±300%Possible, but far more often a units bug (thousands vs millions).warning1259% instead of 125.9%
Negative operating marginNot flagged on purpose. Loss-making companies are real.—A chipmaker in a bad year
⚠️ Why check 2 alone is not enough

We tested this. When AMD's metrics fetch failed, check 2 still passed for AMD: the news result says "AMD MI300 ramps", and even the error message contains the URL …?ticker=AMD. A simple text search can be fooled. Check 1 caught the problem instead. That's why good validators layer several simple checks — each one covers another's blind spot.

💡 Why not just ask the LLM "does this look right?"

Remember the three-attempt story from 5.2: the LLM checker approved invented numbers and rejected correct ones. The Python checker runs in about a millisecond, costs nothing, and gives the same answer every time. Use code for facts; use the LLM for words.

🧪 Simulation · be the data, fool the validator

Change the numbers — the same rules as the Python code run instantly

Start with a preset, then edit any box. Leave a box empty for "unknown" (None). Untick "Fetched?" to make that company's task fail.

CompanyCo.Fetched?OK?Growth %Gross margin %Gross %Operating margin %Oper. %P/E

5.10Step 5 · The synthesizer and the orchestrator

🧠 Analogy — the memo writer's folder

The memo writer receives a folder: every finding, labelled by task, plus the compliance officer's sticky notes ("AMD's P/E is extreme — mention it"). She must fill in the bank's memo template, quote numbers exactly, and say how confident she is. A thin folder or lots of sticky notes → lower confidence.

Python · synthesizer.py · synthesize_report (simplified sketch)
# synthesizer.py — findings + the checker's notes → the final memo
from openai import AsyncOpenAI
from common import ResearchReport, ValidationResult

SYNTH_PROMPT = """You are a senior equity research analyst.
Write an investment research memo using ONLY the findings provided.
- Quote numbers exactly as given. Never invent a number.
- If data is missing, say so plainly.
- Mention every validation warning where it is relevant.
- confidence_score (0 to 1) must reflect how complete and clean the data is."""


async def synthesize_report(question: str, results: dict[int, str],
                            validation: ValidationResult) -> ResearchReport:
    findings = "\n\n".join(f"[Task {tid}]\n{text}"           # ① the research folder
                           for tid, text in sorted(results.items()))
    notes = "\n".join(                                        # ② the checker's notes
        [f"WARNING: {w}" for w in validation.warnings]
        + [f"GAP: {g}" for g in validation.gaps]
        + [f"ERROR: {e}" for e in validation.errors]
    ) or "No issues found."
    response = await AsyncOpenAI().chat.completions.parse(    # ③ fill the memo form
        model="gpt-4o",
        temperature=0,
        messages=[
            {"role": "system", "content": SYNTH_PROMPT},
            {"role": "user", "content": f"QUESTION:\n{question}\n\n"
             f"FINDINGS:\n{findings}\n\nVALIDATION NOTES:\n{notes}"},
        ],
        response_format=ResearchReport,
    )
    return response.choices[0].message.parsed
  1. The folder. sorted(results.items()) lists the notebook in task order 1 → 7. Each finding gets a [Task n] label, so the memo can point back to where a number came from.
  2. The sticky notes. Three list comprehensions build lines like WARNING: AMD: P/E of 195.3 is extreme…, and + glues the lists together. If there are no notes at all, the joined text is empty — and an empty string counts as "false" in Python, so or swaps in "No issues found.".
  3. Fill the memo form. The same .parse(..., response_format=...) trick as the planner, this time with ResearchReport. The LLM can't hand back a memo with a missing section.
💡 Hiding problems is the real danger

Passing the warnings into the prompt is what makes the memo honest: it says "AMD's P/E of 195 reflects depressed earnings after a weak year" instead of quietly presenting 195 as normal. In our sample run the memo came back with 85% confidence because of that one warning. Many teams go one step further and compute the confidence score in code (e.g. start at 100% and subtract for each warning and gap) — the same "code for facts" lesson again.

The orchestrator — the desk manager

Python · deep_search_agent.py · the whole loop
# deep_search_agent.py — the manager that runs the whole loop
import asyncio
from pathlib import Path
from common import ResearchReport
from planner import create_research_plan
from researcher import execute_plan
from validator import validate_research
from synthesizer import synthesize_report

MAX_REPLAN_ATTEMPTS = 2


async def deep_search(question: str, tickers: list[str]) -> ResearchReport:
    for attempt in range(MAX_REPLAN_ATTEMPTS + 1):              # attempt = 0, 1, 2
        plan = await create_research_plan(question)             # Phase 1: plan
        results = await execute_plan(plan)                      # Phase 2: execute
        validation = validate_research(plan, results, tickers)  # Phase 3: check
        if validation.is_valid:
            break                                               # all good → leave
        elif attempt < MAX_REPLAN_ATTEMPTS:                     # tries left → re-plan
            problems = validation.gaps + validation.errors
            question += "\nAddress these gaps:\n" + "\n".join(problems)
    return await synthesize_report(question, results, validation)   # Phase 4


if __name__ == "__main__":
    QUESTION = (
        "Analyze NVIDIA's financial performance and competitive position in "
        "the AI chip market. Compare with AMD and Intel on revenue growth, "
        "profitability, and key risk factors. Produce a structured "
        "investment research memo."
    )
    report = asyncio.run(deep_search(QUESTION, ["NVDA", "AMD", "INTC"]))
    Path("output").mkdir(exist_ok=True)
    Path("output/report.json").write_text(report.model_dump_json(indent=2))
    print(report.title)
    print(report.executive_summary)
    print(f"Confidence: {report.confidence_score:.0%}")
  1. range(MAX_REPLAN_ATTEMPTS + 1) is range(3), so attempt takes the values 0, 1, 2: one first try plus two re-plans.
  2. Each attempt runs three phases in order: plan → execute → validate. Each phase's output is the next phase's input — exactly the relay race from 5.5.
  3. if validation.is_valid: break — happy path. break jumps straight out of the loop to the synthesizer.
  4. elif attempt < MAX_REPLAN_ATTEMPTS — not valid, but tries are left. We add the problems to the question. Why the question? The planner has no memory between calls — the question text is its memory. It's like sending the desk head a sticky note: "Last time: AMD numbers missing, tasks 6 and 7 stuck."
  5. Why gaps + errors? If we sent only the gaps, a run with errors but no gaps would hand the planner an empty "Address these gaps:" list — and it would make the same plan again.
  6. The synthesizer runs after the loop, always. A small Python fact makes this work: variables created inside a for loop still exist after it ends. So results and validation hold the last attempt's values. Even when all three attempts fail, the PM still gets a memo — one that lists the gaps and carries a lower confidence score.
  7. The __main__ block runs only when you start the file directly. asyncio.run(...) starts the async world, and model_dump_json(indent=2) saves the memo as readable JSON in output/.
⚠️ An honest limitation

Each new attempt starts from scratch: it re-plans and re-fetches everything, even the tasks that worked. A cheaper upgrade keeps the successful results and re-runs only what failed. Fine for learning; worth fixing before you run this on 500 companies a day.

The three possible endings

SituationAttemptsWhat the PM receives
Everything works1Memo at ~85% confidence; the AMD P/E warning is mentioned
AMD's API hiccups once2 — the second plan "knows" about the gapThe same full memo, about 30 seconds later
AMD's API is down all day3 (the maximum)A memo that openly lists the missing AMD data, with a clearly lower confidence score

We ran all three scenarios with mock data APIs and a mock LLM to check the loop behaves exactly like this.

Variable cheat-sheet — the whole run on one card

VariableTypeMade byUsed byExample
questionstryou (grows on each re-plan)planner, synthesizer"Analyze NVIDIA's…"
tickerslist[str]youvalidator["NVDA", "AMD", "INTC"]
attemptintthe for loopthe elif0, 1 or 2
planResearchPlanplannerresearcher, validator7 sub-tasks
readylist[SubTask]researcher, each roundgathertasks 1–5, then 6, then 7
resultsdict[int, str]researchervalidator, synthesizer{1: '{"ticker":"NVDA",…}', …}
validationValidationResultvalidatororchestrator, synthesizervalid · 1 warning
reportResearchReportsynthesizeryou, output/report.jsonthe memo, 85% confidence

What comes out — a sample memo (shortened)

# NVIDIA vs AMD vs Intel: AI Chip Market Investment Analysis ## Executive Summary NVIDIA maintains dominant positioning in the AI accelerator market with 80%+ data center GPU share. FY2024 revenue reached $60.9B (+125.9% YoY). AMD's MI300 series is gaining traction as the primary alternative, while Intel focuses on foundry services. ## Key Metrics Comparison | Metric | NVDA | AMD | INTC | |----------------|---------|---------|---------| | Revenue | $60.9B | $22.7B | $54.2B | | Revenue Growth | +125.9% | -3.9% | -14.0% | | Gross Margin | 72.7% | 46.1% | 41.5% | | P/E Ratio | 68.5x | 195.3x | 95.2x | ## Competitive Analysis (excerpt) … AMD's P/E of 195.3x is extreme: it reflects earnings that were depressed after a weak year, not an unusually high price. … … ranked risk factors · conclusion · sources … Confidence: 85%

Sample output from one run — wording and figures change with live data. The highlighted line exists only because the validator's warning was passed into the synthesizer's prompt.


Section 5 · Part 3 — Make it yours

Hands-on lab, production lessons and the wider world

5.11Lab · the same agent, rebuilt with PydanticAI

You've built every part with the raw OpenAI client, so nothing is magic any more. Now we swap in PydanticAI (you met it in Section 3) for the two LLM calls. You get automatic retries when the LLM's answer doesn't fit the form, and you can switch between OpenAI and Anthropic by changing one string. The tools, the researcher loop and the validator don't change at all.

1 · Set up

Terminal · install (Python 3.11+)
pip install pydantic-ai httpx pydantic python-dotenv tavily-python

# optional: cost tracking across the whole pipeline
pip install "pydantic-deep[middleware]"
.env · in the src/ folder (never commit this file)
OPENAI_API_KEY=sk-...
FINANCIAL_DATASETS_API_KEY=...
TAVILY_API_KEY=tvly-...
SEC_EDGAR_EMAIL=your-email@example.com

2 · The project folder

src/ ├── common.py # the forms (5.5) + model names ├── tools/ │ ├── financial_data.py # get_financial_metrics (5.7, unchanged) │ ├── sec_filings.py # get_risk_factors (5.7, unchanged) │ └── web_search.py # search_financial_news (5.7, unchanged) ├── planner.py # PydanticAI Agent → ResearchPlan ├── researcher.py # execute_plan + run_task (5.8, unchanged) ├── validator.py # plain Python checks (5.9, unchanged) ├── synthesizer.py # PydanticAI Agent → ResearchReport ├── deep_search_agent.py # the loop (5.10, unchanged) └── output/ # saved memos (JSON)
Terminal · run it
cd src
python deep_search_agent.py

3 · What changes: only the LLM calls

Python · common.py · lab additions
# common.py — lab version: add these lines at the top
from dotenv import load_dotenv

load_dotenv()                          # copies the .env values into os.environ

PLANNING_MODEL = "openai:gpt-4o"       # "provider:model" in one string
SYNTHESIS_MODEL = "openai:gpt-4o"
# Prefer Claude? Set ANTHROPIC_API_KEY and use "anthropic:<model name>",
# e.g. "anthropic:claude-sonnet-5-5" — check your provider's current names.
Python · planner.py · lab version
# planner.py — lab version, with PydanticAI
from pydantic_ai import Agent
from common import PLANNING_MODEL, ResearchPlan

PLANNER_SYSTEM_PROMPT = """You are a financial research planner. ...
(exactly the same text as PLANNER_PROMPT above)"""

planner_agent = Agent(
    model=PLANNING_MODEL,
    system_prompt=PLANNER_SYSTEM_PROMPT,
    output_type=ResearchPlan,             # the form the answer must fit
    retries=2,                            # wrong shape? sent back, up to 2 times
    model_settings={"temperature": 0},
)


async def create_research_plan(question: str) -> ResearchPlan:
    result = await planner_agent.run(question)
    return result.output                  # already a ResearchPlan object
Step-by-step version (5.6)Lab version
Who makes the callAsyncOpenAI().chat.completions.parse(...)planner_agent.run(question)
How you say the shaperesponse_format=ResearchPlanoutput_type=ResearchPlan
Getting the object outresponse.choices[0].message.parsedresult.output
Answer doesn't fit the formyou handle itsent back to the LLM with the error, up to retries=2 times
Switch to Clauderewrite with another SDKchange one string in common.py
🧠 What retries=2 feels like

A clerk hands back a loan form with a red circle: "tenure must be a number — please fix". PydanticAI does exactly that: if the LLM's JSON fails the Pydantic check, it sends the error message back and asks for a corrected answer — up to two times — before giving up.

Python · synthesizer.py · lab version (the same idea)
# synthesizer.py — lab version: only the LLM call changes
from pydantic_ai import Agent
from common import SYNTHESIS_MODEL, ResearchReport, ValidationResult

synth_agent = Agent(
    model=SYNTHESIS_MODEL,
    system_prompt=SYNTH_PROMPT,           # same prompt as before
    output_type=ResearchReport,
    retries=2,
    model_settings={"temperature": 0},
)


async def synthesize_report(question: str, results: dict[int, str],
                            validation: ValidationResult) -> ResearchReport:
    findings = ...                        # same two lines as before
    notes = ...
    result = await synth_agent.run(
        f"QUESTION:\n{question}\n\nFINDINGS:\n{findings}"
        f"\n\nVALIDATION NOTES:\n{notes}"
    )
    return result.output
💡 Test the wiring for free, before spending a cent

PydanticAI ships a fake model, TestModel, that returns dummy-but-valid data in the right shape. Use it to check your imports and plumbing without calling a real LLM. (Your .env still needs an OPENAI_API_KEY line so the agent can be created — but no request is sent and no tokens are used.)

Python · try_planner.py · a free dry run
# try_planner.py — test the wiring for free: no real LLM call
import asyncio
from pydantic_ai.models.test import TestModel
from planner import planner_agent, create_research_plan


async def main():
    with planner_agent.override(model=TestModel()):    # a fake, free "LLM"
        plan = await create_research_plan("Compare NVIDIA with AMD")
    print(plan)            # dummy text, but a perfectly valid ResearchPlan


asyncio.run(main())

4 · What a run does — the eight steps

  1. Takes the research question (default: the NVIDIA vs AMD vs Intel question).
  2. Plans: planner_agent returns a ResearchPlan.
  3. Executes the sub-tasks in waves — in parallel where the graph allows.
  4. Validates the findings with plain Python checks.
  5. Re-plans if gaps or errors are found — up to two more tries.
  6. Synthesizes a structured memo: synth_agent returns a ResearchReport.
  7. Prints a cost summary (only if the optional pydantic-deep[middleware] is installed).
  8. Saves the memo to output/ — about 30 seconds after you pressed Enter.
🛠️ Homework — pick one extension
  • Dynamic peers: given only "Analyze NVIDIA", let the planner add AMD, Intel, Broadcom and Qualcomm itself.
  • History: compare today's margins with the 3-year and 5-year averages.
  • Human-in-the-loop gate: pause after planning so an analyst approves the plan before any data is fetched.
  • Browser tool: use Playwright to read investor-relations pages that block API access.
  • JSON for other systems: feed the ResearchReport into a risk dashboard.
  • MCP: wrap the three tools as MCP servers (Section 3) so other teams can reuse them.
  • Sub-agents: replace the hand-written loop with create_deep_agent from pydantic-deep.
  • A Claude skill: write a SKILL.md that runs python deep_search_agent.py with the analyst's question, so analysts can just type "research NVIDIA vs AMD".

5.12From demo to production

💬 The one sentence to remember

"The model is not your product. The experience around the model is your product."

— Nicolas Bustamante, founder of the financial research platform Fintool

The LLM is one component. Whether analysts actually trust and use the tool depends on everything around it. Six lessons from teams running deep search in production:

1 · Every user gets a sealed roomEach research session runs in isolation; users can only reach their own data. In a bank this is non-negotiable — it keeps the information barriers between teams that regulators require.
2 · Skills, not codeAnalysts describe a method in a Markdown file ("Earnings surprise: fetch consensus EPS, compare with reported, compute surprise %"). The agent reads it as a plan. New method → new file, no code change.
3 · Store everything, durablyEvery intermediate result goes to cloud storage (e.g. Amazon S3) first, then into a database. You can replay and audit any run.
4 · Survive crashesRuns take 30 seconds to several minutes. A workflow engine such as Temporal saves progress, so a crash resumes where it stopped instead of starting over.
5 · Test on every changeRun a large suite of finance test questions (Fintool runs about 2,000) on every code change, and block the change if scores drop by more than 5%.
6 · Small model for small jobsSend simple extraction ("what was AMD's revenue?") to a small, cheap model and hard reasoning to a large one. Reported savings: 60–70%, with no measurable loss in quality.

Context: the agent's desk gets messy

A multi-company study can pile up 50,000–100,000+ tokens of filings, transcripts and news. Four ways teams keep the desk clear:

Summarise as you goSqueeze 20,000 tokens of 10-K into 500 tokens of key facts with a cheap model before the next phase. Like writing a one-page summary of a thick report.
File it awayWrite results to files and read back only what's needed. A filing cabinet instead of a cluttered desk.
Clear the deskKeep only the N most recent tool results (one open-source agent keeps 5). Old papers go in the drawer.
Send an internA sub-agent studies one 10-K in its own fresh context and returns only a summary. The intern reads 200 pages; you read one.

What does one research run cost?

StepTokensCost (GPT-4o-class rates)
Planning~2,000~$0.01
Tool execution (5 calls)~15,000~$0.08
Validation~3,000~$0.02
Synthesis~8,000~$0.04
Total per research run~28,000~$0.15

Estimates assuming efficient prompts and model routing; prices change, so check your provider's current price list. Our validator itself uses no LLM — the validation line covers lighter LLM checks of report quality. Unoptimised setups often cost 3–5× more.

🧪 Simulation · the monthly bill
100
💡 Five ways to cut the bill
  • Model tiering — cheap models for simple steps.
  • Caching — a company's filed numbers for a quarter never change, so cache them forever.
  • Shorter prompts — the planner prompt should be tight, not chatty.
  • Share common context — explain the industry once, not once per company.
  • Token budgets — cap each sub-task; summarise a 10,000-token filing to 500 tokens.

How do you know the memo is right?

DimensionQuestion it asksHow to test it
Factual accuracyAre the numbers correct?Compare with known values from a database or benchmark
CompletenessIs every company, metric and section there?A checklist — in code
StructureIs it organised and coherent?A separate LLM as judge
CitationsCan every claim be traced to a source?Check links and attributions
ConsistencyDoes section 2 contradict section 4?Cross-check numbers quoted in different places
⚠️ Pretty is not the same as right

FinDeepResearch, a benchmark of 64 companies across 8 markets and 4 languages (15,808 grading items), found that even the best agents struggle to be well-structured and accurate at the same time. Beautifully formatted reports tended to contain invented numbers; careful ones tended to be messy. Never judge a memo by its formatting.

💡 Your first evaluation, this week

Write a golden set of 20–30 research questions whose answers a human analyst has checked. Run the agent on them after every prompt or model change. Check the numbers automatically first; use an LLM judge only for the writing quality. If scores drop, don't ship.

5.13Who else builds this

Three open-source projects faced the same problems you just solved — and chose differently:

Dexterspecialist agentsFour agents (plan, act, validate, answer). One financial_search tool routes internally to the right source, so the agent's tool list stays short. Logs every step to a JSONL "scratchpad" for audit, keeps only the 5 latest tool results when context fills up, and works with many LLM providers. Price: more tokens.
AI Alliance Deep Research Agentorchestrator + MCPThe project behind the three-attempt story in 5.2: naive → over-engineered → right-sized. Plans a task graph up front, runs tools through MCP, checks each step with code and re-plans only on failure — the same design you just built.
ai-hedge-fundmany viewpointsAround twenty analyst agents, each with a famous investing style, study the same stock; a portfolio-manager agent combines their views. Lesson: several lenses beat one — at the cost of many more LLM calls per stock.
Persona (style inspired by)Looks for
Damodaran · valuationDCF, intrinsic value, growth vs value
Graham · valueMargin of safety, book value, conservative numbers
Ackman · activistFixable operations, hidden value, catalysts
Wood · innovationDisruptive technology, market size, revenue growth
Burry · contrarianCrowded trades, hidden risks, short ideas
Munger · qualityMoats, management quality, capital allocation

Commercial platforms, in one line each

  • Fintool — reported 98% accuracy on a 100-question set from FinanceBench (a standard finance Q&A test), against 45% for a leading general-purpose assistant, in the company's own benchmark. Its secret is the boring part: data normalisation, fiscal-period alignment and ~2,000 tests.
  • AlphaSense — deep research agents over 500 million+ business documents and transcripts, for 7,000+ enterprise customers. Lesson: agents shine brightest on curated, private document collections.
  • Google Finance Deep Search — deep search for everyday investors' questions, powered by Gemini. Deep search is becoming a mainstream expectation.
  • Claude for Financial Services — Claude connected directly to data providers such as FactSet, Morningstar, PitchBook, S&P Global and Daloopa, with links back to sources. Reported results: AIG made underwriting reviews 5× faster while raising data accuracy from 75% to over 90%; Norway's sovereign wealth fund (NBIM) estimated ~20% productivity gains, about 213,000 hours saved.

Figures are as reported by the companies themselves.


Wrap-up

What to remember

  1. Deep search = plan → execute → validate → (re-plan) → synthesize. RAG answers a question; deep search does the research.
  2. The plan is a dependency graph. No dependencies → run together with asyncio.gather; dependencies → wait your turn.
  3. Pydantic models are the forms passed between parts. Unknown is None, never 0.
  4. Tools translate. Messy API data becomes clean, labelled numbers in millions and percentages before any LLM sees it.
  5. Failures become notes, not crashes: FAILED → gap → re-plan, at most twice, and the memo admits what's missing.
  6. Code checks facts, the LLM writes words. Errors block, warnings travel into the memo, gaps trigger a re-plan.
  7. 80% of the work is data: units, fiscal calendars, footnotes. The model is not the product.

QuizCheck yourself