Future with Shivank · Hands-on track
Agent Frameworks & a Fundamental Analysis System Section 3 & Section 4 — remember the superpowers, then build an "analyst in a box"
Section 3 is a fast tour: ten agent frameworks, each boiled down to the one superpower worth remembering. Section 4 is the main event: a five-agent system that reads a company's financial statements, news and risks, values it two ways, and writes a full investment brief in under a minute — with every piece of code explained.
How to read the coloured boxes:
You need only OPENAI_API_KEY and pip install openai-agents yfinance. All market data comes free from Yahoo Finance through yfinance. As before: run code in a fresh notebook or terminal, and expect live numbers to differ from the samples here.
Section 3
Agent frameworks — one superpower each
Ten frameworks is too many to memorise feature by feature, and you don't need to. They all do the basics. Each is famous for one thing. Learn that one thing, plus when it saves you, and you can hold your own in any architecture meeting.
Tool calling · the think → act → observe loop · conversation state · retries · sequential/parallel steps · RAG connectors · JSON output · logging. You've used all of these in the AWS module and in Sections 1–2. Ignore any sales pitch built on them.
3.1Banks already run agents (the opening hook)
Before any framework talk, show learners this isn't a toy. Publicly reported examples:
| Institution | What they reportedly run |
|---|---|
| JPMorgan Chase | "LLM Suite": frontier models for ~250,000 employees, behind the bank's own governance layer; agentic features for multi-step tasks from 2025 |
| Citi | Agentic features in "Stylus Workspaces", rolled out to ~182,000 employees |
| Goldman Sachs | Piloting an autonomous AI software engineer working under supervision next to ~12,000 human developers |
| BNY | A growing team of AI "digital employees" on its internal Eliza platform |
| BlackRock | Agents that read research notes, filings and emails overnight to surface portfolio insights |
| Man Group | An agentic research pipeline that proposes trading ideas, writes the code and back-tests them |
Every one of these is the same recipe you're learning: models wrapped in orchestration, guardrails and audit logs. Frameworks are that wrapper.
3.2The ten superpowers
First, the one-word version — this strip alone is worth remembering:
Click a need — the frameworks built for it light up
"Which framework is best at agents talking to each other?" — AutoGen (now the Microsoft Agent Framework) and CrewAI. AutoGen makes agents hold an actual meeting: a group chat where the next speaker can be picked by an LLM, and a human can join as a full participant. CrewAI makes them a team with job titles that delegate to each other. Use them when your workflow already looks like a committee. Just know the meeting has a price — see 3.4.
3.3Same task, four frameworks — spot the difference
The task: fetch Apple's and JPMorgan's price and EPS, compute their P/E ratios, write a short comparison memo. Same model, same two tools (get_stock_data, compute_pe_ratio), same prompt, same mock data — only the framework changes.
Apple: $195.30 ÷ $6.67 EPS = P/E 29.3. JPMorgan: $148.70 ÷ $12.61 = P/E 11.8. Investors pay ~$29 for each $1 of Apple's yearly profit (they expect growth) and ~$12 for JPMorgan's (a value-priced bank). P/E = "how many years of today's profit you're paying for".
from agents import Agent, Runner, function_tool
agent = Agent(
name="Financial Analysis Agent",
instructions=system_message,
tools=[get_stock_data, compute_pe_ratio],
model="gpt-5-mini",
)
result = Runner.run_sync(agent, input_message)
print(result.final_output) # a prose memo; steps appear in OpenAI tracingfrom langchain.agents import create_agent
agent = create_agent(
model="openai:gpt-5-mini",
tools=[get_stock_data, compute_pe_ratio],
system_prompt=system_message,
)
output = agent.invoke({"messages": [{"role": "user", "content": input_message}]})
print(output["messages"][-1].content) # last message = the memo
# Its log shows every tool call: [Tool: compute_pe_ratio] args={'price': 195.3, 'eps': 6.67}analyst_agent = AssistantAgent(
name="FinancialAnalyst",
model_client=OpenAIChatCompletionClient(model="gpt-5-mini"),
tools=[get_stock_data_tool, compute_pe_tool],
system_message=system_message,
)
async def main():
team = RoundRobinGroupChat(
participants=[analyst_agent], # a meeting with one member
termination_condition=MaxMessageTermination(10), # end the meeting after 10 messages
)
result = await team.run(task=input_message)
asyncio.run(main())from pydantic import BaseModel, Field
from pydantic_ai import Agent
class InvestmentMemo(BaseModel): # the "form" every answer must fill in
aapl_pe: float = Field(description="Computed P/E for AAPL")
jpm_pe: float = Field(description="Computed P/E for JPM")
memo: str = Field(description="Short comparative memo")
agent = Agent("openai:gpt-5-mini", system_prompt=system_message, output_type=InvestmentMemo)
result = agent.run_sync(input_message)
print(result.output.model_dump_json(indent=2)) # validated JSON, not proseModel names retire quickly — if gpt-5-mini is gone when you run this, use the current small model.
3.4The cost surprise: architecture is a pricing decision
The same 10,000 questions a day can cost a few hundred dollars a month — or tens of thousands. The difference is not the framework's licence (they're free) — it's how many tokens your design burns. Play with it:
What does Future with Shivank Bank pay per month?
Uses the measured token counts from 3.3 and illustrative late-2025 prices: small model $0.25 in / $2 out, flagship $1.25 in / $10 out, per million tokens. Check current prices before budgeting.
- Tier models: big model to plan and write the final answer, small model for routing and summaries.
- Compress context: summarise old turns instead of resending everything.
- Prompt caching: keep the system prompt and tool definitions identical at the start of every call — cached input is billed at a 50–90% discount.
- Batch: overnight reports through batch APIs cost about half.
- Cache in your app: don't fetch the same price twice (Section 4 does exactly this).
- Budget and alert: per-agent token limits — reasoning models can hide big "thinking" bills behind short answers.
3.5Frameworks aren't rivals — they're layers
Few banks run just one. A typical production stack picks one framework per layer, and two open protocols connect everything:
Prototype in something flexible and readable (CrewAI or LangGraph) → prove it on one real workflow → move to production on something with tracing and guardrails built in (OpenAI Agents SDK, Google ADK, Claude Agent SDK), keeping the business logic portable. And whatever you pick: every claim needs a source, every output needs a schema, and any action with money or regulatory impact needs a human approval step.
3.6Game: pick the framework
Versions and features move fast; treat this as a snapshot. The superpowers change much more slowly than the version numbers.
Section 4 · The main project
Build an "analyst in a box": the fundamental analysis system
A human analyst needs 2–4 hours per company: open filings, copy numbers into a spreadsheet, compute ratios, read news, build a valuation model, write a memo. For a 50-stock portfolio that's weeks. Our system does the first draft in under 60 seconds — five specialist agents and one orchestrator, all on the OpenAI Agents SDK you already know.
Why multi-agent beats one giant agent, agents-as-tools vs handoffs, @function_tool, Agent(...) and Runner.run(...). Here we spend the time on this project's code and the finance needed to read it.
What comes out at the end (a real sample run on Apple)
The system said STRONG SELL while the news mood was BULLISH. Numbers said "too expensive", headlines said "exciting". Which is right? That disagreement is exactly where a human analyst earns their salary — the system's job is to put both views on one page, with every number traceable.
4.1Just-enough finance (five ideas, nothing more)
You don't need a finance degree to follow this code. You need these five ideas. Everything else is in an optional box below — glance at it, don't memorise it.
The labels the code passes around — these strings flow between agents, so learn them as plain words:
| Who decides it | Scale |
|---|---|
| FinancialDataAgent | STRONG · SOLID · MIXED · WEAK |
| ValuationAgent (DCF and peers) | SIGNIFICANTLY UNDERVALUED · SLIGHTLY UNDERVALUED · FAIRLY VALUED · SLIGHTLY OVERVALUED · SIGNIFICANTLY OVERVALUED |
| RiskAgent | LOW · MODERATE · ELEVATED · HIGH |
| NewsAndSentimentAgent | STRONGLY BULLISH · BULLISH · NEUTRAL · BEARISH · STRONGLY BEARISH |
| ReportWriterAgent (final) | STRONG BUY · BUY · HOLD · SELL · STRONG SELL |
The ratio dictionary Optional · glance only
The tools fetch all of these automatically. You only need to recognise the names when you see them in the JSON. Bold = the ones the code actually uses in a rule.
| Family | Ratio | One-line meaning |
|---|---|---|
| Valuation cheap or expensive? | P/E trailing | Price ÷ last year's EPS. "$25 for every $1 earned." |
| P/E forward | Price ÷ next year's expected EPS. Lower than trailing = profits expected to grow. | |
| P/B | Price ÷ book value (accounting net worth). | |
| P/S | Price ÷ sales. Useful when a company has no profits yet. | |
| EV/EBITDA | Whole-business price (incl. debt, minus cash) ÷ operating earnings. Fair across companies with different debt. | |
| EV/Revenue | Like P/S but for the whole business. | |
| Profitability | Gross / operating / net margin | Of every $100 sold, what's left after production cost / running costs / everything. |
| ROE | Profit ÷ owners' money. Above 15% is strong (watch out for buybacks, as you saw in Section 2). | |
| ROA | Profit ÷ everything owned. | |
| Liquidity & leverage | Current ratio | Short-term assets ÷ bills due this year. Below 1.0 = pressure. |
| Quick ratio | Same, without inventory. | |
| Debt/Equity | Borrowed money ÷ owners' money. Above 2× is high — except banks and utilities, which run on debt by design. | |
| Growth | Revenue growth YoY, 3-year growth, earnings growth | Is the business growing, flat or shrinking? |
| Cash flow | FCF, FCF yield, operating cash flow | FCF yield = FCF ÷ market value — like the interest rate a bond pays you. |
| Dividends | Yield, payout ratio, annual rate | Payout above 100% = paying out more than it earns; usually not sustainable. |
The non-number side (what agents read from news): a moat (an advantage competitors can't easily copy, like network effects), management quality, industry trends, and market sentiment.
4.2The architecture: an equity research team in code
| Agent | Human it replaces (the mechanical part only) | Its tools |
|---|---|---|
| FinancialDataAgent | Junior analyst building the spreadsheet | get_income_statement get_balance_sheet get_cash_flow_statement compute_key_ratios |
| NewsAndSentimentAgent | News-desk analyst watching headlines | search_recent_news analyze_sentiment |
| RiskAgent | Risk manager — the professional sceptic | get_balance_sheet compute_key_ratios search_recent_news (shared) |
| ValuationAgent | Valuation specialist who owns the models | run_dcf_model get_peer_multiples |
| ReportWriterAgent | Managing director writing the memo | none — pure synthesis |
| OrchestratorAgent | Director of research assigning work | the five agents above, each wrapped with .as_tool() |
Run the pipeline for AAPL — watch the map and the trace log
The strip inside the panel is a mini version of the map above: gold = working now, green = finished.
How to check parallelism: run with the --trace flag. If all three CALL lines appear before any OUTPUT, the SDK ran them together. If they alternate, the LLM ran them one at a time — and your prompt should say more clearly that they're independent. The SDK never forces parallel calls; the LLM decides, and your prompt persuades.
Where everything lives
Tools are the hands (plain Python that fetches and calculates). Agents are the brains (an LLM + instructions + which hands they may use). The orchestrator is the manager. We'll go in that order: tools → agents → running it.
4.3The financial tools (tools/financial_tools.py)
Every tool in the project follows three rules — once you see them, every tool reads the same way:
- Return a JSON string. The SDK hands tool results to the LLM as text; JSON keeps that text structured and unambiguous.
- Never crash. Delisted ticker? API limit? Catch the error and return
{"error": ...}as JSON. The agent reads it and the pipeline carries on. - Check the cache first. Two agents call the same tools. The first call fetches; the second gets the stored answer.
The small helpers every tool uses
The project ships its own helpers; these short versions behave the same way so you can read the tools without guessing:
import json, math
import yfinance as yf
from agents import function_tool
class _SimpleCache:
"""Remembers tool results for this run, keyed by (tool name, ticker)."""
def __init__(self):
self._store = {}
def get(self, key):
return self._store.get(key) # None = never seen this key
def store(self, key, value):
self._store[key] = value
_cache = _SimpleCache()
def _safe_float(v):
"""Anything → float, or None if it isn't a usable number."""
try:
f = float(v)
return None if math.isnan(f) else f
except (TypeError, ValueError):
return None
def _millions(v):
"""Raw dollars → millions: 383285000000 → 383285.0"""
f = _safe_float(v)
return round(f / 1_000_000, 1) if f is not None else None
def _extract_row(df, *names, col):
"""Value of the first row name that exists in the table (in millions)."""
for name in names: # e.g. try "Operating Income", then "EBIT"
if name in df.index:
return _millions(df.loc[name, col])
return NoneYahoo doesn't label every company's rows identically — one company's "Operating Income" is another's "EBIT". _extract_row(fin, "Operating Income", "EBIT", col=col) is like asking "is Rahul here? If not, is R. Sharma here?" — it takes whichever name answers first.
Tool 1 · get_income_statement
@function_tool
def get_income_statement(ticker: str) -> str:
"""
Fetch the annual income statement for a given stock ticker.
Returns revenue, gross profit, operating income, EBITDA, net income,
and EPS for the last 4 fiscal years. All monetary values are in millions USD.
Args:
ticker: The stock ticker symbol, e.g. 'AAPL', 'MSFT', 'GOOGL'.
"""
_key = ("get_income_statement", ticker.upper()) # ① cache key
_hit = _cache.get(_key)
if _hit is not None:
return _hit # already fetched this run
try:
stock = yf.Ticker(ticker.upper())
fin = stock.financials # ② rows = line items, columns = fiscal years
if fin is None or fin.empty:
return json.dumps({"error": f"No income statement data found for {ticker}"})
currency = stock.info.get("financialCurrency", "USD")
result: dict = {
"ticker": ticker.upper(),
"company_name": stock.info.get("longName", ticker.upper()),
"currency": currency,
"unit": f"millions {currency}",
"annual_data": {}, # ③ filled year by year
}
for col in fin.columns[:4]: # the newest 4 fiscal years
year = str(col.year) # Timestamp('2025-09-30') → "2025"
result["annual_data"][year] = {
"revenue": _extract_row(fin, "Total Revenue", col=col),
"gross_profit": _extract_row(fin, "Gross Profit", col=col),
"operating_income": _extract_row(fin, "Operating Income", "EBIT", col=col),
"ebitda": _extract_row(fin, "EBITDA", col=col),
"net_income": _extract_row(fin, "Net Income", col=col),
"r_and_d": _extract_row(fin, "Research And Development", col=col),
}
info = stock.info # ④ today's headline numbers
result["eps_ttm"] = _safe_float(info.get("trailingEps"))
result["eps_forward"] = _safe_float(info.get("forwardEps"))
result["revenue_ttm_M"] = _millions(info.get("totalRevenue"))
result["gross_margin_pct"] = _safe_float(info.get("grossMargins", 0)) and round(info.get("grossMargins", 0) * 100, 2)
result["operating_margin_pct"] = round(info.get("operatingMargins", 0) * 100, 2) if info.get("operatingMargins") else None
result["net_margin_pct"] = round(info.get("profitMargins", 0) * 100, 2) if info.get("profitMargins") else None
output = json.dumps(result, indent=2, default=str) # ⑤ dict → JSON text
_cache.store(_key, output) # remember it
return output
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker}) # ⑥ never crash the pipeline- Cache key
("get_income_statement", "AAPL")— a tuple of tool name + ticker, so different tools and tickers never collide. stock.financialsis a pandas table: each row is a line item ("Total Revenue", "Net Income"…), each column is a fiscal-year end date, newest first. See the picture below.- The loop turns that table into a nested dictionary keyed by year.
col.yearpulls the year out of the date. stock.infois a different source: one big dictionary of ready-made "right now" numbers (EPS, margins, price…).default=strtellsjson.dumps: "if you meet something you can't write as JSON (like a date), just turn it into text".- Any failure becomes a JSON error message instead of an exception.
Before: stock.financials (pandas table)
| index | 2025-09-30 | 2024-09-30 | … |
|---|---|---|---|
| Total Revenue | 416161000000 | 391035000000 | … |
| Gross Profit | 195201000000 | 180683000000 | … |
| EBIT | … | … | … |
| Net Income | … | … | … |
After: result (JSON for the LLM)
Illustrative values. Notice two conversions: rows → named keys, and raw dollars → millions (smaller numbers = fewer tokens and less chance of the LLM misreading zeros).
and trick on the gross-margin line
A and B in Python returns A if A is "empty" (0, None), otherwise B. So that line means "if there's a gross margin, give me it as a percent". It works — but when the field is missing it returns 0.0 (looks like a 0% margin!) while the next two lines return None. Prefer the clearer style of the next two lines: round(x * 100, 2) if x else None.
Tools 2 & 3 · get_balance_sheet and get_cash_flow_statement
Same skeleton as Tool 1 (cache → fetch → loop over 4 years → JSON → cache → return), different rows:
Total assets · total liabilities · shareholders' equity · cash · total and long-term debt · current assets and liabilities · goodwill & intangibles · working capital (current assets − current liabilities), plus market cap and book value per share.
Operating cash flow · capex · investing and financing cash flow · dividends paid · share buybacks · free cash flow = operating cash flow − capex. FCF feeds the DCF later.
Small real-world catch: Yahoo reports capex as a negative number (money going out), so in code "OCF − capex" becomes ocf + capex_value. Always print one row and check the sign.
Some fields (R&D, goodwill, buybacks) aren't used in any formula — they're there so the LLM can talk about them. The four tools are independent: compute_key_ratios doesn't reuse the other three's output; it fetches its own.
Tool 4 · compute_key_ratios — 20+ ratios in one call
@function_tool
def compute_key_ratios(ticker: str) -> str:
"""
Compute key fundamental ratios for a given stock ticker.
Calculates valuation ratios (P/E, P/B, P/S, EV/EBITDA), profitability
ratios (ROE, ROA, net margin), leverage ratios (Debt/Equity, current ratio,
quick ratio), and growth metrics (revenue YoY, EPS YoY).
Args:
ticker: The stock ticker symbol, e.g. 'AAPL', 'MSFT', 'GOOGL'.
"""
_key = ("compute_key_ratios", ticker.upper())
_hit = _cache.get(_key)
if _hit is not None:
return _hit
try:
stock = yf.Ticker(ticker.upper())
info = stock.info # one big dict of ready-made fields
def pct(v): # 0.4691 → 46.91
return round(v * 100, 2) if v is not None else None
# --- Valuation ---
pe_trailing = _safe_float(info.get("trailingPE"))
pe_forward = _safe_float(info.get("forwardPE"))
pb_ratio = _safe_float(info.get("priceToBook"))
ps_ratio = _safe_float(info.get("priceToSalesTrailing12Months"))
ev_ebitda = _safe_float(info.get("enterpriseToEbitda"))
ev_revenue = _safe_float(info.get("enterpriseToRevenue"))
# --- Profitability ---
roe = pct(info.get("returnOnEquity"))
roa = pct(info.get("returnOnAssets"))
net_margin = pct(info.get("profitMargins"))
gross_margin = pct(info.get("grossMargins"))
op_margin = pct(info.get("operatingMargins"))
# --- Liquidity & leverage ---
current_ratio = _safe_float(info.get("currentRatio"))
quick_ratio = _safe_float(info.get("quickRatio"))
debt_to_eq = _safe_float(info.get("debtToEquity")) # already in %
# --- Growth: worked out by hand from the income statement ---
fin = stock.financials
revenue_growth = None
if fin is not None and not fin.empty and len(fin.columns) >= 2:
rev_rows = [r for r in ["Total Revenue"] if r in fin.index]
if rev_rows:
rev_now = fin.loc[rev_rows[0], fin.columns[0]] # column 0 = newest year
rev_prev = fin.loc[rev_rows[0], fin.columns[1]] # column 1 = the year before
if rev_prev and float(rev_prev) != 0:
revenue_growth = round(((float(rev_now) - float(rev_prev)) / abs(float(rev_prev))) * 100, 2)
# --- Free-cash-flow yield ---
market_cap = info.get("marketCap")
fcf = info.get("freeCashflow")
fcf_yield = None
if market_cap and fcf and float(market_cap) > 0:
fcf_yield = round((float(fcf) / float(market_cap)) * 100, 2)
# --- Dividend ---
div_yield = pct(info.get("dividendYield"))
payout_rat = pct(info.get("payoutRatio"))
result = {
"ticker": ticker.upper(),
"company_name": info.get("longName", ticker.upper()),
"current_price": _safe_float(info.get("currentPrice") or info.get("regularMarketPrice")),
"market_cap_M": _millions(info.get("marketCap")),
"52_week_high": _safe_float(info.get("fiftyTwoWeekHigh")),
"52_week_low": _safe_float(info.get("fiftyTwoWeekLow")),
"valuation": {
"pe_trailing": pe_trailing, "pe_forward": pe_forward, "pb_ratio": pb_ratio,
"ps_ratio": ps_ratio, "ev_ebitda": ev_ebitda, "ev_revenue": ev_revenue,
},
"profitability": {
"roe_pct": roe, "roa_pct": roa, "net_margin_pct": net_margin,
"gross_margin_pct": gross_margin, "op_margin_pct": op_margin,
},
"leverage": {
"current_ratio": current_ratio, "quick_ratio": quick_ratio, "debt_to_equity": debt_to_eq,
},
"growth": {
"revenue_yoy_pct": revenue_growth,
"revenue_growth_3y": pct(info.get("revenueGrowth")),
"earnings_growth_yoy": pct(info.get("earningsGrowth")),
"earnings_quarterly": pct(info.get("earningsQuarterlyGrowth")),
},
"cash_flow": {
"fcf_yield_pct": fcf_yield,
"free_cash_flow_M": _millions(info.get("freeCashflow")),
"operating_cf_M": _millions(info.get("operatingCashflow")),
},
"dividend": {
"yield_pct": div_yield, "payout_ratio": payout_rat,
"annual_div": _safe_float(info.get("dividendRate")),
},
}
output = json.dumps(result, indent=2, default=str)
_cache.store(_key, output)
return output
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker})- Most ratios aren't calculated at all — they're looked up in
stock.infoand renamed.trailingPEbecomespe_trailing,enterpriseToEbitdabecomesev_ebitda, and so on. pct()is a tiny function inside the tool, used only here: Yahoo gives margins as fractions (0.4691), we want percents (46.91).- Revenue growth is the one real calculation: (this year − last year) ÷ last year × 100, using columns 0 and 1 because the table is newest-first.
- FCF yield = free cash flow ÷ market value × 100 — "if you bought the whole company, what % cash return would you get?"
- The result is grouped into six sections (valuation, profitability, leverage, growth, cash flow, dividend), so the LLM can find things by name.
Look at the comment # already in % next to debt_to_eq. Yahoo's debtToEquity of 102.63 means 102.63% = 1.03×. But the RiskAgent's prompt says "Debt/Equity: >2.0 is high leverage". An LLM reading 102.63 against a rule of 2.0 will shout "extremely leveraged!" — and in our Apple sample the brief did call "102.63" an elevated debt-to-equity ratio. Fix it in the tool, not the prompt: debt_to_eq = debt_to_eq / 100 if debt_to_eq is not None else None, or rename the key to debt_to_equity_pct. Lesson: units are part of the contract between tool and prompt. Yahoo has changed the units of other fields before, so spot-check a value against the website now and then.
4.4The valuation tools (tools/valuation_tools.py)
Two ways of answering "is this stock cheap?" — and the clever part is that they disagree for different reasons.
Values the flat on its own merits: how much rent will it earn for years to come, in today's money? Ignores what the neighbours sold for.
"Flats in this society go for ₹11,000 per sq ft; this one wants ₹15,000." Ignores the future; only compares prices right now.
Tool 1 · run_dcf_model — four steps
- Project free cash flow for 5 years, growing at
growth_rate(default 8%). - Discount each year back to today's money at
discount_rate(default 9%) — the return investors demand for the risk. - Terminal value: everything after year 5 as one lump, growing forever at
terminal_growth_rate(max 3%), also discounted back. - Per share: add it all up (= value of the business), subtract net debt (debt − cash), divide by the number of shares. Compare with today's price → upside % → verdict.
@function_tool
def run_dcf_model(ticker: str, growth_rate: float, discount_rate: float,
terminal_growth_rate: float) -> str:
"""Estimate intrinsic value per share with a 5-year DCF and compare it to the current price."""
try:
# The real tool reads these from yfinance: latest FCF, total debt, cash, shares, price
fcf, net_debt, shares, price = _load_dcf_inputs(ticker)
# Step 1 · project free cash flow for 5 years
fcfs = [fcf * (1 + growth_rate) ** t for t in range(1, 6)]
# Step 2 · bring each year back to today's money
pv_fcfs = [f / (1 + discount_rate) ** t for t, f in enumerate(fcfs, start=1)]
# Step 3 · everything after year 5 as one lump (Gordon growth), also brought back
terminal_value = fcfs[-1] * (1 + terminal_growth_rate) / (discount_rate - terminal_growth_rate)
pv_terminal = terminal_value / (1 + discount_rate) ** 5
# Step 4 · business value → owners' value → per share
enterprise_value = sum(pv_fcfs) + pv_terminal
equity_value = enterprise_value - net_debt
intrinsic_value = equity_value / shares
upside = (intrinsic_value / price - 1) * 100
return json.dumps({"intrinsic_value": round(intrinsic_value, 2), "current_price": price,
"upside_pct": round(upside, 1), "verdict": _dcf_verdict(upside)})
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker})
def _dcf_verdict(upside):
if upside > 30: return "SIGNIFICANTLY UNDERVALUED"
if upside > 15: return "SLIGHTLY UNDERVALUED"
if upside >= -15: return "FAIRLY VALUED"
if upside >= -30: return "SLIGHTLY OVERVALUED"
return "SIGNIFICANTLY OVERVALUED"(1 + growth_rate) ** t—**means "to the power of". Year 3 at 8% growth: fcf × 1.08³.enumerate(fcfs, start=1)gives pairs (1, year-1 FCF), (2, year-2 FCF)… so each year is divided by (1 + rate) to the power of its own year number.- The terminal formula divides by
discount_rate − terminal_growth_rate. If they get close, the value explodes — that's why the agent is told "never above 3%". - The verdict is computed in code, from fixed thresholds, so it's the same every time. (Section 4.8 explains why that matters.)
Move the three assumptions — watch the value swing
Apple-like illustrative inputs: latest FCF $98.8B · net debt $63B · 14.8B shares · price $258.95.
- About three-quarters of the value comes from the terminal value — "years 6 to forever". A DCF is mostly a bet on the very long run.
- Small assumption, big swing. Discount rate 9% → 11% cuts the value by about a quarter. That's why the ValuationAgent must print its assumptions and the reason for each, and why a good next step is a human approving them.
The mirror trap: same number, opposite meaning
Tool 2 · get_peer_multiples
@function_tool
def get_peer_multiples(ticker: str) -> str:
"""
Compare a stock's valuation multiples against its sector peers.
Fetches P/E, P/B, EV/EBITDA, and P/S ratios for the company and
a set of sector peers. Returns averages, medians, and highlights
whether the stock trades at a premium or discount to peers.
Args:
ticker: The stock ticker symbol, e.g. 'AAPL', 'MSFT', 'GOOGL'.
"""
try:
stock = yf.Ticker(ticker.upper())
info = stock.info
sector = info.get("sector")
# ... (full code: choose the list `peers` for this sector)
def get_multiples(t: str) -> dict: # the same 5 multiples for ANY ticker
try:
i = yf.Ticker(t).info
return {
"ticker": t,
"pe": _safe_float(i.get("trailingPE")),
"forward_pe": _safe_float(i.get("forwardPE")),
"pb": _safe_float(i.get("priceToBook")),
"ps": _safe_float(i.get("priceToSalesTrailing12Months")),
"ev_ebitda": _safe_float(i.get("enterpriseToEbitda")),
"roe_pct": round(i.get("returnOnEquity", 0) * 100, 2) if i.get("returnOnEquity") else None,
}
except Exception:
return {"ticker": t, "pe": None, "pb": None, "ps": None, "ev_ebitda": None}
subject = get_multiples(ticker.upper()) # our company
peer_data = [get_multiples(p) for p in peers] # one dict per peer
def avg(key: str) -> float | None: # peer average, skipping missing values
vals = [p[key] for p in peer_data if p.get(key) is not None]
return round(sum(vals) / len(vals), 2) if vals else None
peer_avg = {"pe": avg("pe"), "forward_pe": avg("forward_pe"), "pb": avg("pb"),
"ps": avg("ps"), "ev_ebitda": avg("ev_ebitda"), "roe_pct": avg("roe_pct")}
def premium(subject_val, peer_val) -> str | None: # "+16.2%" style text
if subject_val is None or peer_val is None or peer_val == 0:
return None
pct = round(((subject_val - peer_val) / peer_val) * 100, 1)
return f"{'+' if pct >= 0 else ''}{pct}%"
verdict, weighted_avg = _peer_verdict(subject, peer_avg) # the verdict is computed in code
# ... (full code: build `result` with subject, peers, averages, premiums, verdict)
return json.dumps(result, indent=2, default=str)
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker})- A function inside a function.
get_multipleslives inside the tool because only this tool needs it. It's called once for our company and once per peer. [get_multiples(p) for p in peers]— a list comprehension: "for each peer ticker, fetch its multiples" → a list of dictionaries.avg("pe")collects that key from every peer, skipping peers with no value, then averages. Missing data never crashes and never drags the average to zero.premium()formats a number like16.2as"+16.2%"; the'+' if pct >= 0 else ''part only adds a plus sign for positives (negatives already have a minus)._peer_verdictturns five premiums into one weighted number and a label. Sketch below.
WEIGHTS = {"forward_pe": 0.30, "ev_ebitda": 0.25, "pe": 0.20, "ps": 0.15, "pb": 0.10}
def _peer_verdict(subject, peer_avg):
total, weight_used = 0.0, 0.0
for key, w in WEIGHTS.items():
s, p = subject.get(key), peer_avg.get(key)
if s is None or not p: # missing on either side → skip this multiple
continue
total += w * (s / p - 1) * 100 # premium of this multiple, times its weight
weight_used += w
if weight_used == 0:
return "N/A", None
weighted_avg = round(total / weight_used, 1) # re-scale so skipped weights don't count
if weighted_avg > 30: verdict = "SIGNIFICANTLY OVERVALUED"
elif weighted_avg > 15: verdict = "SLIGHTLY OVERVALUED"
elif weighted_avg >= -15: verdict = "FAIRLY VALUED"
elif weighted_avg >= -30: verdict = "SLIGHTLY UNDERVALUED"
else: verdict = "SIGNIFICANTLY UNDERVALUED"
return verdict, weighted_avgForward P/E 30% — what professional investors look at most. EV/EBITDA 25% — fair across companies with different debt; the standard in M&A. Trailing P/E 20% — real reported profits, not forecasts. P/S 15% — still works when profits are tiny. P/B 10% — book value says little about brand- and software-heavy companies.
Enter each premium vs peers (%) — see the weighted verdict
With these Apple-like premiums, P/B (+242.7%) carries only 10% weight yet adds about 24 of the 39 points. Tick "skip P/B" and the verdict drops a whole level, from significantly to slightly overvalued. Remember Apple's tiny equity from Section 2? Same root cause. A real system might cap extreme premiums or use the peer median.
4.5The news tools (tools/news_tools.py)
Tool 1 grabs headlines and gives each a quick mood score. Tool 2 averages them into one verdict and flags dangerous topics. The LLM carries the JSON from tool 1 into tool 2.
@function_tool
def search_recent_news(ticker: str, max_results: int) -> str:
"""
Fetch recent news articles and headlines for a given stock ticker.
Uses yfinance to retrieve the latest news. Returns titles, publishers,
publication dates, and article links. This data feeds into sentiment
analysis and helps identify current market narratives around the stock.
Args:
ticker: The stock ticker symbol, e.g. 'AAPL', 'MSFT', 'GOOGL'.
max_results: Maximum number of news articles to retrieve (1-20).
"""
try:
max_results = max(1, min(int(max_results), 20)) # ① clamp to 1..20
_key = ("search_recent_news", ticker.upper(), max_results)
_hit = _cache.get(_key)
if _hit is not None:
return _hit
stock = yf.Ticker(ticker.upper())
short_name = stock.info.get("shortName", "")
raw_news = stock.news or [] # ② list of news items, or []
# ... (full code: drop articles that aren't really about this company)
articles = []
for item in raw_news:
if len(articles) >= max_results:
break
content = item.get("content") or {} # ③ safe digging into nested dicts
title = content.get("title") or "No title"
publisher = (content.get("provider") or {}).get("displayName") or "Unknown"
pub_time = _format_timestamp(content.get("pubDate"))
link = (content.get("clickThroughUrl") or {}).get("url") or ""
# ... (full code: first_sentence = first sentence of the article summary)
scoring_text = f"{title}. {first_sentence or ''}"
label, score = _score_headline(scoring_text) # ④ quick keyword score
articles.append({
"title": title, "publisher": publisher, "published_at": pub_time,
"sentiment": label, "sentiment_score": score,
"url": link, "first_sentence": first_sentence,
})
# ... (full code: count labels, wrap in a dict, json.dumps, cache, return)
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker})max(1, min(int(max_results), 20))— the LLM picksmax_results; this line forces it into 1–20 whatever it asks for.min(…, 20)caps the top,max(1, …)the bottom. Never trust an LLM-chosen number blindly.stock.news or []— if Yahoo returns nothing (None), use an empty list so the loop simply doesn't run.(content.get("provider") or {}).get("displayName") or "Unknown"reads as: "get the provider; if it's missing use an empty dict; from that get displayName; if that's missing say Unknown". It's a ladder that never crashes on missing data.- Each headline (plus its first sentence) gets a quick keyword score — next.
import re
BULLISH_SIGNALS = ["beat", "beats", "record", "surge", "upgrade", "growth", "strong",
"raises", "buyback", "outperform", "jumps", "rally", "gains", "boosts"]
BEARISH_SIGNALS = ["miss", "misses", "fall", "falls", "drop", "decline", "cut", "downgrade",
"lawsuit", "probe", "investigation", "antitrust", "recall", "fine", "weak", "loss"]
def _score_headline(text: str):
words = re.findall(r"[a-z]+", text.lower()) # "Apple beats estimates!" → ["apple", "beats", "estimates"]
bull = sum(w in BULLISH_SIGNALS for w in words) # True counts as 1
bear = sum(w in BEARISH_SIGNALS for w in words)
if bull + bear == 0:
return "neutral", 0.0 # no signal words at all
net = (bull - bear) / (bull + bear) # always between -1 and +1
if net > 0.15: return "bullish", round(net, 2)
if net < -0.15: return "bearish", round(net, 2)
return "neutral", round(net, 2)Net score = (bullish words − bearish words) ÷ (bullish + bearish). Two good words and none bad → +1.0. One of each → 0. It's crude — but fast, free, and it catches the strongest signals. The LLM does the subtle reading later.
@function_tool
def analyze_sentiment(news_json: str) -> str:
"""
Perform a structured sentiment analysis on a set of news articles.
Takes the JSON output from search_recent_news and produces a detailed
sentiment report: an aggregate sentiment score, key bullish and bearish
themes extracted from headlines, and an overall market narrative summary.
Args:
news_json: JSON string output from search_recent_news containing
a list of articles with titles and sentiment scores.
"""
try:
data = json.loads(news_json) # tool 1's text → dict again
articles = data.get("articles", [])
ticker = data.get("ticker", "UNKNOWN")
scores = [a.get("sentiment_score", 0.0) for a in articles]
avg_score = round(sum(scores) / len(scores), 3) if scores else 0.0
all_titles = " ".join(a.get("title", "") for a in articles).lower()
bullish_themes = [w for w in BULLISH_SIGNALS if w in all_titles][:5]
bearish_themes = [w for w in BEARISH_SIGNALS if w in all_titles][:5]
# ... (full code: top_bullish / top_bearish = the most extreme headlines)
if avg_score > 0.40:
overall = "strongly bullish"
elif avg_score > 0.15:
overall = "bullish"
elif avg_score < -0.40:
overall = "strongly bearish"
elif avg_score < -0.15:
overall = "bearish"
else:
overall = "neutral"
high_risk_keywords = ["fraud", "investigation", "antitrust", "lawsuit",
"recall", "scandal", "penalty", "fine"]
risk_flags = [
a["title"] for a in articles
if any(kw in a.get("title", "").lower() for kw in high_risk_keywords)
]
result = {
"ticker": ticker,
"overall_sentiment": overall,
"aggregate_score": avg_score,
"interpretation": f"Score of {avg_score:.3f} on a scale of -1 (very bearish) to +1 (very bullish)",
"article_count": len(articles),
"sentiment_breakdown": data.get("sentiment_summary", {}),
"key_bullish_themes": bullish_themes,
"key_bearish_themes": bearish_themes,
"top_bullish_headlines": [h["title"] for h in top_bullish],
"top_bearish_headlines": [h["title"] for h in top_bearish],
"risk_flags": risk_flags,
"risk_flag_count": len(risk_flags),
"all_articles": [
{"title": a["title"], "publisher": a["publisher"], "published_at": a["published_at"],
"sentiment": a["sentiment"], "url": a["url"], "first_sentence": a.get("first_sentence")}
for a in articles
],
}
# ... (full code: return json.dumps(result))
except Exception as e:
return json.dumps({"error": str(e), "ticker": ticker})- Average the per-headline scores → one number between −1 and +1.
- Themes: glue all titles into one lowercase string, then keep every signal word that appears in it (first 5).
- Five levels here, three levels in tool 1. One headline can only "lean" up or down; "strongly bullish" only means something when you average many.
- Risk flags:
any(kw in title for kw in keywords)= "does this title contain any danger word?" Those headlines are listed separately because one lawsuit matters more than ten "stock rises" stories.
Tick headlines in or out, or add your own — watch both tools work
Made-up practice headlines. Green = bullish word, red = bearish word.
"Apple redefines the premium laptop market" is flagged as a risk. Why? "fine" in "apple redefines…" is True — "re-de-fine-s". Substring checks match inside other words. The fix: match whole words (re.findall, like _score_headline does) or use \bfine\b. A tiny bug like this sends a fake "regulatory risk" into the final brief.
4.6The six agents (agents/*.py)
Every agent is the same three lines of SDK code — Agent(name, instructions, tools, model). All the intelligence is in the instructions. So read each agent as a prompt-engineering lesson. Five tricks repeat across all of them:
STRONG | SOLID | MIXED | WEAK. Fixed words are a contract.FinancialDataAgent — the junior analyst
from agents import Agent
from fundamental_analysis_agent.tools.financial_tools import (
get_income_statement,
get_balance_sheet,
get_cash_flow_statement,
compute_key_ratios,
)
FINANCIAL_DATA_INSTRUCTIONS = """
You are a senior financial analyst specializing in reading and interpreting
corporate financial statements.
Your job:
Given a stock ticker, retrieve the company's financial statements and compute
key fundamental ratios. Then provide a concise, structured interpretation.
Steps to follow:
1. Call get_income_statement(ticker) to fetch revenue, margins, and earnings.
2. Call get_balance_sheet(ticker) to fetch assets, liabilities, equity, and debt.
3. Call get_cash_flow_statement(ticker) to fetch operating, investing, and FCF.
4. Call compute_key_ratios(ticker) to get valuation, profitability, leverage, and growth ratios.
After gathering all data, write a structured summary with these sections:
- REVENUE & PROFITABILITY: Revenue trend (growing/declining), margin quality.
- BALANCE SHEET HEALTH: Debt levels, cash position, working capital.
- CASH FLOW QUALITY: Is FCF growing? Does it track net income (quality indicator)?
- KEY RATIOS SNAPSHOT: Highlight the 5-6 most important ratios for this company.
- FINANCIAL HEALTH VERDICT: One of [STRONG | SOLID | MIXED | WEAK] with 2-3 sentence justification.
STRICT RULES:
- Every statement must be directly supported by a number from the tool outputs.
Do not add qualitative judgments or editorial conclusions that cannot be traced
to a specific data point (e.g. do not say "enhances shareholder value",
"reflects management discipline", or similar unsourced interpretations).
- Each section must be self-contained. Do not reference data that belongs to a
later section (e.g. do not mention cash flows inside BALANCE SHEET HEALTH --
cash flows are covered in CASH FLOW QUALITY).
- If a data point is unavailable, say so explicitly rather than omitting it silently.
"""
financial_data_agent = Agent(
name="FinancialDataAgent",
instructions=FINANCIAL_DATA_INSTRUCTIONS,
tools=[get_income_statement, get_balance_sheet, get_cash_flow_statement, compute_key_ratios],
model="gpt-4o",
)- The imports show the folder layout: agents live in
agents/, tools intools/. The agent file only uses tools; it never fetches data itself. - "Does FCF track net income?" is a real analyst's check: profits that never turn into cash are a warning sign. One line of prompt carries that know-how.
- STRICT RULES were added after real failures — the agent once wrote "enhances shareholder value", which no number supports (more in 4.8).
- "Say so if a data point is missing" — silence looks like "fine"; an explicit "N/A" is honest.
NewsAndSentimentAgent — the news desk
from agents import Agent
from fundamental_analysis_agent.tools.news_tools import search_recent_news, analyze_sentiment
NEWS_SENTIMENT_INSTRUCTIONS = """
You are a market intelligence analyst specializing in news analysis
and investor sentiment for publicly traded companies.
Your job:
Retrieve and analyze recent news for a stock ticker to surface the current
market narrative, sentiment, and any material risk events.
Steps to follow:
1. CALL search_recent_news(ticker, max_results=15)
This fetches the latest headlines with preliminary sentiment labels.
2. CALL analyze_sentiment(news_json) with the JSON output from step 1.
This produces an aggregate sentiment score and key themes.
3. WRITE A STRUCTURED SENTIMENT REPORT with these sections:
- MARKET NARRATIVE: In 2-3 sentences, what is the dominant story the market
is telling about this company right now?
- SENTIMENT VERDICT: [STRONGLY BULLISH | BULLISH | NEUTRAL | BEARISH | STRONGLY BEARISH]
with the aggregate score.
- KEY BULLISH CATALYSTS: Bullet list of positive themes from headlines.
- KEY BEARISH RISKS: Bullet list of negative themes.
- MATERIAL RISK FLAGS: Any headlines involving lawsuits, investigations,
fraud, recalls, or regulatory actions. These are high-priority.
If none, state "No material risk flags identified."
- SENTIMENT CONFIDENCE: [HIGH | MEDIUM | LOW] based on the volume
and recency of news. Low if fewer than 5 articles found.
- RAW NEWS SOURCES: List every article from all_articles in the sentiment
result as a numbered list:
[N] <title> -- <publisher> (<published_at>) | <sentiment> | <url>
This section is mandatory. It allows readers to verify the analysis
against the original sources.
Focus on substance, not noise. One major regulatory investigation matters more
than ten generic "stock rises" headlines.
"""
news_sentiment_agent = Agent(
name="NewsAndSentimentAgent",
instructions=NEWS_SENTIMENT_INSTRUCTIONS,
tools=[search_recent_news, analyze_sentiment],
model="gpt-4o",
)- A tool chain through the LLM: step 2 says "call analyze_sentiment with the JSON output from step 1". The LLM copies tool 1's result into tool 2's argument — tools never talk directly.
- RAW NEWS SOURCES is mandatory — every claim must be checkable with a link. Same principle as the verified-news agent in Section 2.
- "Signal over noise" is the line a real news-desk head would say. Putting it in the prompt makes the agent rank, not just list.
RiskAgent — the professional sceptic
from agents import Agent
from fundamental_analysis_agent.tools.financial_tools import get_balance_sheet, compute_key_ratios
from fundamental_analysis_agent.tools.news_tools import search_recent_news
RISK_INSTRUCTIONS = """
You are a risk analyst at a hedge fund. Your job is to stress-test investment
theses and find the vulnerabilities that optimistic analysts overlook.
You are deliberately skeptical. Your goal is NOT to be bearish for its own sake,
but to identify REAL, MATERIAL risks that an investor must weigh.
Steps to follow:
1. CALL get_balance_sheet(ticker) -- examine debt levels, cash runway,
working capital. A company burning cash with high debt is a red flag.
2. CALL compute_key_ratios(ticker) -- focus on:
- Debt/Equity: >2.0 is high leverage territory
- Current Ratio: <1.0 means current liabilities exceed current assets
- Interest Coverage: implied from operating income / interest expense
- P/E vs growth: if P/E is high but growth is slowing, valuation risk is elevated
3. CALL search_recent_news(ticker, max_results=10) -- scan for:
regulatory investigations, lawsuits, data breaches, product recalls,
management changes, covenant violations, credit downgrades.
4. WRITE A STRUCTURED RISK REPORT:
RISK REGISTER (table format):
| Risk | Category | Severity | Evidence |
Categories: [FINANCIAL | OPERATIONAL | REGULATORY | MARKET | MACRO]
Severity: [LOW | MEDIUM | HIGH | CRITICAL]
FINANCIAL STRESS TEST:
- What happens to the company if revenue drops 20%?
- Can it service its debt with current cash flow?
- What is the cash runway (months of expenses covered by cash)?
KEY VULNERABILITIES: Top 3 specific risks with detailed explanation.
RISK VERDICT: One of [LOW RISK | MODERATE RISK | ELEVATED RISK | HIGH RISK]
with a 2-sentence justification.
Be specific and evidence-based. Vague risks like "macroeconomic uncertainty"
only add value if you connect them to specific company vulnerabilities.
"""
risk_agent = Agent(
name="RiskAgent",
instructions=RISK_INSTRUCTIONS,
tools=[get_balance_sheet, compute_key_ratios, search_recent_news],
model="gpt-4o",
)- Same data, different eyes. It borrows two tools from the FinancialDataAgent and one from the news agent. The data is identical; the job is to find what could go wrong. (And thanks to the cache, those calls cost nothing extra.)
- "Sceptical, NOT bearish for its own sake" — without the second half, an adversarial agent finds doom everywhere.
- A stress test in three questions: revenue −20%? can it pay its debt? how many months of cash? This is what a risk manager actually asks.
- "Vague risks only count if connected" — kills filler like "macroeconomic uncertainty".
Cash runway = how many months the company could pay its bills from the cash it has, if no new money came in. Covenant violation = breaking a promise written into a loan ("we'll keep debt below 3× earnings"). It can let the lender demand money back early.
ValuationAgent — rules for choosing assumptions
from agents import Agent
from fundamental_analysis_agent.tools.valuation_tools import run_dcf_model, get_peer_multiples
VALUATION_INSTRUCTIONS = """
You are a buy-side equity analyst specializing in company valuation.
Your job:
Estimate the intrinsic value of a stock using two complementary methods,
then synthesize them into a clear investment verdict.
Steps to follow:
1. DETERMINE DCF INPUTS
Your input starts with "Ticker: [SYMBOL]" -- use that symbol for all tool calls.
It also contains a ---FINANCIAL CONTEXT FOR DCF--- block extracted by the
Orchestrator from the financial data agent. Read it before choosing inputs.
BASELINE (apply by default):
- growth_rate: 0.08 (8%) -- use unless FCF 3-year CAGR differs by more than 3pp
- discount_rate: 0.09 (9%) -- use for large-cap, investment-grade companies
- terminal_growth_rate: 0.03 (3%) -- use for stable, mature companies
ALLOWED ADJUSTMENTS (document the reason explicitly, citing the value from the context block):
- Raise discount_rate to 0.10-0.12 only if debt/equity ratio > 3.0x
AND operating cash flow trend = declining.
- Adjust growth_rate toward the FCF 3-year CAGR if it differs from 8% by more than 3pp.
- Lower growth_rate below 0.06 only if both revenue growth YoY values are negative.
- Never set terminal_growth_rate above 0.03.
Always output a DCF INPUTS section listing your chosen values and the reason
(either "baseline -- no adjustment triggered" or the specific data point that triggered a change).
2. CALL run_dcf_model(ticker, growth_rate, discount_rate, terminal_growth_rate)
Interpret the result: upside/downside %, whether the stock is cheap or expensive.
3. CALL get_peer_multiples(ticker)
Compare the company's P/E, EV/EBITDA, P/B vs sector peers.
Note whether the premium/discount is justified by superior growth or margins.
4. SYNTHESIZE: Write a structured valuation report with these sections:
- DCF INPUTS: chosen values and, for each, "baseline" or the data point that triggered a change.
- DCF VALUATION: Intrinsic value per share, upside/downside,
and the verdict field returned by run_dcf_model exactly as-is.
- RELATIVE VALUATION: How the stock trades vs peers. The peer_verdict field in the
get_peer_multiples result already contains the weighted average premium and
computed verdict -- report it exactly as returned. Do not override or reinterpret it.
- VALUATION VERDICT: Synthesize the DCF verdict and the peer-based verdict into a
single final verdict using the same 5-level scale.
Use the more conservative (more cautious) of the two if they differ.
- CONFIDENCE LEVEL: Derive from method agreement:
HIGH -- both DCF verdict and peer verdict are the same label
MEDIUM -- they differ by one level (e.g., SLIGHTLY vs SIGNIFICANTLY)
LOW -- they diverge by more than one level or point in opposite directions
- KEY ASSUMPTIONS & RISKS: What could make the DCF wrong?
"""
valuation_agent = Agent(
name="ValuationAgent",
instructions=VALUATION_INSTRUCTIONS,
tools=[run_dcf_model, get_peer_multiples],
model="gpt-4o",
)- The LLM picks the DCF inputs — but inside a fence. Baseline 8 / 9 / 3, and only listed triggers may change them. It must cite the number that triggered a change. Creativity where it helps, rules where it matters.
- "Report it exactly as returned" — the tool already computed the verdicts; the LLM only relays them.
- "More conservative of the two" — when the surveyor and the dealer disagree, believe the more cautious one. Try it below.
CAGR (compound annual growth rate) = the steady yearly growth that would take you from the start value to the end value. pp = percentage points: going from 8% to 11% is +3 pp (not +3%).
Pick what the DCF says and what the peers say
ReportWriterAgent — the rating comes from a table, not a feeling
from agents import Agent
REPORT_WRITER_INSTRUCTIONS = """
You are a managing director at an investment firm writing the final investment
committee memo. You have received analysis from four specialist analysts:
financial data, valuation, news/sentiment, and risk.
Your job:
Synthesize all inputs into a single, professional investment brief that a
portfolio manager can act on. You do NOT call any tools -- you only synthesize
the information provided to you.
OVERALL RATING RULES -- apply these deterministically:
Valuation verdict (exact label from ValuationAgent) x Risk verdict (exact label from RiskAgent):
LOW MODERATE ELEVATED HIGH
SIGNIFICANTLY UNDERVALUED -> STRONG BUY BUY HOLD HOLD
SLIGHTLY UNDERVALUED -> BUY BUY HOLD HOLD
FAIRLY VALUED -> HOLD HOLD HOLD HOLD
SLIGHTLY OVERVALUED -> HOLD SELL SELL STRONG SELL
SIGNIFICANTLY OVERVALUED -> HOLD SELL STRONG SELL STRONG SELL
EXAMPLE:
Valuation verdict (from ValuationAgent): SLIGHTLY UNDERVALUED
Risk verdict (from RiskAgent): LOW RISK
Applying rating table => BUY (not STRONG BUY -- only slightly undervalued)
Use the exact valuation verdict from the ValuationAgent and the exact risk
verdict from the RiskAgent. Do not override these with your own judgment.
OUTPUT FORMAT -- produce the report in exactly this structure:
FUNDAMENTAL ANALYSIS BRIEF
[Company Name] ([TICKER]) | [Sector] | [Date]
EXECUTIVE SUMMARY
[2-3 sentences: what the company does, our overall view, the single most important thing to know.]
INVESTMENT VERDICT
Rating derivation (fill this in before writing the Overall Rating):
Valuation verdict (from ValuationAgent): [exact label]
Risk verdict (from RiskAgent): [exact label]
Applying rating table => [resulting rating]
Overall Rating: [STRONG BUY | BUY | HOLD | SELL | STRONG SELL]
Valuation / Risk Profile / Sentiment / Intrinsic Value / Current Price / Upside-Downside
FINANCIAL HEALTH [3-4 bullets with specific numbers]
VALUATION ANALYSIS [relay the ValuationAgent's conclusions -- do not form your own judgment]
MARKET SENTIMENT & CATALYSTS [2-3 bullets]
RISK FACTORS [3-4 specific, actionable bullets]
INVESTMENT THESIS Bull case / Base case / Bear case
CONCLUSION [buy, hold or avoid -- and on what time horizon]
This report is for educational purposes only. Not financial advice.
IMPORTANT RULES:
- Every claim must be supported by data from the analysts' reports.
- Do not invent numbers or make up analyst projections.
- If data is missing or conflicting, acknowledge it explicitly.
- Keep the total report under 800 words -- clarity over length.
- Use a confident, professional tone. Avoid hedging every sentence.
"""
report_writer_agent = Agent(
name="ReportWriterAgent",
instructions=REPORT_WRITER_INSTRUCTIONS,
tools=[], # pure synthesis -- no external tools needed
model="gpt-4o",
)- The rating is a lookup, not an opinion. Valuation row × risk column → one cell. Same inputs always give the same rating, and an auditor can check it in seconds.
- "Fill this in before writing the Overall Rating" forces the model to show the derivation first (chain-of-thought written into the format), then the answer.
- The table sits at the top of the prompt on purpose. When it was at the bottom, the model had already picked a rating by the time it read the rules (4.8, lesson 2).
tools=[]— this agent only writes. It can't fetch anything new, so it can't sneak in unchecked facts.
Click any cell — this is exactly what the ReportWriterAgent must do
OrchestratorAgent — the director of research
from agents import Agent
from fundamental_analysis_agent.agents.financial_data_agent import financial_data_agent
from fundamental_analysis_agent.agents.valuation_agent import valuation_agent
from fundamental_analysis_agent.agents.news_sentiment_agent import news_sentiment_agent
from fundamental_analysis_agent.agents.risk_agent import risk_agent
from fundamental_analysis_agent.agents.report_writer_agent import report_writer_agent
ORCHESTRATOR_INSTRUCTIONS = """
You are a senior investment analyst orchestrating a full fundamental analysis.
You coordinate a team of specialist sub-agents and synthesize their findings
into a final investment brief.
Given a stock ticker symbol, execute the following workflow:
PHASE 1 -- DATA GATHERING (call all three simultaneously in a single step):
Call financial_data_analysis, news_and_sentiment_analysis, and risk_assessment
all at once with the ticker. Do not wait for one to finish before calling the next.
They are independent and must be issued as parallel tool calls in a single response.
- financial_data_analysis: returns financial statements, key ratios, and a financial health verdict.
- news_and_sentiment_analysis: returns recent news, sentiment score, and risk flags.
- risk_assessment: returns a risk register and financial stress test.
PHASE 2 -- VALUATION (requires Phase 1 financial data):
Step 2: Call valuation_analysis with the following input (fill in the values
from the Step 1a output). The ticker must appear on the first line.
Ticker: [TICKER]
---FINANCIAL CONTEXT FOR DCF---
Revenue growth YoY (latest year): [X%]
Revenue growth YoY (prior year): [X%]
FCF 3-year CAGR (if available): [X%]
Debt/Equity ratio: [X]
Operating cash flow trend: [growing | declining | stable]
---END FINANCIAL CONTEXT---
If a value is not available in the Step 1a output, write "N/A".
PHASE 3 -- SYNTHESIS:
Step 3: Call write_investment_report with ALL findings from Steps 1a, 1b, 1c, and 2.
Structure your input as:
FINANCIAL DATA ANALYSIS: [output from step 1a]
NEWS & SENTIMENT ANALYSIS: [output from step 1b]
RISK ASSESSMENT: [output from step 1c]
VALUATION ANALYSIS: [output from step 2]
IMPORTANT:
- Do not skip any step. All four specialist analyses are required.
- If a sub-agent returns an error for any tool, note it in the final report
rather than stopping the workflow entirely.
- Your final output must be the ReportWriterAgent's output copied verbatim,
character for character. Do not add commentary, remove sections, reformat,
or summarize any part of it.
- Be patient: the workflow has multiple API calls and may take 30-60 seconds.
"""
orchestrator = Agent(
name="OrchestratorAgent",
instructions=ORCHESTRATOR_INSTRUCTIONS,
tools=[
financial_data_agent.as_tool(
tool_name="financial_data_analysis",
tool_description=(
"Fetches and analyzes financial statements (income statement, "
"balance sheet, cash flow) and computes key fundamental ratios "
"for a given stock ticker. Returns a financial health verdict."
),
),
news_sentiment_agent.as_tool(
tool_name="news_and_sentiment_analysis",
tool_description=(
"Retrieves recent news headlines and performs sentiment analysis "
"for a given stock ticker. Returns sentiment verdict, key themes, "
"and any material risk flags from news."
),
),
risk_agent.as_tool(
tool_name="risk_assessment",
tool_description=(
"Performs a comprehensive risk assessment for a given stock ticker. "
"Examines balance sheet stress points, leverage ratios, liquidity, "
"and news-based risk events. Returns a risk register and verdict."
),
),
valuation_agent.as_tool(
tool_name="valuation_analysis",
tool_description=(
"Estimates the intrinsic value of a stock using DCF modeling and "
"peer multiples comparison. Returns intrinsic value per share, "
"upside/downside percentage, and a valuation verdict."
),
),
report_writer_agent.as_tool(
tool_name="write_investment_report",
tool_description=(
"Synthesizes all analysis (financial data, valuation, sentiment, risk) "
"into a final, professional investment brief. Takes the combined "
"findings from all specialist agents and produces the final report."
),
),
],
model="gpt-4o",
).as_tool(tool_name=…, tool_description=…)wraps a whole agent — its instructions, its tools, its model — into one function the orchestrator can call by name. To the orchestrator,valuation_analysis(...)looks no different fromrun_dcf_model(...).- The tool name and description are what the orchestrator's LLM reads when deciding what to call. They're mini-prompts — write them like job descriptions.
- The FINANCIAL CONTEXT block is a hand-off form. The orchestrator copies five numbers from the financial agent's report into it. The valuation agent's rules ("if debt/equity > 3.0×…") read exactly these lines.
- "Copy verbatim, character for character" — otherwise the orchestrator likes to "helpfully" summarise the final brief and drop sections.
- "Note errors, don't stop" — one failed news call shouldn't kill a whole analysis.
A handoff is transferring a customer's call to another department — you're off the line. An agent-as-tool is the manager phoning three specialists, staying on the line, collecting their answers, and then deciding what to send to the next person. The orchestrator must collect four reports and pass the right pieces on, so it can't hang up. Bonus: tool calls can run in parallel, handoffs can't.
4.7Running it (main.py)
import asyncio
from pathlib import Path
from agents import Runner
from fundamental_analysis_agent.agents.orchestrator import orchestrator
async def analyze_ticker(
ticker: str,
stream: bool = False, # print tokens as they arrive
verbose: bool = False, # print each sub-agent's output afterwards
trace: bool = False, # print the CALL / OUTPUT sequence
log_dir: Path | None = None, # save each sub-agent's output to its own .txt file
) -> str:
"""Run the full fundamental analysis pipeline for a single ticker."""
ticker = ticker.upper().strip() # " aapl " → "AAPL"
prompt = (
f"Perform a complete fundamental analysis for the stock ticker: {ticker}\n"
f"Follow the full workflow: gather financial data, news sentiment, and risk "
f"assessment, then run valuation, and finally produce the investment brief."
)
# ... (full code: streaming / tracing / logging options)
result = await Runner.run(orchestrator, input=prompt)
return result.final_output
# From a notebook or script:
# asyncio.run(analyze_ticker("AAPL"))One line does all the work: await Runner.run(orchestrator, input=prompt). Inside, the SDK loops: send to the LLM → it asks for tool calls → run them (some are whole agents, which loop on their own) → feed results back → repeat until the LLM gives a final answer with no more tool calls. For this pipeline that's about 6–8 rounds.
python -m fundamental_analysis_agent.main AAPL # one stock
python -m fundamental_analysis_agent.main MSFT --stream # watch it type
python -m fundamental_analysis_agent.main AAPL --trace --verbose --log-dir logs/ # see everything
python -m fundamental_analysis_agent.main AAPL --watchlist GOOGL TSLA NVDA MSFT # several stocks| Flag | What you get | Use it when |
|---|---|---|
--stream | Output appears word by word | Live demos |
--verbose | Each specialist's full report printed after the run | Checking one agent's reasoning |
--trace | Every CALL and OUTPUT in order | Proving Phase 1 really ran in parallel |
--log-dir logs/ | One .txt file per agent | Audit trail, comparing runs |
--watchlist … | Analyse extra tickers in one go | Morning screening of a portfolio |
python -m package.module runs a module that lives inside a package (so its from fundamental_analysis_agent… imports work). Run it from the folder above fundamental_analysis_agent/. argparse is the standard-library module that turns these flags into Python variables.
4.8Behind the scenes: 7 bugs and their fixes
This is the most valuable part of the project for engineers — every one of these will happen in your own agent systems.
_peer_verdict computes it in the tool; the agent relays it. If code can compute it, code should.--trace flag; three CALLs before any OUTPUT = parallel.Push anything deterministic into tools (Python), and let the LLM reason only over verified inputs. Plus the two bonus bugs you found on this page: the debt/equity unit trap (4.3) and the "refines" substring false alarm (4.5).
4.9Humans vs agents, and what to build next
Collect and structure data · compute ratios · read statements · scan news at scale · apply valuation models the same way every time · check against risk rules — with every number traceable to a tool call.
Validate the assumptions (a DCF is only as good as its growth and discount rates) · settle conflicts (bullish news vs "too expensive") · judge what's hard to measure: management, moats, regulation · own the decision — investing is regulated and fiduciary.
The skill that matters isn't competing with agents at what they automate — it's knowing when to trust them, when to question them, and when to override them.
- Memory: save every brief to SQLite and add a HistoricalComparisonAgent — "what changed since last quarter?" (Section 2's episodic memory, reused.)
- Human approval of DCF assumptions: pause before valuation and let the analyst confirm or change growth and discount rates.
- PortfolioAgent: analyse a watchlist and rank stocks on valuation, quality and sentiment.
- Better data: swap yfinance for Financial Modeling Prep or Polygon.io — only the tools change, the agents stay the same.
- Web app: a FastAPI backend plus a Streamlit or React front end that streams each agent's progress.
Wrap-up
What to remember
- Frameworks all do the basics; remember one superpower each. Production = OpenAI SDK · flexibility = LangGraph · scale = ADK · roles = CrewAI · conversation = AutoGen · schema = PydanticAI · sovereignty = Mistral · code = smolagents · screens = Claude SDK · documents = LlamaIndex.
- Architecture is a cost decision. The same task cost 10× more tokens as a "meeting" of agents.
- Tools are the hands, agents the brains, the orchestrator the manager. Read the project bottom-up.
- Three phases: independent work in parallel → dependent work next → synthesis last.
- Verdicts come from code and tables, not moods: DCF thresholds, weighted peer premium, the 5×4 rating table.
- Watch units, signs and substrings. Debt/equity in %, negative capex, "refines".
Everything on this page is for learning. Nothing here is investment advice or a recommendation to buy or sell any security.