Future with Shivank · AI Agents in Finance · Section 6

Future with Shivank · Hands-on track · Section 6

How an Agent Thinks Seven reasoning patterns, one busy earnings week on the equity desk

The same model can give a sloppy answer or a careful one. The difference is often how you make it think: draft and polish, ask five times and vote, check live data, fact-check against a source, learn from yesterday's mistake, or explore a tree of options before committing. These structured ways of thinking are called reasoning paradigms, and in finance — where a wrong number costs money and a regulator may ask "why?" — they matter as much as the model itself.

🏦 Earnings week at Future with Shivank Bank. Monday the equity desk drafts an investment thesis. Tuesday it votes on BUY / HOLD / SELL. Wednesday it checks the valuation against live market data. Thursday it fact-checks the morning briefing and learns from a screening mistake. Friday it chooses a hedge before a big earnings release, then plans a trim of its technology exposure. Each day uses a different way of thinking — and you'll build every one of them.
7reasoning paradigms, from simple to advanced
5runnable labs, plus 2 small sketches
1story: the desk's earnings week
2advanced patterns you can save for later
🧠 Analogy💰 Finance corner⚠️ Watch out💡 Tip🧪 Simulation (click it!)🔶 Advanced · optional

Section 6 · Part 1 — The map

Seven ways to make an agent think

6.1The map: seven reasoning paradigms

A reasoning paradigm is a recipe for how the model works through a problem: how many times it is called, what each call is asked to do, whether it may use tools, whether it remembers anything, and how the final answer is chosen. Same model, different recipe, very different reliability.

🧠 Analogy — four kinds of analyst

A junior analyst can think harder on their own (re-read their draft, ask colleagues and take a vote). A better one checks the terminal before saying a number. A senior one keeps a notebook of past mistakes. And for the big decisions, a portfolio manager lays out several options, scores them and drops the weak ones before acting. The seven paradigms climb exactly this ladder.

① Inside the model ② Grounded in tools ③ Learns across tries ④ Searches a tree 🔶 Self-refinedraft → critique → fixMon · the thesis Self-consistencyask 5 times, voteTue · BUY/HOLD/SELL ReActthink → tool → lookWed · valuation CRITICdraft, then check factsThu am · briefing Reflexionwrite the lesson, reuse itThu pm · screening Tree of thoughtsbranch, score, pruneFri am · the hedge LATStree + tools + lessonsFri pm · the trim + tools + memory + search more power → more LLM calls, more cost, more moving parts
Each group adds one new ingredient to the one before. LATS, on the far right, reuses almost everything to its left.
ParadigmThe question it answersLLM calls in our labNew here?
Self-refine"Can I make this draft better?"up to 7✅ new
Self-consistency"Would five analysts agree?"5idea from Section 2 · code new
ReAct"What does live data say?"one per stepidea from Section 2 · Claude Agent SDK new
CRITIC"Is every fact right?"draft + 2 per round✅ new
Reflexion"What did I learn last time?"+2 per failed try✅ new
Tree of thoughts 🔶"Which option is best — and how big?"13✅ new
LATS 🔶"Which sequence of real trades works?"12 (3 rounds)✅ new

The earnings week, day by day

MondaySelf-refineTurn raw fundamentals into a thesis the investment committee will accept.
TuesdaySelf-consistencyFive independent reads of the stock; the majority sets the recommendation.
WednesdayReActIs it expensive versus peers? Fetch live ratios before answering.
Thursday amCRITICEvery number in the morning briefing is checked against a source.
Thursday pmReflexionA screening mistake becomes a written lesson for next time.
Friday amTree of thoughtsCompare hedges before earnings, then size the best ones.
Friday pmLATSPlan a sequence of trims, learning from each plan that falls short.

Setup for every lab

Terminal · install once (Python 3.10+)
pip install anthropic claude-agent-sdk yfinance anyio python-dotenv
.env · next to your scripts (never commit this file)
ANTHROPIC_API_KEY=sk-ant-...
⚠️ Two things that trip people up
  • The model name lives in one constant, MODEL = "claude-sonnet-4-6". Any current Claude model works — change that one line.
  • Anthropic's Python SDK 1.0 (August 2026) removed temperature, top_p and top_k from messages.create. Older tutorials write temperature=0.8; with today's SDK that raises a TypeError. Our labs send it through extra_body={"temperature": 0.8} instead — you'll see why it matters in 6.3.

Labs 6.2, 6.3 and 6.7 call the Claude API directly with the anthropic package. Labs 6.4 and 6.8 use the Claude Agent SDK, which runs a full agent loop (tool calls, skills, permissions) for you — that's why their code is async.


Section 6 · Part 2 — Thinking inside the model

Monday and Tuesday: no tools, just better thinking

6.2Self-refine — draft, critique, polish

📅 Monday, 9 am. The first job of earnings week: turn a page of raw Apple fundamentals into an investment thesis the investment committee will sign off. First drafts are always weak — vague numbers, missing risks. So we let the model play three roles in turn: writer, reviewer, re-writer.
🧠 Analogy — one analyst, three hats

You write a memo (analyst hat). You put on the investment-committee hat and tear it apart: "Where's the growth rate behind that 28× P/E?" You switch back to the analyst hat and fix every point. Repeat until the committee hat says "no blocking issues". Nobody else was involved — the same person, the same brain, three different instructions. In code: the same LLM, three different prompts.

One LLM, three hats — ①②③ all call the same call_llm() with a different prompt Financial dataAAPL fundamentals ① Generateanalyst hat → draft ② Feedbackcommittee hat → critique NO_FURTHER_FEEDBACK?…or 3 rounds used up? ③ Refineanalyst hat → better draft Final thesis+ the audit log no yes again
The loop stops for one of two reasons: the reviewer writes the exact word NO_FURTHER_FEEDBACK, or the round budget runs out. Most of the improvement usually arrives in the first one or two rounds; after that you mainly pay for tokens.
💰 Finance corner: the words in Apple's fundamentals optional · glance over
  • Investment thesis — a short argument for owning a stock: what drives the business, whether the price is reasonable, what could go wrong.
  • Long-only — a fund that only buys shares (no short-selling). Its choices are "own more, own less, or don't own".
  • Forward P/E 28× — the share price is 28 times next year's expected earnings per share.
  • EV/EBITDA 22× — the whole company's value (shares + debt − cash) divided by its operating cash-type profit. Useful for comparing firms with different amounts of debt.
  • Net debt −$52B — negative net debt means more cash than debt: a "net cash" cushion.
  • Services at ~70% gross margin — app store, iCloud, payments: small slice of revenue, but very profitable, so the mix matters.

The setup — and why one helper is enough

Python · self_refine.py · setup and the one LLM helper
import os

import anthropic
from dotenv import load_dotenv

load_dotenv()                                   # copies .env into os.environ
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"                     # any current Claude model works
MAX_ITERATIONS = 3                              # at most 3 feedback → refine rounds


def call_llm(prompt: str, max_tokens: int = 1024) -> str:
    """One plain LLM call. All three roles below use THIS same function."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=max_tokens,
        messages=[{"role": "user", "content": prompt}],
    )
    return response.content[0].text             # the reply's text

Everything else in this lab is just prompts passed into call_llm. That's the whole trick of self-refine: no second model, no fine-tuning, no extra infrastructure. response.content[0].text unwraps the reply: content is a list of blocks, and the first block holds the text.

Hat ① — the generator

Python · self_refine.py · generate_initial_thesis
def generate_initial_thesis(financials: str) -> str:
    """Role 1 — the analyst writes a first draft."""
    prompt = f"""You are a senior equity analyst at a long-only asset management firm.
Draft a concise investment thesis based on the following financial data:

{financials}

Your thesis should cover: key business drivers, valuation, and 2-3 key risks.
Cite only metrics present in the data above; flag any outside claim as [unverified].
Write 1-2 sentences for each section. Be concise."""
    return call_llm(prompt)
  1. A role ("senior equity analyst at a long-only firm") sets the tone and what "good" looks like.
  2. A fixed shape — drivers, valuation, 2–3 risks, 1–2 sentences each. The reviewer and re-writer will use the same sections, so all three hats talk about the same document.
  3. A grounding rule — "cite only metrics in the data; flag anything else as [unverified]". This is how you stop the model filling gaps from memory.

Hat ② — the feedback provider

Python · self_refine.py · get_feedback
def get_feedback(thesis: str, financials: str, history_feedback: str) -> str:
    """Role 2 — the investment committee reviews the draft."""
    prompt = f"""You are a critical investment committee reviewer.
Review the following investment thesis and provide specific, actionable feedback.
Identify missing information, weak arguments, or factual gaps.
Ground your feedback only on the metrics present in the provided data
[Original query]; flag any outside claim as [unverified].
Your feedback should cover the thesis sections: key business drivers,
valuation, and 2-3 key risks.
If no issue would block investment-committee approval, respond with exactly:
NO_FURTHER_FEEDBACK
Be concise.

Original query:
{financials}

Previous theses and feedback:
{history_feedback}

Thesis to provide feedback on:
{thesis}

Feedback:"""
    return call_llm(prompt)
  1. The stop word. "If nothing blocks approval, respond with exactly NO_FURTHER_FEEDBACK." A fixed word (a sentinel) is easy for code to detect — the loop checks for it with startswith.
  2. Same data, same sections. The reviewer may only criticise using the numbers the writer had. Otherwise it would demand facts nobody can supply, and the loop would never end.
  3. The history. history_feedback holds every earlier draft and critique, so round 2's feedback can say "resolved: …" instead of repeating round 1.

Hat ③ — the refiner

Python · self_refine.py · refine_thesis
def refine_thesis(thesis: str, feedback: str, financials: str,
                  history_feedback: str) -> str:
    """Role 3 — the analyst rewrites the draft to answer every comment."""
    prompt = f"""You are a senior equity analyst.
Revise the following investment thesis based on the reviewer feedback below.
Produce an improved version that directly addresses each point in the feedback.
Cite only metrics present in the provided data [Original query]; flag any
outside claim as [unverified].
Keep the same sections as the original: key business drivers, valuation,
and 2-3 key risks. Write 1-2 sentences for each section. Be concise.

Original query:
{financials}

Previous theses and feedback:
{history_feedback}

Original thesis to revise:
{thesis}

Reviewer feedback:
{feedback}

Revised thesis:"""
    return call_llm(prompt, max_tokens=2048)

The refiner receives four things — the data, the history, the current draft and the new critique — and must "directly address each point". It gets max_tokens=2048 (double the others) because a revised thesis is often longer.

The loop — follow the variables

Python · self_refine.py · self_refine_thesis
def self_refine_thesis(financials: str) -> tuple[str, str]:
    print("[STEP 1] Generating initial thesis ...")
    thesis = generate_initial_thesis(financials)              # ① draft v0
    history_feedback = ""                                     # ② empty audit log
    print(f"Initial thesis:\n{thesis}\n")

    for iteration in range(1, MAX_ITERATIONS + 1):            # ③ 1, 2, 3
        print(f"[STEP 2] Iteration {iteration} -- getting feedback ...")
        feedback = get_feedback(thesis, financials, history_feedback)
        print(f"Feedback:\n{feedback}\n")
        if feedback.strip().startswith("NO_FURTHER_FEEDBACK"):  # ④ early stop
            print("Stopping: the reviewer has no blocking issues left.")
            break
        history_feedback += (                                  # ⑤ remember this round
            f"Iteration: {iteration}\nThesis: {thesis}\nFeedback: {feedback}\n\n"
        )
        print(f"[STEP 3] Iteration {iteration} -- refining thesis ...")
        thesis = refine_thesis(thesis, feedback, financials,   # ⑥ overwrite with v+1
                               history_feedback)
        print(f"Refined thesis:\n{thesis}\n")

    return thesis, history_feedback                           # ⑦ best draft + audit log
  1. thesis starts as draft v0. It is overwritten at every refinement, so it always holds the best version so far.
  2. history_feedback starts as an empty string — the audit log.
  3. range(1, MAX_ITERATIONS + 1) gives 1, 2, 3 — counting from 1 makes the printed round numbers human-friendly.
  4. Early stop. feedback.strip().startswith("NO_FURTHER_FEEDBACK") — strip() removes stray spaces and newlines first. break jumps out of the loop straight to the return.
  5. history_feedback += … appends this round's draft and critique. Notice it happens before refining, so the refiner sees the round it is fixing.
  6. thesis = refine_thesis(...) — draft v1, v2…
  7. Returns two things as a tuple: the final thesis and the audit log. The caller unpacks them: final_thesis, audit_log = self_refine_thesis(...).
Python · self_refine.py · run it
FINANCIALS = """
----- AAPL -----
Revenue FY2023: $383B (+2% YoY)
Services Revenue: $78B (+16% YoY), Gross Margin ~70%
Net Income: $97B
P/E (forward): 28x | EV/EBITDA: 22x
Cash & Equivalents: $62B | Net Debt: -$52B (net cash)
"""

if __name__ == "__main__":
    # Note: the prompt grows a little every round, because history_feedback grows.
    final_thesis, audit_log = self_refine_thesis(FINANCIALS)
    print("FINAL THESIS:\n", final_thesis)
🧪 Simulation · watch one real run, variable by variable

Seven steps from draft to approval

The mini loop in the panel (and the big diagram above) lights up as you click. Watch history_feedback — and the prompt-size bars — grow.

What the run printed (shortened)

[STEP 2] Iteration 1 -- Feedback ### Summary of Blocking Items | Issue | Severity | | Services compounding assertion unsupported | High | | No forward growth rate to contextualise 28x P/E | High | | Hardware revenue characterisation inferred | Medium | | Net cash figure imprecision ($52B vs $62B) | Medium | The thesis is not ready for approval in current form. [STEP 2] Iteration 2 -- Feedback Resolved: hardware revenue now flagged as inferred; Services claim removed. No blocking items remain. Two medium items to address. [STEP 2] Iteration 3 -- Feedback NO_FURTHER_FEEDBACK Stopping: the reviewer has no blocking issues left.

A sample run; wording changes every time. Notice the reviewer catching a real slip: the draft mixed up cash ($62B) and net cash ($52B).

⚠️ Three cautions
  • Keep all three prompts aligned — same data, same sections. If the reviewer asks for sections the writer never had, the loop drifts.
  • The prompt grows every round because the history grows (see the bars in the simulation). Watch cost and context limits in production.
  • Blind spots survive. The critic is the same model with the same knowledge. If it doesn't know something, no amount of self-critique will discover it. That's why we'll add tools on Wednesday.
💡 Why finance teams like it

The returned history_feedback is an audit trail: every draft and every critique, in order. If compliance asks "why does the memo say this?", you can show exactly how it got there.


6.3Self-consistency — five analysts, one vote

📅 Tuesday. The thesis is drafted. Now the desk needs the call itself: BUY, HOLD or SELL on ACME Corp. Rather than trusting one line of reasoning, we ask the model five separate times and let the majority decide.

Where the diversity comes from: sampling

An LLM writes one word (token) at a time. At each step it has a probability for every possible next word. Greedy decoding always takes the top word — ask five times, get the same essay five times. Sampling draws the next word at random, weighted by those probabilities, so each run can wander down a slightly different path of reasoning. Three knobs control how adventurous the draw is:

KnobWhat it doesAnalogy
TemperatureSharpens (< 1) or flattens (> 1) all the probabilities. 0.7–0.9 is typical for self-consistency in finance.How bold the analyst feels today
Top-kKeep only the k most likely words, re-scale them to add up to 100%, drop the rest."Only consider the top 3 ideas"
Top-p (nucleus)Keep the smallest group of top words whose probabilities add up to p (e.g. 85%). Few words when the model is sure, more when it isn't."Consider ideas until you've covered 85% of your belief"
🧪 Simulation · the sampling lab

The model is about to write the next word in "…at 28× earnings, the stock looks ____"

At temperature 1 with no filter, these are its probabilities (35%, 25%, 22%, 10%, 5%, 5%). Move the knobs, then draw 20 words.

1.0
Each draw is one "analyst" finishing the sentence.
⚠️ Newer models and the temperature knob

Some of Anthropic's newest models no longer accept a temperature setting at all. That's fine for self-consistency: their replies are still sampled, so five calls still give five different paths. If your model rejects the setting, delete that one line — and, if the paths come back too similar, ask each "analyst" to start from a different angle (earnings, valuation, risks).

Step 1 · The constants and the answer contract

Python · self_consistency.py · setup and the system prompt
import os
from collections import Counter

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"
N_PATHS = 5                 # how many independent analysts vote
TEMPERATURE = 0.8           # enough randomness for different reasoning paths

SYSTEM_PROMPT = """You are a financial analyst.
Analyze the stock summary of a company and provide a final recommendation:
BUY, HOLD, or SELL.
Reason step by step through the investment case. Cover:
1. Earnings quality and trajectory
2. Valuation vs. peers and history
3. Key risks and near-term catalysts
4. Overall risk/reward balance
Be concise: 1-2 sentences per point.
End your response with exactly one line in this plain format (no markdown,
no bold, no asterisks):
RECOMMENDATION: <BUY|HOLD|SELL>"""
  1. N_PATHS = 5, TEMPERATURE = 0.8 — five analysts, moderately adventurous. At 0 they'd all write the same thing; much above 1 they'd ramble.
  2. Four fixed angles (earnings, valuation, risks, risk/reward). Every analyst covers the same ground, so when they disagree it's a real difference of judgement, not just a different topic.
  3. The contract line — RECOMMENDATION: <BUY|HOLD|SELL>, plain text, no bold. A vote only counts if code can read it.

Step 2 · One analyst = one API call

Python · self_consistency.py · sample_reasoning_path
def sample_reasoning_path(stock_summary: str) -> str:
    """One analyst = one ordinary API call."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        system=SYSTEM_PROMPT,
        messages=[{"role": "user", "content": stock_summary}],
        # Anthropic SDK 1.0+ removed temperature from the method signature,
        # so we send it in extra_body. On SDK < 1.0 write temperature=TEMPERATURE.
        # If your model rejects temperature, delete this line: replies are
        # sampled (a bit random) anyway.
        extra_body={"temperature": TEMPERATURE},
    )
    return response.content[0].text

No tools, no memory, no conversation: each call starts fresh, which is exactly what "independent" means here. The system= argument carries the analyst instructions; the stock summary is the user message. extra_body is the SDK's "send these extra fields as they are" door — today's way to pass temperature.

Step 3 · Reading the vote: a forgiving but strict parser

Python · self_consistency.py · extract_recommendation
def extract_recommendation(path: str) -> str | None:
    """Find 'RECOMMENDATION: X' near the end, tolerating stray formatting."""
    for line in reversed(path.strip().split("\n")):           # ① last line first
        cleaned = line.strip().lstrip("*_`# ").upper()        # ② drop **, #, `, _
        if cleaned.startswith("RECOMMENDATION:"):             # ③ the contract line?
            label = cleaned.replace("RECOMMENDATION:", "").strip().strip("*_`. ")
            if label in ("BUY", "HOLD", "SELL"):              # ④ only legal labels
                return label
    return None                                               # ⑤ no valid line found
  1. reversed(path.strip().split("\n")) — split the essay into lines and read them from the bottom up, because the contract line should be last.
  2. lstrip("*_`# ") removes any of those characters from the start of the line (bold stars, heading hashes, backticks), then .upper() makes "Recommendation" and "RECOMMENDATION" the same.
  3. startswith("RECOMMENDATION:") — is this the contract line?
  4. Only three legal labels. "STRONG BUY" or "ACCUMULATE" is rejected rather than guessed.
  5. return None — an unreadable vote is thrown away, never invented.
🧪 Simulation · parser playground

Type or pick an analyst's last lines — watch the parser work line by line

Step 4 · Counting the votes

Python · self_consistency.py · self_consistency_recommend
def self_consistency_recommend(stock_summary: str, n_paths: int = N_PATHS) -> dict:
    paths, recommendations = [], []
    print(f"[STEP 1] Sampling {n_paths} paths at temperature={TEMPERATURE}.\n")
    for i in range(1, n_paths + 1):
        print(f"[STEP 2] Sampling reasoning path {i}/{n_paths} ...")
        path = sample_reasoning_path(stock_summary)           # one analyst's notes
        recommendation = extract_recommendation(path)         # BUY / HOLD / SELL / None
        paths.append(path)
        recommendations.append(recommendation)
        print(f"--- Path {i} reasoning ---\n{path}\n")
        print(f"[Path {i}] Parsed recommendation: {recommendation}\n")

    print("[STEP 3] Aggregating answers via majority vote ...")
    valid = [r for r in recommendations if r is not None]     # drop unreadable paths
    if not valid:
        raise ValueError("No path ended with a valid RECOMMENDATION line.")
    vote_counts = Counter(valid)                              # {'HOLD': 3, 'SELL': 2}
    final_recommendation, top_votes = vote_counts.most_common(1)[0]
    agreement = top_votes / len(valid)                        # 3/5 = 0.6
    return {
        "final_recommendation": final_recommendation,
        "vote_counts": dict(vote_counts),
        "agreement": agreement,
        "needs_human_review": agreement < 0.8,                # a split vote = ambiguity
        "paths": paths,                                       # the audit trail
    }
LineVariable after it runs
recommendations (after the loop)["HOLD", "SELL", "HOLD", None, "HOLD", …] — one entry per path, None if unreadable
valid = [r for r in … if r is not None]["HOLD", "SELL", "HOLD", "SELL", "HOLD"]
vote_counts = Counter(valid)Counter({"HOLD": 3, "SELL": 2}) — a dictionary that counts for you
vote_counts.most_common(1)[("HOLD", 3)] — a list with the single top pair
final_recommendation, top_votes = …[0]"HOLD" and 3 (tuple unpacking)
agreement = top_votes / len(valid)0.6 → below 0.8, so needs_human_review = True
💡 Two small safety additions

If every path is unreadable, valid is empty and most_common(1)[0] would crash with an IndexError — so we raise a clear error instead. And we return agreement and needs_human_review, because the size of the majority is information the portfolio manager needs. (In a tie, Counter keeps whichever label it saw first — another reason to flag split votes.)

Python · self_consistency.py · run it on ACME Corp
STOCK_SUMMARY = """
Company: ACME Corp (ticker: ACME)
Latest Earnings:
- Revenue: $94.9B (+5% YoY), beat consensus by 1.2%
- EPS: $1.56, beat consensus by $0.04
- Net margin: 25.5% (down 80bps YoY)
- Free Cash Flow: $18.1B
Valuation:
- P/E: 28x (sector median: 22x)
- EV/EBITDA: 18x (sector median: 14x)
- PEG ratio: 1.9
Guidance:
- FY2025 revenue guidance raised to $97-99B
- Management flagged EU regulatory headwinds in H2
Market Context:
- Sector under pressure from rising rates
- Main competitor cut guidance last week
"""

if __name__ == "__main__":
    result = self_consistency_recommend(STOCK_SUMMARY)
    print(f"\n=== FINAL RECOMMENDATION: {result['final_recommendation']} ===")
    print(f"Vote breakdown: {result['vote_counts']}  "
          f"(agreement {result['agreement']:.0%})")
    if result["needs_human_review"]:
        print("Split vote -> send to a human analyst before acting.")
[STEP 2] Sampling reasoning path 1/5 ... **1. Earnings Quality and Trajectory** Revenue and EPS both beat consensus … the 80bps net margin compression is a concern … **2. Valuation vs. Peers** P/E 28x vs. 22x; EV/EBITDA 18x vs. 14x … little room for error. **3. Key Risks and Catalysts** EU regulatory headwinds in H2 … raised FY2025 guidance … **4. Overall Risk/Reward** … the risk/reward does not favor new buyers at this level. RECOMMENDATION: HOLD [Path 1] Parsed recommendation: HOLD … === FINAL RECOMMENDATION: HOLD === Vote breakdown: {'HOLD': 3, 'SELL': 2} (agreement 60%) Split vote -> send to a human analyst before acting.
VoteWhat it tells the desk
5–0Strong agreement; reruns will very likely give the same answer.
4–1Clear majority; worth reading the one dissent.
3–2Genuinely ambiguous — a rerun could flip it. Send to a human.
💰 Finance corner: reading ACME's summary optional · glance over
  • Beat consensus — results came in above what analysts, on average, expected.
  • Net margin down 80 bps — profit per dollar of sales fell by 0.80 percentage points (100 basis points = 1%).
  • Free cash flow — cash left after running the business and investing in it.
  • P/E 28× vs sector median 22× — investors pay about 27% more per dollar of profit than for a typical peer.
  • PEG 1.9 — P/E divided by expected growth. Around 1 is often called "fair"; 1.9 means you pay a lot for the growth.
  • Guidance raised — management now expects more revenue than before. Good news, but "EU regulatory headwinds" is a warning.
⚠️ Lessons to carry into production
  • Keep the temperature fixed across the five paths — the vote assumes they're drawn the same way.
  • It shines on ambiguous calls. For a famous mega-cap the model "already has an opinion", all five agree, and the vote adds little.
  • Closed answers only. Voting works for BUY / HOLD / SELL, not for essays or price forecasts.
  • Five times the cost — and no protection from shared bias. If all five paths inherit the same wrong belief, the majority is confidently wrong. Like self-refine, it never looks at live data.

Section 6 · Part 3 — Thinking with tools

Wednesday and Thursday morning: check the world, not your memory

6.4ReAct with the Claude Agent SDK — is the stock expensive?

📅 Wednesday. The portfolio manager asks: "Is Apple overvalued relative to the Technology sector, and what does that mean for our long-only portfolio?" No amount of thinking can answer that from memory — prices move every second. The agent must fetch live data, look at it, think, and fetch again.

Five kinds of "Thought" a good agent writes

Kind of thoughtExample from today's task
Break the task down"I need Apple's P/E, then the sector median to compare against."
Read the observation"The tool says P/E 34.4; the sector median is 29.6."
Do the arithmetic"34.4 ÷ 29.6 = 1.16, so Apple trades at a 16% premium."
Try another way"That query returned nothing — I'll search by a different identifier."
Wrap up"Given valuation, growth and the balance sheet, my conclusion is…"
💰 Finance corner: the valuation toolkit optional · glance over
  • P/E — price ÷ last 12 months' earnings per share. "How many years of profit am I paying for?"
  • EV/EBITDA — like P/E but for the whole company including its debt, so firms with very different borrowing can be compared fairly.
  • P/B (price-to-book) — price ÷ accounting net worth. Can look absurd (Apple ≈ 47×) when a company has bought back lots of shares, which shrinks book value.
  • PEG — P/E ÷ growth rate. Above ~2 means you pay a lot for each unit of growth.
  • Sector median — the middle value of the peer group. We use the median, not the average, because one high-flyer can drag an average up: peers at 20, 22, 25, 28 and 105 have an average of 40 but a median of 25.
  • Net cash — cash minus debt. Negative means net debt.
  • Debt-to-equity — debt ÷ shareholders' equity. Yahoo reports 80.0 when it means 0.8×, hence our / 100.
Your Python process · MCP server "finance" run_react_agent()your question in Claudevia ClaudeSDKClient get_valuation_ratios get_sector_median_pe get_balance_sheet yfinanceYahoo Finance data tool call streamed messages AssistantMessageTextBlock → [THOUGHT] · ToolUseBlock → [ACTION] UserMessageToolResultBlock → [OBSERVATION] finalthe last TextBlock = the answer
The SDK runs the loop: Claude decides which tool to call, the SDK calls your Python function, sends the result back to Claude, and repeats. Your code only has to listen to the stream of messages and label them.

Tool 1 · valuation ratios

Python · react_agent.py · get_valuation_ratios
@tool(
    "get_valuation_ratios",                                               # ① name
    "Retrieve valuation ratios (P/E, EV/EBITDA, P/B, PEG) for a given ticker.",  # ② when to use
    {"ticker": str},                                                      # ③ inputs
)
async def get_valuation_ratios(args):
    info = yf.Ticker(args["ticker"]).info              # a big dict of Yahoo fields
    data = {
        "PE": info.get("trailingPE"),
        "EV_EBITDA": info.get("enterpriseToEbitda"),
        "PB": info.get("priceToBook"),
        "PEG": info.get("pegRatio") or info.get("trailingPegRatio"),
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}  # ④ MCP format
  1. The tool's name — what Claude calls it. On the wire it becomes mcp__finance__get_valuation_ratios.
  2. The description — Claude reads this to decide when to use the tool. Write it like a label on a drawer.
  3. The input schema {"ticker": str} — the SDK turns it into a JSON schema; your function receives a dictionary called args, so you read args["ticker"].
  4. The return shape {"content": [{"type": "text", "text": …}]} is the standard MCP envelope: a list of content blocks. We put our numbers in as JSON text.

info.get("pegRatio") or info.get("trailingPegRatio") means "use pegRatio; if it's missing (None), fall back to trailingPegRatio". Yahoo fills different fields for different companies.

Tool 2 · a live sector benchmark

Python · react_agent.py · get_sector_median_pe
# A handful of large-cap tickers per sector, used to compute live sector medians.
SECTOR_TICKERS = {
    "Technology": ["MSFT", "NVDA", "GOOGL", "META", "ORCL",
                   "CRM", "ADBE", "AMD", "INTC", "CSCO"],
    "Healthcare": ["JNJ", "UNH", "PFE", "MRK", "ABBV",
                   "TMO", "ABT", "LLY", "BMY", "AMGN"],
    "Financials": ["JPM", "BAC", "WFC", "GS", "MS",
                   "C", "BLK", "AXP", "USB", "PNC"],
}


@tool(
    "get_sector_median_pe",
    "Retrieve the median P/E and EV/EBITDA for a given GICS sector.",
    {"sector": str},
)
async def get_sector_median_pe(args):
    pes, evs = [], []
    for tk in SECTOR_TICKERS.get(args["sector"], []):    # unknown sector → []
        info = yf.Ticker(tk).info
        if info.get("trailingPE"):                        # skip missing values
            pes.append(info["trailingPE"])
        if info.get("enterpriseToEbitda"):
            evs.append(info["enterpriseToEbitda"])
    data = {
        "median_pe": round(statistics.median(pes), 2) if pes else None,
        "median_ev_ebitda": round(statistics.median(evs), 2) if evs else None,
        "sample_size": len(pes),                          # how many names counted
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}

For each of ten large-cap peers it reads two ratios, skips missing ones (if info.get(...)), and returns the medians plus sample_size — how many peers actually counted. If only 3 of 10 had data, the agent can say the benchmark is weak. SECTOR_TICKERS.get(sector, []) returns an empty list for an unknown sector, so the medians come back as None instead of crashing.

Tool 3 · balance-sheet check

Python · react_agent.py · get_balance_sheet
@tool(
    "get_balance_sheet",
    "Retrieve balance sheet summary (net cash in $bn, debt-to-equity) for a ticker.",
    {"ticker": str},
)
async def get_balance_sheet(args):
    info = yf.Ticker(args["ticker"]).info
    cash = info.get("totalCash") or 0
    debt = info.get("totalDebt") or 0
    de = info.get("debtToEquity")                         # Yahoo gives 80.0 for 0.8x
    data = {
        "net_cash_bn": round((cash - debt) / 1e9, 1),     # negative = net debt
        "debt_to_equity": round(de / 100, 2) if de else None,
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}

Why this tool? After "it looks expensive", the next analyst question is: is the premium backed by a fortress balance sheet, or is it just a rich multiple? (cash - debt) / 1e9 converts dollars to billions; or 0 turns a missing value into zero so the subtraction never fails.

The ReAct prompt — short on purpose

Python · react_agent.py · SYSTEM_PROMPT
SYSTEM_PROMPT = """You are a financial research analyst following the ReAct pattern.
For every step, first emit a 'Thought:' line explaining your plan or
interpretation, then call the appropriate tool. After each observation, briefly
reason about what it means before the next step. Conclude with a clear,
well-grounded recommendation."""

Three jobs in four sentences: a role, the Thought → tool → reflect rhythm, and a concrete recommendation at the end. Over-detailed prompts make traces rigid and repetitive; a short one lets the agent adapt to what each observation says.

The agent loop

Python · react_agent.py · run_react_agent
async def run_react_agent(question: str) -> str:
    server = create_sdk_mcp_server(                            # ① a tool "shop"
        name="finance",
        version="1.0.0",
        tools=[get_valuation_ratios, get_sector_median_pe, get_balance_sheet],
    )
    options = ClaudeAgentOptions(                              # ② the agent's rules
        model="claude-sonnet-4-6",
        system_prompt=SYSTEM_PROMPT,
        mcp_servers={"finance": server},
        allowed_tools=[                                        # mcp__<server>__<tool>
            "mcp__finance__get_valuation_ratios",
            "mcp__finance__get_sector_median_pe",
            "mcp__finance__get_balance_sheet",
        ],
    )
    final = ""
    async with ClaudeSDKClient(options=options) as client:    # ③ open the session
        await client.query(question)                           # ④ ask
        async for msg in client.receive_response():            # ⑤ stream every message
            if isinstance(msg, AssistantMessage):              # Claude speaking
                for block in msg.content:
                    if isinstance(block, TextBlock):           # → THOUGHT (or answer)
                        print(f"\n[THOUGHT] {block.text.strip()}")
                        final = block.text
                    elif isinstance(block, ToolUseBlock):      # → ACTION
                        print(f"\n[ACTION] {block.name}({block.input})")
            elif isinstance(msg, UserMessage):                 # tool results come back
                content = msg.content if isinstance(msg.content, list) else []
                for block in content:
                    if isinstance(block, ToolResultBlock):     # → OBSERVATION
                        print(f"[OBSERVATION] {block.content}")
    return final                                               # ⑥ the last text = answer
  1. create_sdk_mcp_server bundles the three functions into a tool "shop" named finance, running inside your own Python process — no separate server to start.
  2. ClaudeAgentOptions holds the rules: model, prompt, which servers exist, and allowed_tools — the tools that may run without asking permission. Names follow the pattern mcp__<server>__<tool>.
  3. async with ClaudeSDKClient(...) as client opens a session and closes it cleanly afterwards.
  4. await client.query(question) sends the question.
  5. async for msg in client.receive_response() — messages arrive one by one as the agent works. isinstance checks sort them: Claude speaking (AssistantMessage) or tool results coming back (UserMessage), and inside each, the block types.
  6. final is overwritten by every text block, so after the loop it holds the last one — the recommendation.
Streamed messageBlock inside itReAct label printed
AssistantMessageTextBlock[THOUGHT] — and the final answer
AssistantMessageToolUseBlock[ACTION] tool name + inputs
UserMessageToolResultBlock[OBSERVATION] the tool's output

Why are tool results inside a UserMessage? In the chat format, everything that isn't Claude talking is on the "user" side of the conversation — including tool results.

Python · react_agent.py · run it
if __name__ == "__main__":
    question = (
        "Is Apple (AAPL) overvalued relative to the Technology sector? "
        "What does this imply for a long-only portfolio?"
    )
    answer = asyncio.run(run_react_agent(question))
    print("\n" + "=" * 60)
    print("FINAL ANSWER")
    print("=" * 60)
    print(answer)
🧪 Simulation · the message sorter

Replay a real run: which if branch catches each message?

The final answer (shortened)

Apple (AAPL) Valuation Analysis vs. Technology Sector | Metric | AAPL | Tech median | Premium | | P/E | 34.4× | 29.6× | +16.2% | | EV/EBITDA | 26.2× | 24.0× | +9.2% | | PEG | 2.49 | — | expensive (>2.0) | | P/B | 47.4× | — | distorted by buybacks | | Net cash | −$16.2bn | — | net debt, not net cash | Bottom line: AAPL appears moderately overvalued relative to the sector. For a long-only portfolio: trim, or hold at benchmark weight — don't add here.

Sample run with live data; your numbers will differ. The premiums are simple division: 34.36 ÷ 29.58 = 1.162 → +16.2%.

💡 Two things the trace taught us
  • The first action may be a ToolSearch — the SDK can list tools by name only, and Claude loads their full descriptions before using them. Normal; not a bug.
  • Claude fired all three lookups at once, because they don't depend on each other — one step instead of three, same audit trail.
⚠️ Lessons
  • The trace is as important as the answer. It shows which ratios were fetched, which peer group was used and how the balance sheet changed the view — that's what makes the recommendation defensible.
  • Tool design decides quality. Small, focused tools that combine well beat one giant "do everything" tool.
  • The final answer also prints with a [THOUGHT] label — it's a TextBlock too. final is how you tell it apart.

6.5CRITIC — fact-check before it reaches the PM

📅 Thursday, 7:30 am. Every morning the desk sends a briefing on its top holdings: opening price, trailing-twelve-month revenue, latest dividend, and a short story tying them together. A wrong number here gets repeated on a client call. The rule: every figure is checked against an authoritative source before it goes out.
🧠 Analogy — the newspaper sub-editor

A reporter files a story. The sub-editor doesn't ask "does this feel right?" — she opens the terminal and checks every number. Wrong ones go back with a note: "you wrote 78.29; the exchange says 78.37". The reporter fixes them, and she checks again. Self-refine was the reporter re-reading their own draft; CRITIC brings in the terminal.

Draft briefingfrom a ReAct agent / RAG Verifyask market-data tools Critique"what's wrong above?" Any issues left?…or rounds used up Correctfix only what's flagged Publish+ critique trail yes no check again 📈 prices · 📊 fundamentals · 📅 dividends
The difference from self-refine is one box: Verify asks outside tools, so the critique is based on evidence instead of the model's own opinion. The loop stops when the critique is clean or the round budget runs out.

In the original research version, the first draft comes from the model's memory alone. In finance that's the wrong starting point — the draft should already come from a tool-using agent (like Wednesday's ReAct agent). CRITIC then sits on top as an independent checker. Even a tool-built draft can carry a stale quote or a copy-paste slip, and those are exactly what this layer catches. The checker can use different tools — even a different model — from the writer.

🧪 Simulation · be the CRITIC

Coca-Cola's morning briefing — verify, critique, correct

The draft numbers are editable. The "tools" return the authoritative values. Try the 0.5% tolerance and watch a wrong price slip through.

The shape of the loop, in code

CRITIC has no separate lab — it's the self-refine loop with a tool-based check in the middle. This small sketch runs offline and shows the shape. In a real system fetch_sources calls your market-data APIs and correct is an LLM rewriting the briefing.

Python · critic_sketch.py · verify (simplified sketch)
def verify(claims: dict, sources: dict, tolerance: float = 0.0005) -> list[str]:
    """Compare every number in the draft with the source (0.0005 = 0.05% slack)."""
    issues = []
    for field, source_value in sources.items():
        claimed = claims.get(field)
        if claimed is None:
            issues.append(f"{field}: missing from the draft (source says {source_value})")
        elif abs(claimed - source_value) > tolerance * abs(source_value):
            issues.append(f"{field}: draft says {claimed}, source says {source_value}")
    return issues                       # [] means "nothing wrong" → stop
  1. One loop over the source's fields — for each authoritative value, look up what the draft claimed with claims.get(field) (None if the draft forgot it).
  2. A relative tolerance: abs(claimed - source) > tolerance * abs(source). 0.0005 means "more than 0.05% off". A fixed gap like "±0.10" would be too strict for a $1,000 stock and too loose for a $2 one.
  3. An empty list means clean. The loop below uses that as its stop signal.
Python · critic_sketch.py · critic_loop (simplified sketch)
def critic_loop(claims: dict, fetch_sources, correct, max_iters: int = 3):
    audit_trail = []
    for i in range(1, max_iters + 1):
        sources = fetch_sources()                     # VERIFY: ask the tools
        issues = verify(claims, sources)              # CRITIQUE: what's wrong?
        audit_trail.append({"round": i, "issues": issues})
        if not issues:                                # clean → done
            break
        claims = correct(claims, issues, sources)     # CORRECT: an LLM in real life
    return claims, audit_trail
Python · critic_sketch.py · run it
if __name__ == "__main__":
    draft = {"open_price": 78.29, "ttm_revenue_bn": 45.0, "dividend_ps": 1.80}   # Coca-Cola

    def fetch_sources():          # stand-in for market-data / fundamentals / events APIs
        return {"open_price": 78.37, "ttm_revenue_bn": 46.0, "dividend_ps": 1.84}

    def correct(claims, issues, sources):   # stand-in for "LLM, fix these issues"
        return {**claims, **sources}

    final, trail = critic_loop(draft, fetch_sources, correct)
    for step in trail:
        print(step)
    print("Verified briefing numbers:", final)
{'round': 1, 'issues': ['open_price: draft says 78.29, source says 78.37', 'ttm_revenue_bn: draft says 45.0, source says 46.0', 'dividend_ps: draft says 1.8, source says 1.84']} {'round': 2, 'issues': []} Verified briefing numbers: {'open_price': 78.37, 'ttm_revenue_bn': 46.0, 'dividend_ps': 1.84}
💡 Let code compare, let the LLM write

In the research paper the critique itself is written by the LLM after reading the tool results. For numbers, we let plain code do the comparing — the same "code for facts, LLM for words" lesson from Section 5's validator. The LLM's job is to rewrite the briefing's sentences around the corrected numbers.

💰 Finance corner: the three briefing numbers optional · glance over
  • Opening price — the first traded price when the market opened today.
  • TTM revenue — trailing twelve months: the last four quarters added up. Always the most recent full year of sales, whatever the calendar says.
  • Dividend per share — cash paid to shareholders for each share they own (Coca-Cola pays quarterly).

The limit of CRITIC: every check starts from zero. If the drafting agent keeps making the same kind of mistake, CRITIC will catch it every single day — but nobody learns. That's Thursday afternoon's job.

6.6Reflexion — write the lesson down, read it next time

📅 Thursday afternoon. The screening agent checks companies against the desk's "buy list" checklist. It just flagged ShopCo, a big retailer, because its working capital is negative — "liquidity problem!". The senior analyst disagrees: for a retailer that collects from customers today and pays suppliers in 60 days, negative working capital is a sign of strength. How do we make sure the agent doesn't make the same mistake on the next retailer?
🧠 Analogy — a trader's journal

Good traders keep a journal. After a bad trade they don't retrain their brain; they write one sentence: "I sold too early because I misread the volume — next time, wait for the close." Before the next trade, they read the journal. Reflexion gives an agent exactly that: no change to the model's weights, just a growing notebook of plain-English lessons that goes into the prompt.

Taskscreen ShopCo ① Actordoes the work (ReAct/CoT)short-term memory: this try ② Evaluatorpass / fail (rubric) Passed? Done ③ Self-reflectionwrites a 1-line lesson Long-term memorylessons, not raw logs yes no read before the next try
Three roles — actor, evaluator, self-reflection (they can be one model with three prompts, or three models). Two memories: short-term is everything the actor did in this attempt; long-term is a short list of lessons from past failures, small enough to fit in every prompt.
Self-refineCRITICReflexion
Improves…one answerone answerthe next attempts
Feedback comes fromthe model itselfoutside toolsan evaluator's verdict
Remembers across tasks?nonoyes — written lessons
Desk examplepolish the thesischeck the briefingstop mis-flagging retailers

You built episodic memory in Section 2 — a journal of past runs. Reflexion stores something more focused: only lessons from failures, each one condensed into a sentence.

💰 Finance corner: working capital, and when "negative" is good optional · glance over

Working capital = short-term assets (cash, stock on shelves, money customers owe you) − short-term debts (bills you owe suppliers). Usually you want it positive: enough short-term money to pay short-term bills.

But think of a busy restaurant: diners pay at the table today, while the vegetable supplier is paid in 30 days. The restaurant runs on its suppliers' money — working capital is negative, and that's a strength. Big retailers and online platforms work the same way. A struggling manufacturer whose unpaid bills are piling up while cash shrinks also shows negative working capital — and there it is a red flag. Same number, different story: the industry decides.

🧪 Simulation · the screening agent's notebook

Screen three companies. Watch lessons appear — then try deleting one

The agent starts with an empty notebook and naively flags any negative working capital. Choose how good its self-reflections are, then click through. The notebook is plain text, so a compliance officer can delete a lesson (✕) — and the old mistake comes back.

Long-term memory (the notebook)

The shape of a reflexion loop

Like CRITIC, reflexion reuses parts you already have (a ReAct actor, a memory list), so there's no separate lab. Here is the loop with stand-in functions — it runs offline and prints Trial 1: FAIL … Trial 2: PASS.

Python · reflexion_shape.py · the loop (simplified sketch)
MAX_TRIALS = 3
memory: list[str] = []                        # long-term memory: lessons, not logs


def actor(task: str, lessons: list[str]) -> dict:
    """Does the screening. Real life: a ReAct agent with the lessons in its prompt."""
    knows = any("negative working capital" in l for l in lessons)
    return {"task": task, "flagged_wc": not knows}


def evaluator(trajectory: dict) -> bool:
    """Reward: did we get it right? (rubric, labelled examples or another model)"""
    return not trajectory["flagged_wc"]


def reflector(trajectory: dict, memory: list[str]) -> str:
    """Writes a short, human-readable lesson about the failure."""
    return ("I treated negative working capital as a red flag. For retailers and "
            "platforms with strong supplier terms it is often a strength; "
            "check the industry first.")


for trial in range(1, MAX_TRIALS + 1):
    trajectory = actor("Screen ShopCo for the buy list", lessons=memory)   # act
    passed = evaluator(trajectory)                                         # score
    print(f"Trial {trial}: {'PASS' if passed else 'FAIL'}  (lessons in memory: {len(memory)})")
    if passed:
        break
    memory.append(reflector(trajectory, memory))                          # learn
  1. memory lives outside the loop, so it survives from one trial to the next. That's the long-term memory.
  2. actor(task, lessons=memory) — in real life a ReAct agent whose prompt includes the lessons.
  3. evaluator(...) returns pass/fail: a rubric, labelled past examples, or another model.
  4. Only on failure does the reflector write a lesson, and memory.append(...) stores it.
⚠️ Strengths and limits
  • Fully transparent learning. Every lesson is a sentence a human can read, edit or delete. When a regulator asks "why did the agent's behaviour change?", you can show the note.
  • Only as good as its reflections. A vague or over-general lesson ("never flag negative working capital") can do more harm than no lesson — you just saw it in the simulation.
  • Pays off on repeated, similar tasks — screening hundreds of companies, not a one-off question.

Section 6 · Part 4 — Thinking as a search 🔶

Friday: explore the options before you commit

6.7Tree of thoughts — choose the hedgeAdvanced

📅 Friday, 2 pm. The desk holds 5,000 NVIDIA shares (~$5M). NVIDIA reports earnings tonight after the close, and option prices say the market expects a big move. A one-shot answer ("buy puts") isn't good enough for $5M. We want the agent to list the hedge ideas, score them, drop the weak ones, and only then work out the size of the best ones.
🧠 Analogy — a chess player

A chess player doesn't play the first move that comes to mind. She considers three or four candidate moves, glances at each, abandons the obviously bad ones and spends her thinking time on the two most promising lines. That's a tree of thoughts: branch, score, prune, go deeper.

Chain of thought Self-consistency Tree of thoughts one answer vote 8 7 6 ✕ 4 ✕ keep 2, go deeper
Chain of thought is a tree with one branch. Self-consistency grows several branches but only compares their final answers. Tree of thoughts compares partial answers at every level and only keeps growing the promising ones.
Design choiceWhat it meansIn our hedge lab
1 · Split the task into stepsWhich decision comes first, which second?Level 1 = which instrument; level 2 = what size / strikes
2 · Thought generatorProduces candidate next stepsOne call proposes 4 hedges (or 3 sizings) at once
3 · State evaluatorJudges how promising each partial plan isOne call per candidate returns a score 1–10 + reason
4 · Search strategyWhich branches to grow nextBeam search: keep the top 2, drop the rest
💰 Finance corner: the hedge menu optional · glance over
  • Hedge — a position that gains when your main holding loses. Insurance for a portfolio.
  • Put option — the right to sell a share at a fixed price (the strike) until expiry. If NVDA falls below the strike, the put gains. One contract covers 100 shares, so 5,000 shares need 50 contracts.
  • ATM / OTM — at-the-money: strike ≈ today's price. Out-of-the-money: strike below today's price — cheaper, but you absorb the first part of a fall (like an insurance deductible).
  • Put spread — buy one put, sell a lower one. Cheaper, but protection stops at the lower strike.
  • Covered call — sell someone the right to buy your shares higher up. You collect cash now; it barely protects against a big drop.
  • SMH — a semiconductor ETF (a basket of chip stocks) where NVDA is the biggest member. Hedging with it is cheaper, but it won't move exactly like NVDA: that mismatch is basis risk.
  • Implied volatility — how big a move option prices "expect". Before earnings it spikes, so options are expensive.

Two forms: one for ideas, one for scores

Python · tot_hedge.py · JSON schemas and the ask_json helper
HEDGES_SCHEMA = {                       # "give me a list of named ideas"
    "type": "object",
    "properties": {
        "candidates": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "rationale": {"type": "string"},
                },
                "required": ["name", "rationale"],
                "additionalProperties": False,
            },
        }
    },
    "required": ["candidates"],
    "additionalProperties": False,
}

SCORE_SCHEMA = {                        # "give me one number and why"
    "type": "object",
    "properties": {
        "score": {"type": "integer"},
        "reasoning": {"type": "string"},
    },
    "required": ["score", "reasoning"],
    "additionalProperties": False,
}


def ask_json(prompt: str, schema: dict) -> dict:
    """One LLM call whose reply MUST match `schema` (structured outputs)."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        output_config={"format": {"type": "json_schema", "schema": schema}},
        messages=[{"role": "user", "content": prompt}],
    )
    text = next(b.text for b in response.content if b.type == "text")  # first text block
    return json.loads(text)                                            # JSON text → dict
  1. HEDGES_SCHEMA — "a list of candidates, each with a name and a rationale". Used by both generators: hedge ideas and sizing ideas have the same shape.
  2. SCORE_SCHEMA — "one integer and a reason". Used by both evaluators.
  3. "required" must list real field names and "additionalProperties": False forbids extra fields — together they make the reply predictable enough for code to sort.
  4. output_config={"format": {"type": "json_schema", ...}} is Claude's structured-output switch: the reply text is guaranteed to be JSON matching the schema.
  5. next(b.text for b in response.content if b.type == "text") — walk through the reply's blocks and take the first text block. json.loads turns that text into a Python dictionary.

Level 1 — which hedge?

Python · tot_hedge.py · generator and evaluator, level 1
def generate_hedges(portfolio: str, scenario: str, n: int) -> list[dict]:
    """Thought generator, level 1: n hedge ideas in ONE call."""
    prompt = (
        f"Portfolio: {portfolio}\nStress scenario: {scenario}\n"
        f"Propose {n} distinct hedge candidates, each with a short rationale."
    )
    return ask_json(prompt, HEDGES_SCHEMA)["candidates"]


def score_hedge(portfolio: str, scenario: str, hedge: dict) -> dict:
    """State evaluator, level 1: score one idea from 1 to 10."""
    prompt = (
        f"Portfolio: {portfolio}\nStress scenario: {scenario}\n"
        f"Candidate hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Score this hedge from 1 to 10 on protection, cost, and basis risk."
    )
    return ask_json(prompt, SCORE_SCHEMA)

The generator asks for all n ideas in a single call. Because the model writes idea 2 while seeing idea 1, the ideas come out more different from each other — and it's cheaper than four separate calls. The evaluator is a small, focused call per idea, scoring three things a risk manager cares about: protection, cost and basis risk.

Level 2 — how big, which strikes?

Python · tot_hedge.py · generator and evaluator, level 2
def generate_sizings(portfolio: str, scenario: str, hedge: dict, n: int) -> list[dict]:
    """Thought generator, level 2: n ways to size ONE parent hedge."""
    prompt = (
        f"Portfolio: {portfolio}\nScenario: {scenario}\n"
        f"Parent hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Propose {n} distinct sizings or structures for this hedge "
        f"(e.g. strike, notional, expiry, spread width), each with a short rationale."
    )
    return ask_json(prompt, HEDGES_SCHEMA)["candidates"]


def score_sizing(portfolio: str, scenario: str, hedge: dict, sizing: dict) -> dict:
    """State evaluator, level 2: judged together with its parent."""
    prompt = (
        f"Portfolio: {portfolio}\nScenario: {scenario}\n"
        f"Parent hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Candidate sizing: {sizing['name']} ({sizing['rationale']})\n"
        f"Score this sizing from 1 to 10 on residual exposure to the catalyst, "
        f"premium cost, and how cleanly it complements the parent hedge."
    )
    return ask_json(prompt, SCORE_SCHEMA)

Same pattern, one level deeper. The key words are "Parent hedge": every sizing is generated and scored in the context of its parent, so a sizing for "weekly puts" is judged as a put sizing, not in a vacuum.

The search — beam width 2

Python · tot_hedge.py · best_hedges
def best_hedges(portfolio: str, scenario: str, beam_width: int = 2) -> list[dict]:
    # Level 1: pick the best hedge instruments
    candidates = generate_hedges(portfolio, scenario, n=4)                   # ① 4 ideas
    scored = [{**c, **score_hedge(portfolio, scenario, c)} for c in candidates]  # ② + score
    scored.sort(key=lambda x: x["score"], reverse=True)                      # ③ best first
    retained = scored[:beam_width]                                           # ④ prune

    # Level 2: for each retained hedge, pick its best sizing
    for hedge in retained:                                                   # ⑤ per branch
        sizings = generate_sizings(portfolio, scenario, hedge, n=3)
        scored_sizings = [
            {**s, **score_sizing(portfolio, scenario, hedge, s)} for s in sizings
        ]
        scored_sizings.sort(key=lambda x: x["score"], reverse=True)
        hedge["best_sizing"] = scored_sizings[0]                             # ⑥ keep 1
    return retained
  1. 4 ideas from one generator call.
  2. {**c, **score_hedge(...)} — the ** "spreads" a dictionary's keys into a new one. Two small dictionaries become one: {"name", "rationale"} + {"score", "reasoning"} → {"name", "rationale", "score", "reasoning"}.
  3. sort(key=lambda x: x["score"], reverse=True) — lambda x: x["score"] is a tiny unnamed function: "sort by each item's score", highest first.
  4. scored[:beam_width] keeps the first two — this one slice is the pruning.
  5. For each survivor, generate 3 sizings and score them with the parent in view.
  6. hedge["best_sizing"] = scored_sizings[0] attaches the winning sizing to its parent dictionary.

Before: two dictionaries

c = {"name": "Weekly puts", "rationale": "direct protection…"} score = {"score": 8, "reasoning": "Protection 8/10…"}

After: {**c, **score}

{"name": "Weekly puts", "rationale": "direct protection…", "score": 8, "reasoning": "Protection 8/10…"}

Count the calls: 1 (ideas) + 4 (scores) + 2 survivors × (1 sizing call + 3 scores) = 13 LLM calls. Widen the beam and the bill grows — try it below.

Python · tot_hedge.py · run it
if __name__ == "__main__":
    portfolio = "5,000 shares of NVDA held outright (~$5M concentrated single-name position)"
    scenario = ("NVDA reports earnings tonight after the close; "
                "weekly implied volatility is elevated")
    for h in best_hedges(portfolio, scenario):
        print(f"{h['score']:>2}  {h['name']}: {h['reasoning']}")
        s = h["best_sizing"]
        print(f"    └─ best sizing ({s['score']}): {s['name']}: {s['reasoning']}")
🧪 Simulation · grow and prune the tree

Change the beam width — see what survives and what it costs

2
8 Buy NVDA Weekly Put Options (ATM or slightly OTM): Protection (8/10): weekly puts hedge the single-name earnings event with high precision … Cost (6/10): weekly implied volatility is very elevated into earnings … Basis risk (9/10) … └─ best sizing (8): Put Spread (5%-to-15% OTM, 50 contracts): the corridor is well calibrated to a typical adverse earnings move … 7 Buy NVDA Put Spread (buy 95% strike, sell 80% strike, weekly): … └─ best sizing (8): Full notional 95/80 put spread, 50 contracts: covers exactly 5,000 shares (50 × 100) …

A sample run, shortened. Covered calls scored only 4 — "Protection (2/10): extremely limited downside protection" — and were pruned before any sizing work was spent on them.

⚠️ Lessons and limits
  • Generate → evaluate → select, level by level. Only promising branches get more thinking.
  • Structured outputs make it orchestratable. Scores must be numbers code can sort, not prose.
  • Small branching keeps it inspectable — an analyst can read why every option was kept or dropped.
  • But: the scores are the model's own opinion (no market data), and nothing is learned between runs. For a sequence of real actions with feedback, we need the last pattern.

6.8LATS — plan the trim as a searchAdvanced

📅 Friday, 4 pm. Technology is 40% of the portfolio; the target is 30%. Getting there means real trades with real costs: sell too much of one name at once and you push its price against yourself (slippage). Which names, how much each, in what order? The agent will try trade plans, score them, back up from weak ones and write down lessons — Language Agent Tree Search.
🧠 Analogy — exploring a new city without a map

You try the streets that look most promising. Some turn into dead ends; you note that ("streets past the river don't lead downtown") and walk back to the best junction so far. You also try a street you haven't explored yet, just in case. Bit by bit your effort concentrates on the routes that keep leading somewhere good.

From ReActActions change an environment and return observations ("trimmed NVDA and MSFT by 8% — slippage 21 bps, exposure now 33.6%").
From tree of thoughtsSeveral candidate actions per step, each scored by the model.
From reflexionFailed plans produce one-line lessons that go into the next prompts.
New: Monte Carlo tree searchA simple formula (UCT) decides which branch deserves the next look, and scores flow back up the tree.

The six steps, in plain words

  1. Select — walk down from the top, at each fork picking the child with the best UCT score, until you reach a node that hasn't been fully explored.
  2. Expand — ask the model for K different trades from there; apply each one to a copy of the portfolio.
  3. Evaluate — the model scores each new position (1–10, turned into 0.1–1.0).
  4. Simulate — did any new position hit the target? Then stop and return it. (The research version plays one branch all the way to the end; our lab looks one step ahead and goes back to the top each round — cheaper, and the tree can change its mind sooner.)
  5. Backpropagate — send each new score up to every ancestor, updating their averages.
  6. Reflect — the best failed plan gets a one-line lesson, stored for future proposals.

The two formulas, without fear

UCT(s) = V(s) + w · √( ln N(parent) ÷ N(s) )

Left part — exploitation: how good this branch has looked so far (its average score, 0–1). Right part — exploration: a bonus that is big when this branch has been visited rarely compared with its parent. w (we use 1.41 ≈ √2) sets how much you value curiosity. A branch never visited gets UCT = ∞, so every child is tried at least once.

Vnew(s) = ( Vold(s) × (N(s) − 1) + r ) ÷ N(s)

That's just a running average: "my average so far, weighted by how many scores I had, plus the new score, divided by the new count". If c2 had one score of 0.5 and receives 0.4 and then 0.2, its average becomes (0.5 + 0.4 + 0.2) ÷ 3 = 0.367.

🧪 Simulation · the UCT playground

Two branches under one parent. When does curiosity beat a good track record?

0.80
10
0.50
1
1.41
💰 Finance corner: trims, exposure and slippage optional · glance over
  • Sector exposure — the share of the portfolio's value in one sector. 40% tech means 40 of every 100 rupees sit in technology stocks.
  • Trim — sell part of a position (not all of it).
  • Slippage — the gap between the price you expected and the price you got. Big orders push the price against you.
  • bps (basis points) — hundredths of a percent. 15 bps = 0.15%. On ₹100 crore that's ₹15 lakh.
  • Child order — one slice of a big order. Traders split large trades so each slice moves the market less.

The code, piece by piece

The environment. A mock world with deliberately simple formulas so you can check every number by hand. In real life this would be your portfolio and execution systems.

Python · lats_trim.py · the environment (mock)
# ---------- Pure environment (mock) ----------
# In practice you would read real exposures and constraints from your own systems.
INITIAL_MARKET = {
    "tech_exposure_pct": 40.0,
    "target_pct": 30.0,
    "slippage_bps": [],
}


def apply_trim(state, positions, pct):
    """Apply a trim and return (new_state, observation_text). Never mutates `state`."""
    new = copy.deepcopy(state)                               # a private copy per branch
    impact = 5 + len(positions) * 2 + pct * 1.5              # toy slippage model, in bps
    new["slippage_bps"].append(impact)
    new["tech_exposure_pct"] -= pct * len(positions) * 0.4   # toy exposure model
    obs = (
        f"Trimmed {positions} by {pct}% each. Slippage {impact:.1f} bps. "
        f"New tech exposure: {new['tech_exposure_pct']:.1f}%."
    )
    return new, obs


def reached_target(state):
    return state["tech_exposure_pct"] <= state["target_pct"]
🧠 Why copy.deepcopy?

Every branch of the tree is a "what if". If branch A changed the real portfolio dictionary, branch B would start from A's result. deepcopy gives each branch its own photocopy of the portfolio — including the list inside it — to scribble on. Check one by hand: trimming NVDA and MSFT by 8% each cuts exposure by 8 × 2 × 0.4 = 6.4 points → 33.6%, with slippage 5 + 2×2 + 8×1.5 = 21 bps.

The tree. Each Node remembers the portfolio after its trade, its parent and children, and the two numbers MCTS needs: visits N and value V.

Python · lats_trim.py · Node and uct
# ---------- LATS tree ----------
class Node:
    """One node = the portfolio AFTER this node's trade (the root = before any trade)."""

    def __init__(self, action_hint, state, parent=None):
        self.action_hint = action_hint
        self.state = state
        self.parent = parent
        self.children = []
        self.depth = 0 if parent is None else parent.depth + 1
        self.visits = 0          # N(s): how many scores have flowed through here
        self.value = 0.0         # V(s): running average of those scores, 0..1
        self.is_terminal = False
        self.proposal = None     # the trade that created this node (not for root)
        self.observation = None  # what the environment said about that trade

    def update(self, score):
        # V_new(s) = (V_old(s) * (N(s) - 1) + r) / N(s)   — a running average
        self.visits += 1
        self.value = ((self.value * (self.visits - 1)) + score) / self.visits


def uct(child, parent_visits, w=1.41):
    """UCT = how good it has looked so far + a bonus for being rarely tried."""
    if child.visits == 0:
        return float("inf")                    # never tried → try it first
    n_p = max(parent_visits, 1)
    return child.value + w * math.sqrt(math.log(n_p) / child.visits)

update is the running-average formula in two lines: count one more visit, then blend the new score in. uct is the first formula; max(parent_visits, 1) avoids log(0).

Step 1 · Selection.

Python · lats_trim.py · select
# ---------- 1. Selection ----------
def select(root, k_expand, max_depth):
    """Walk root → leaf via max-UCT until a node is not fully expanded or terminal."""
    node = root
    while (
        not node.is_terminal
        and node.depth < max_depth
        and len(node.children) >= k_expand
    ):
        node = max(node.children, key=lambda c: uct(c, node.visits))
    return node

Start at the root. While the current node is not finished, not too deep and already has its K children, step into the child with the highest UCT. Stop at the first node with room to grow. max(..., key=lambda c: uct(c, node.visits)) means "the child whose UCT is largest".

Talking to Claude. One helper sends a prompt through the Agent SDK and collects the text. The skills option loads a named skill from .claude/skills/ for that one call; [] means "no skills".

Python · lats_trim.py · _run_query and the three parsers
# ---------- Talking to Claude through the Agent SDK ----------
async def _run_query(prompt, system_prompt, max_turns, skill=None):
    """Send one prompt; return all the text Claude wrote. `skill` loads one skill."""
    options = ClaudeAgentOptions(
        model=MODEL,
        system_prompt=system_prompt,
        max_turns=max_turns,
        cwd=str(PROJECT_DIR),                    # so .claude/skills/ is found
        skills=[skill] if skill else [],         # [] = no skills for this call
    )
    parts = []
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if isinstance(block, TextBlock):
                    parts.append(block.text)
    return "\n".join(parts)


def parse_proposals(text):
    """Pull the JSON array out of the ```json block (or the first [...] found)."""
    m = (re.search(r"```(?:json)?\s*(\[.*?\])\s*```", text, re.S)
         or re.search(r"(\[.*\])", text, re.S))
    if not m:
        return []
    try:
        items = json.loads(m.group(1))
    except json.JSONDecodeError:
        return []
    return [p for p in items
            if p.get("positions") and isinstance(p.get("percent_each"), (int, float))]


def parse_score(text):
    """'... SCORE: 7' → 7 (clamped to 1..10; 1 if missing)."""
    found = re.findall(r"SCORE:\s*(\d+)", text)
    return max(1, min(10, int(found[-1]))) if found else 1


def parse_lesson(text):
    """'LESSON: When X, do Y.' → 'When X, do Y.'"""
    found = re.findall(r"LESSON:\s*(When .+)", text)
    return found[-1].strip() if found else None

The parsers are deliberately defensive: the proposal parser looks for the fenced JSON block first, then any […]; the score parser takes the last SCORE: line and clamps it to 1–10; anything unreadable becomes "no proposals" or the lowest score — never a crash.

Step 2 · Expansion — K different trims in one call.

Python · lats_trim.py · propose_k_trims
# ---------- 2. Expansion: K distinct trims in ONE call ----------
PROPOSE_SYSTEM_PROMPT = """You are a trade-construction agent reducing tech exposure.
You will be asked to propose K distinct candidate trims from a given market state.
The K candidates MUST differ materially from one another -- different ticker
selection, different slice size, or different concentration profile. Mode
collapse to identical or near-identical trims is a failure.
Output exactly one fenced JSON code block and no other text. The block must
contain a JSON array of K objects, each with these fields:
- positions: list of ticker symbols (strings, non-empty)
- percent_each: number, the % to trim from each named position
- rationale: short string explaining the candidate's distinct angle
Example:
```json
[
  {"positions": ["NVDA", "AMD"], "percent_each": 5.0,
   "rationale": "concentrated semis trim"},
  {"positions": ["AAPL", "MSFT", "GOOGL", "META"], "percent_each": 2.5,
   "rationale": "diversified mega-cap shave"}
]
```
"""


async def propose_k_trims(state, k_expand, lessons):
    lessons_block = ""
    if lessons:                                              # reflexion-style memory
        lessons_block = "\n\nLessons from prior attempts:\n- " + "\n- ".join(lessons)
    prompt = (
        f"Current tech exposure: {state['tech_exposure_pct']:.1f}%. "
        f"Target: {state['target_pct']}%. "
        f"K = {k_expand}. Propose {k_expand} materially distinct trim candidates."
        f"{lessons_block}"
    )
    text = await _run_query(prompt, system_prompt=PROPOSE_SYSTEM_PROMPT, max_turns=2)
    return parse_proposals(text)

Two ideas from earlier in this section meet here: one call, K distinct proposals (from tree of thoughts — later proposals can differ from earlier ones because they're written in the same reply) and "Lessons from prior attempts" (from reflexion — past failures steer new proposals).

Step 3 · Evaluation — a skill does the scoring. A skill is a folder with a SKILL.md file: a reusable recipe the agent loads when needed. The trading desk can edit the scoring rubric without touching Python.

.claude/skills/trade-evaluator/SKILL.md
---
name: trade-evaluator
description: Score a partial tech-sector trim trajectory. Use when asked to evaluate how close a trajectory is to the target reduction at acceptable cost.
---

Score the trajectory from 1 to 10 using these criteria:
- 6-10: progress on target exposure exceeds elapsed time fraction, slippage
  below 8 bps per child order, residual risk broadly diversified.
- 3-5: on-pace but slippage between 8 and 15 bps, or concentrated residual.
- 1-2: behind schedule, or slippage above 15 bps on any child order.

Return a single integer score and a one-sentence justification.
Python · lats_trim.py · evaluate_proposal
# ---------- 3. Evaluation: a skill scores each new child ----------
def _trajectory_block(parent_state, proposal, child_state, observation):
    return (
        f"Trajectory:\n"
        f"- Starting tech exposure: {parent_state['tech_exposure_pct']:.1f}%\n"
        f"- Action: trim {proposal['positions']} by {proposal['percent_each']}% each\n"
        f"- Rationale: {proposal.get('rationale', '')}\n"
        f"- Observation: {observation}\n"
        f"- Resulting tech exposure: {child_state['tech_exposure_pct']:.1f}%\n"
        f"- Target: {child_state['target_pct']}%"
    )


EVAL_SYSTEM_PROMPT = """You are evaluating a single tech-trim trajectory.
Use the Skill tool to invoke `trade-evaluator` on the trajectory described.
End your response with a line of the exact form: SCORE: <integer 1-10>
"""


async def evaluate_proposal(parent_state, proposal, child_state, observation):
    prompt = _trajectory_block(parent_state, proposal, child_state, observation)
    return await _run_query(prompt + "\n\nEvaluate this trajectory.",
                            system_prompt=EVAL_SYSTEM_PROMPT, max_turns=4,
                            skill="trade-evaluator")
Python · lats_trim.py · expand
async def expand(node, k_expand, lessons):
    """Grow `node` by up to k children; return [(child, score 0..1), ...]."""
    new = []
    for p in (await propose_k_trims(node.state, k_expand, lessons))[:k_expand]:
        child_state, obs = apply_trim(node.state, p["positions"], p["percent_each"])
        child = Node(action_hint=p.get("rationale"), state=child_state, parent=node)
        child.proposal, child.observation = p, obs
        child.is_terminal = reached_target(child_state)
        verdict = await evaluate_proposal(node.state, p, child_state, obs)
        node.children.append(child)
        new.append((child, parse_score(verdict) / 10))     # 1..10 → 0.1..1.0
    return new

expand glues steps 2 and 3: for each proposal, apply it to a copy of the parent's portfolio, create the child node, mark it terminal if it hit the target, and ask the evaluator for a score. It returns pairs (child, score) with the score scaled to 0–1.

Steps 5 and 6 · Backpropagation and reflection.

Python · lats_trim.py · backprop
# ---------- 5. Backpropagation ----------
def backprop(leaf, score):
    """Walk leaf → root, updating value/visits at every ancestor (incl. root)."""
    node = leaf
    while node is not None:
        node.update(score)
        node = node.parent
.claude/skills/trade-reflector/SKILL.md
---
name: trade-reflector
description: Write a one-sentence reflection on a failed tech-sector trim. Use when a trajectory ended short of its target exposure reduction.
---

Identify the single most important decision that caused the shortfall (venue
choice, slice size, timing, or name selection) and phrase the lesson as a
conditional rule the agent can apply next time.

Output exactly one line, with no other text, in this exact form:
LESSON: When <situation>, do <action>.
Python · lats_trim.py · reflect_on_failure
# ---------- 6. Reflection ----------
REFLECT_SYSTEM_PROMPT = """You are reflecting on a failed tech-trim trajectory.
Use the Skill tool to invoke `trade-reflector` on the trajectory described, then
end your response with a line of the exact form:
LESSON: When <situation>, do <action>.
"""


async def reflect_on_failure(parent_state, proposal, child_state, observation):
    prompt = _trajectory_block(parent_state, proposal, child_state, observation)
    return await _run_query(
        prompt + "\n\nThe target was not reached. Reflect on this trajectory.",
        system_prompt=REFLECT_SYSTEM_PROMPT, max_turns=4, skill="trade-reflector")

The driver — all six steps in one loop.

Python · lats_trim.py · printing helpers and lats_search
# ---------- Printing helpers ----------
def name_of(node):
    if node.parent is None:
        return "root"
    return f"{name_of(node.parent)}/c{node.parent.children.index(node) + 1}"


def all_nodes(node):
    yield node
    for c in node.children:
        yield from all_nodes(c)


def print_tree(root):
    print("\n=== Final tree ===")
    for n in all_nodes(root):
        print(f"{'  ' * n.depth}{name_of(n)}: N={n.visits} V={n.value:.2f} "
              f"exposure={n.state['tech_exposure_pct']:.1f}%")


# ---------- The LATS loop ----------
async def lats_search(n_iterations=3, k_expand=2, max_depth=3):
    root = Node(action_hint=None, state=copy.deepcopy(INITIAL_MARKET))
    lessons = []                                             # long-term memory

    for it in range(1, n_iterations + 1):
        print(f"\n=== Iteration {it} ===")
        node = select(root, k_expand, max_depth)                          # 1 SELECT
        print(f"Selected: {name_of(node)} (depth={node.depth}, "
              f"N={node.visits}, V={node.value:.2f})")
        if node.depth >= max_depth:
            print("Reached max depth on this branch; skipping.")
            node.is_terminal = True
            continue

        new = await expand(node, k_expand, lessons)                       # 2 EXPAND + 3 EVALUATE
        for child, score in new:
            p = child.proposal
            print(f"[add ] {name_of(child)}: positions={p['positions']} "
                  f"pct={p['percent_each']}  score={score * 10:.1f}/10  "
                  f"exposure={child.state['tech_exposure_pct']:.1f}%")
        if not new:
            print("No valid proposals this round.")
            continue

        winners = [c for c, _ in new if c.is_terminal]                    # 4 SIMULATE (1 step)
        if winners:
            print(f"Target reached by {name_of(winners[0])}!")
            return winners[0]

        for child, score in new:                                          # 5 BACKPROPAGATE
            backprop(child, score)

        best_child, _ = max(new, key=lambda cs: cs[1])                    # 6 REFLECT
        verdict = await reflect_on_failure(node.state, best_child.proposal,
                                           best_child.state, best_child.observation)
        lesson = parse_lesson(verdict)
        if lesson and lesson not in lessons:                              # dedupe
            lessons.append(lesson)
            lessons = lessons[-MAX_LESSONS:]                              # cap at 5
            print(f"[lesson] {lesson}")

    print_tree(root)
    leaves = [n for n in all_nodes(root) if n.parent and not n.children]
    best = max(leaves, key=lambda n: (n.value, -n.state["tech_exposure_pct"]))
    print(f"Best leaf: {name_of(best)}  V={best.value:.2f}  "
          f"exposure={best.state['tech_exposure_pct']:.1f}%")
    return best


if __name__ == "__main__":
    anyio.run(lats_search, 3, 2, 3)          # n_iterations, k_expand, max_depth
  1. root holds a deep copy of the starting portfolio; lessons is the long-term memory.
  2. Select the frontier node; skip it if it's already at the depth limit.
  3. Expand + evaluate → a list of (child, score) pairs.
  4. Early exit if any child reached the target — no backprop or reflection needed.
  5. Backpropagate every new score up to the root.
  6. Reflect on the best failed child; keep at most 5 unique lessons (lessons[-MAX_LESSONS:] keeps the last five).
  7. After the budget, print the tree and return the best leaf (highest V; ties go to the lower exposure).
🧪 Simulation · replay a real LATS run

Three iterations, every number computed live with the two formulas

The proposals and scores are from a real run; the tree values, UCT scores and selections are recalculated here exactly as the Python code does it. Watch c2's early lead disappear.

=== Final tree === root: N=6 V=0.40 exposure=40.0% root/c1: N=3 V=0.43 exposure=33.6% root/c1/c1: N=1 V=0.50 exposure=32.2% root/c1/c2: N=1 V=0.40 exposure=32.2% root/c2: N=3 V=0.37 exposure=36.0% root/c2/c1: N=1 V=0.40 exposure=33.6% root/c2/c2: N=1 V=0.20 exposure=33.6% Best leaf: root/c1/c1 V=0.50 exposure=32.2% [lesson] When a two-name trim falls short of the target exposure reduction, do increase the per-name trim percentage or add a third name …

We replayed exactly these proposals and scores through the Python code above (with the Claude calls swapped for recorded replies) and it printed this tree — every N and V matches.

💡 The one moment to remember

After round 1, c2 looked best (0.50 vs 0.40). LATS treated that as a hypothesis, explored c2 — and its children scored 0.4 and 0.2, pulling its average down to 0.367. In round 3 the formula moved the effort to c1, which was now both better and less explored. A static tree would have stayed stuck on its first impression.

⚠️ When is LATS worth it?
  • It combines tools, branching, memory and search — so it has the most moving parts, the most LLM calls and the most state to manage of all seven.
  • In this run it improved the allocation (40% → 32.2%) but didn't reach 30% within 3 iterations. More iterations, or the lessons it wrote ("add a slippage buffer"), would help — at a cost.
  • Use it when a wrong answer costs more than the extra search: multi-step execution, high-stakes plans. Not for a quick question.

6.9Cheat-sheet: the seven on one page

ParadigmHow it worksWatch out forDesk use this week
Self-refineOne LLM: draft → critique → fix, in a loopBlind spots survive; the prompt grows with historyPolish the investment thesis
Self-consistencyAsk N times with sampling, take the majority voteN× the cost; closed answers only; shared bias → confidently wrongBUY / HOLD / SELL, with a confidence signal
ReActThink → call a tool → read the result → think againOnly as good as its tools; each step adds latencyLive valuation vs peers
CRITICDraft, then verify every fact with tools, critique, correctNo memory: the same mistake gets caught every dayFact-check the morning briefing
ReflexionAfter a failure, write a one-line lesson; read lessons next timeBad lessons do harm; pays off only on repeated tasksStop mis-flagging retailers
Tree of thoughts 🔶Generate options, score them, prune, go deeperModel's own opinion only; nothing learned between runs; more callsChoose and size the hedge
LATS 🔶Tree search over real actions + scores flowing up + lessonsMost calls, state and complexityPlan the tech trim
💡 Mix and match, one agent at a time

You don't pick one paradigm for a whole system. In a multi-agent setup each agent can think differently: a research agent might pair ReAct retrieval with reflexion memory, while the decision agent reading its findings adds a self-consistency vote on top. And however clever the reasoning, a human checkpoint still signs off before money moves. A newer idea even puts the human inside the loop: the agent is allowed to stop and ask a clarifying question when the task is ambiguous, instead of guessing.


Wrap-up

What to remember

  1. How the model thinks matters as much as which model it is. Same LLM, different recipe, different reliability.
  2. Self-refine = one model, three hats, a stop word and a round limit. Keep the three prompts aligned.
  3. Self-consistency needs three things: real diversity (sampling), a strict answer line code can parse, and reading the size of the majority, not just the winner.
  4. ReAct on the Claude Agent SDK: tools are Python functions in an in-process MCP server; the stream of messages maps onto Thought / Action / Observation — your audit trail.
  5. CRITIC checks facts against sources; reflexion writes lessons so mistakes aren't repeated. Code compares numbers; the LLM writes words.
  6. Tree of thoughts and LATS search before committing. Prune early, sort by numbers, and let scores flow back up the tree.
  7. Every extra bit of reasoning costs calls. Pick the lightest paradigm that's reliable enough for the stakes.

QuizCheck yourself


Appendix

Complete code for every lab

Everything you need is on this page — nothing to download. Make a folder, create each file below with exactly the name shown, and paste the code in. The walkthroughs above explain each part; these are the full files, including imports and the run block at the bottom.

your-folder/ ├── .env # ANTHROPIC_API_KEY=sk-ant-... ├── self_refine.py ├── self_consistency.py ├── react_agent.py ├── critic_sketch.py # offline ├── reflexion_shape.py # offline ├── tot_hedge.py └── lats/ ├── lats_trim.py └── .claude/skills/ ├── trade-evaluator/SKILL.md └── trade-reflector/SKILL.md
Terminal · set up once
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install anthropic claude-agent-sdk yfinance anyio python-dotenv
echo "ANTHROPIC_API_KEY=sk-ant-..." > .env
📄 Self-refine (6.2) self_refine.py

Monday's thesis: draft → critique → refine.

self_refine.py
"""
self_refine.py — Monday at Future with Shivank Bank: draft an investment
thesis, then let the SAME model critique it and polish it.

    generate  →  feedback  →  refine  →  feedback  →  refine …  (max 3 rounds)

Run it:
    pip install anthropic python-dotenv
    # put ANTHROPIC_API_KEY=sk-ant-... in a .env file next to this script
    python self_refine.py
"""
import os

import anthropic
from dotenv import load_dotenv

load_dotenv()                                   # copies .env into os.environ
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"                     # any current Claude model works
MAX_ITERATIONS = 3                              # at most 3 feedback → refine rounds


def call_llm(prompt: str, max_tokens: int = 1024) -> str:
    """One plain LLM call. All three roles below use THIS same function."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=max_tokens,
        messages=[{"role": "user", "content": prompt}],
    )
    return response.content[0].text             # the reply's text


def generate_initial_thesis(financials: str) -> str:
    """Role 1 — the analyst writes a first draft."""
    prompt = f"""You are a senior equity analyst at a long-only asset management firm.
Draft a concise investment thesis based on the following financial data:

{financials}

Your thesis should cover: key business drivers, valuation, and 2-3 key risks.
Cite only metrics present in the data above; flag any outside claim as [unverified].
Write 1-2 sentences for each section. Be concise."""
    return call_llm(prompt)


def get_feedback(thesis: str, financials: str, history_feedback: str) -> str:
    """Role 2 — the investment committee reviews the draft."""
    prompt = f"""You are a critical investment committee reviewer.
Review the following investment thesis and provide specific, actionable feedback.
Identify missing information, weak arguments, or factual gaps.
Ground your feedback only on the metrics present in the provided data
[Original query]; flag any outside claim as [unverified].
Your feedback should cover the thesis sections: key business drivers,
valuation, and 2-3 key risks.
If no issue would block investment-committee approval, respond with exactly:
NO_FURTHER_FEEDBACK
Be concise.

Original query:
{financials}

Previous theses and feedback:
{history_feedback}

Thesis to provide feedback on:
{thesis}

Feedback:"""
    return call_llm(prompt)


def refine_thesis(thesis: str, feedback: str, financials: str,
                  history_feedback: str) -> str:
    """Role 3 — the analyst rewrites the draft to answer every comment."""
    prompt = f"""You are a senior equity analyst.
Revise the following investment thesis based on the reviewer feedback below.
Produce an improved version that directly addresses each point in the feedback.
Cite only metrics present in the provided data [Original query]; flag any
outside claim as [unverified].
Keep the same sections as the original: key business drivers, valuation,
and 2-3 key risks. Write 1-2 sentences for each section. Be concise.

Original query:
{financials}

Previous theses and feedback:
{history_feedback}

Original thesis to revise:
{thesis}

Reviewer feedback:
{feedback}

Revised thesis:"""
    return call_llm(prompt, max_tokens=2048)


def self_refine_thesis(financials: str) -> tuple[str, str]:
    print("[STEP 1] Generating initial thesis ...")
    thesis = generate_initial_thesis(financials)              # ① draft v0
    history_feedback = ""                                     # ② empty audit log
    print(f"Initial thesis:\n{thesis}\n")

    for iteration in range(1, MAX_ITERATIONS + 1):            # ③ 1, 2, 3
        print(f"[STEP 2] Iteration {iteration} -- getting feedback ...")
        feedback = get_feedback(thesis, financials, history_feedback)
        print(f"Feedback:\n{feedback}\n")
        if feedback.strip().startswith("NO_FURTHER_FEEDBACK"):  # ④ early stop
            print("Stopping: the reviewer has no blocking issues left.")
            break
        history_feedback += (                                  # ⑤ remember this round
            f"Iteration: {iteration}\nThesis: {thesis}\nFeedback: {feedback}\n\n"
        )
        print(f"[STEP 3] Iteration {iteration} -- refining thesis ...")
        thesis = refine_thesis(thesis, feedback, financials,   # ⑥ overwrite with v+1
                               history_feedback)
        print(f"Refined thesis:\n{thesis}\n")

    return thesis, history_feedback                           # ⑦ best draft + audit log


FINANCIALS = """
----- AAPL -----
Revenue FY2023: $383B (+2% YoY)
Services Revenue: $78B (+16% YoY), Gross Margin ~70%
Net Income: $97B
P/E (forward): 28x | EV/EBITDA: 22x
Cash & Equivalents: $62B | Net Debt: -$52B (net cash)
"""

if __name__ == "__main__":
    # Note: the prompt grows a little every round, because history_feedback grows.
    final_thesis, audit_log = self_refine_thesis(FINANCIALS)
    print("FINAL THESIS:\n", final_thesis)
📄 Self-consistency (6.3) self_consistency.py

Tuesday's five-path vote.

self_consistency.py
"""
self_consistency.py — Tuesday: five independent "junior analysts" reason
about the same stock; the majority vote becomes the recommendation.

Run it:
    pip install anthropic python-dotenv
    python self_consistency.py
"""
import os
from collections import Counter

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"
N_PATHS = 5                 # how many independent analysts vote
TEMPERATURE = 0.8           # enough randomness for different reasoning paths

SYSTEM_PROMPT = """You are a financial analyst.
Analyze the stock summary of a company and provide a final recommendation:
BUY, HOLD, or SELL.
Reason step by step through the investment case. Cover:
1. Earnings quality and trajectory
2. Valuation vs. peers and history
3. Key risks and near-term catalysts
4. Overall risk/reward balance
Be concise: 1-2 sentences per point.
End your response with exactly one line in this plain format (no markdown,
no bold, no asterisks):
RECOMMENDATION: <BUY|HOLD|SELL>"""


def sample_reasoning_path(stock_summary: str) -> str:
    """One analyst = one ordinary API call."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        system=SYSTEM_PROMPT,
        messages=[{"role": "user", "content": stock_summary}],
        # Anthropic SDK 1.0+ removed temperature from the method signature,
        # so we send it in extra_body. On SDK < 1.0 write temperature=TEMPERATURE.
        # If your model rejects temperature, delete this line: replies are
        # sampled (a bit random) anyway.
        extra_body={"temperature": TEMPERATURE},
    )
    return response.content[0].text


def extract_recommendation(path: str) -> str | None:
    """Find 'RECOMMENDATION: X' near the end, tolerating stray formatting."""
    for line in reversed(path.strip().split("\n")):           # ① last line first
        cleaned = line.strip().lstrip("*_`# ").upper()        # ② drop **, #, `, _
        if cleaned.startswith("RECOMMENDATION:"):             # ③ the contract line?
            label = cleaned.replace("RECOMMENDATION:", "").strip().strip("*_`. ")
            if label in ("BUY", "HOLD", "SELL"):              # ④ only legal labels
                return label
    return None                                               # ⑤ no valid line found


def self_consistency_recommend(stock_summary: str, n_paths: int = N_PATHS) -> dict:
    paths, recommendations = [], []
    print(f"[STEP 1] Sampling {n_paths} paths at temperature={TEMPERATURE}.\n")
    for i in range(1, n_paths + 1):
        print(f"[STEP 2] Sampling reasoning path {i}/{n_paths} ...")
        path = sample_reasoning_path(stock_summary)           # one analyst's notes
        recommendation = extract_recommendation(path)         # BUY / HOLD / SELL / None
        paths.append(path)
        recommendations.append(recommendation)
        print(f"--- Path {i} reasoning ---\n{path}\n")
        print(f"[Path {i}] Parsed recommendation: {recommendation}\n")

    print("[STEP 3] Aggregating answers via majority vote ...")
    valid = [r for r in recommendations if r is not None]     # drop unreadable paths
    if not valid:
        raise ValueError("No path ended with a valid RECOMMENDATION line.")
    vote_counts = Counter(valid)                              # {'HOLD': 3, 'SELL': 2}
    final_recommendation, top_votes = vote_counts.most_common(1)[0]
    agreement = top_votes / len(valid)                        # 3/5 = 0.6
    return {
        "final_recommendation": final_recommendation,
        "vote_counts": dict(vote_counts),
        "agreement": agreement,
        "needs_human_review": agreement < 0.8,                # a split vote = ambiguity
        "paths": paths,                                       # the audit trail
    }


STOCK_SUMMARY = """
Company: ACME Corp (ticker: ACME)
Latest Earnings:
- Revenue: $94.9B (+5% YoY), beat consensus by 1.2%
- EPS: $1.56, beat consensus by $0.04
- Net margin: 25.5% (down 80bps YoY)
- Free Cash Flow: $18.1B
Valuation:
- P/E: 28x (sector median: 22x)
- EV/EBITDA: 18x (sector median: 14x)
- PEG ratio: 1.9
Guidance:
- FY2025 revenue guidance raised to $97-99B
- Management flagged EU regulatory headwinds in H2
Market Context:
- Sector under pressure from rising rates
- Main competitor cut guidance last week
"""

if __name__ == "__main__":
    result = self_consistency_recommend(STOCK_SUMMARY)
    print(f"\n=== FINAL RECOMMENDATION: {result['final_recommendation']} ===")
    print(f"Vote breakdown: {result['vote_counts']}  "
          f"(agreement {result['agreement']:.0%})")
    if result["needs_human_review"]:
        print("Split vote -> send to a human analyst before acting.")
📄 ReAct on the Claude Agent SDK (6.4) react_agent.py

Wednesday's live-data valuation agent.

react_agent.py
"""
react_agent.py — Wednesday: is the stock expensive versus its peers?
A ReAct agent built with the Claude Agent SDK and three live-data tools.

Run it:
    pip install claude-agent-sdk yfinance python-dotenv
    python react_agent.py
"""
import asyncio
import json
import statistics

import yfinance as yf
from dotenv import load_dotenv
from claude_agent_sdk import (
    AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, TextBlock,
    ToolResultBlock, ToolUseBlock, UserMessage, create_sdk_mcp_server, tool,
)

load_dotenv()                      # the SDK reads ANTHROPIC_API_KEY from the env


@tool(
    "get_valuation_ratios",                                               # ① name
    "Retrieve valuation ratios (P/E, EV/EBITDA, P/B, PEG) for a given ticker.",  # ② when to use
    {"ticker": str},                                                      # ③ inputs
)
async def get_valuation_ratios(args):
    info = yf.Ticker(args["ticker"]).info              # a big dict of Yahoo fields
    data = {
        "PE": info.get("trailingPE"),
        "EV_EBITDA": info.get("enterpriseToEbitda"),
        "PB": info.get("priceToBook"),
        "PEG": info.get("pegRatio") or info.get("trailingPegRatio"),
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}  # ④ MCP format


# A handful of large-cap tickers per sector, used to compute live sector medians.
SECTOR_TICKERS = {
    "Technology": ["MSFT", "NVDA", "GOOGL", "META", "ORCL",
                   "CRM", "ADBE", "AMD", "INTC", "CSCO"],
    "Healthcare": ["JNJ", "UNH", "PFE", "MRK", "ABBV",
                   "TMO", "ABT", "LLY", "BMY", "AMGN"],
    "Financials": ["JPM", "BAC", "WFC", "GS", "MS",
                   "C", "BLK", "AXP", "USB", "PNC"],
}


@tool(
    "get_sector_median_pe",
    "Retrieve the median P/E and EV/EBITDA for a given GICS sector.",
    {"sector": str},
)
async def get_sector_median_pe(args):
    pes, evs = [], []
    for tk in SECTOR_TICKERS.get(args["sector"], []):    # unknown sector → []
        info = yf.Ticker(tk).info
        if info.get("trailingPE"):                        # skip missing values
            pes.append(info["trailingPE"])
        if info.get("enterpriseToEbitda"):
            evs.append(info["enterpriseToEbitda"])
    data = {
        "median_pe": round(statistics.median(pes), 2) if pes else None,
        "median_ev_ebitda": round(statistics.median(evs), 2) if evs else None,
        "sample_size": len(pes),                          # how many names counted
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}


@tool(
    "get_balance_sheet",
    "Retrieve balance sheet summary (net cash in $bn, debt-to-equity) for a ticker.",
    {"ticker": str},
)
async def get_balance_sheet(args):
    info = yf.Ticker(args["ticker"]).info
    cash = info.get("totalCash") or 0
    debt = info.get("totalDebt") or 0
    de = info.get("debtToEquity")                         # Yahoo gives 80.0 for 0.8x
    data = {
        "net_cash_bn": round((cash - debt) / 1e9, 1),     # negative = net debt
        "debt_to_equity": round(de / 100, 2) if de else None,
    }
    return {"content": [{"type": "text", "text": json.dumps(data)}]}


SYSTEM_PROMPT = """You are a financial research analyst following the ReAct pattern.
For every step, first emit a 'Thought:' line explaining your plan or
interpretation, then call the appropriate tool. After each observation, briefly
reason about what it means before the next step. Conclude with a clear,
well-grounded recommendation."""


async def run_react_agent(question: str) -> str:
    server = create_sdk_mcp_server(                            # ① a tool "shop"
        name="finance",
        version="1.0.0",
        tools=[get_valuation_ratios, get_sector_median_pe, get_balance_sheet],
    )
    options = ClaudeAgentOptions(                              # ② the agent's rules
        model="claude-sonnet-4-6",
        system_prompt=SYSTEM_PROMPT,
        mcp_servers={"finance": server},
        allowed_tools=[                                        # mcp__<server>__<tool>
            "mcp__finance__get_valuation_ratios",
            "mcp__finance__get_sector_median_pe",
            "mcp__finance__get_balance_sheet",
        ],
    )
    final = ""
    async with ClaudeSDKClient(options=options) as client:    # ③ open the session
        await client.query(question)                           # ④ ask
        async for msg in client.receive_response():            # ⑤ stream every message
            if isinstance(msg, AssistantMessage):              # Claude speaking
                for block in msg.content:
                    if isinstance(block, TextBlock):           # → THOUGHT (or answer)
                        print(f"\n[THOUGHT] {block.text.strip()}")
                        final = block.text
                    elif isinstance(block, ToolUseBlock):      # → ACTION
                        print(f"\n[ACTION] {block.name}({block.input})")
            elif isinstance(msg, UserMessage):                 # tool results come back
                content = msg.content if isinstance(msg.content, list) else []
                for block in content:
                    if isinstance(block, ToolResultBlock):     # → OBSERVATION
                        print(f"[OBSERVATION] {block.content}")
    return final                                               # ⑥ the last text = answer


if __name__ == "__main__":
    question = (
        "Is Apple (AAPL) overvalued relative to the Technology sector? "
        "What does this imply for a long-only portfolio?"
    )
    answer = asyncio.run(run_react_agent(question))
    print("\n" + "=" * 60)
    print("FINAL ANSWER")
    print("=" * 60)
    print(answer)
📄 CRITIC sketch (6.5) critic_sketch.py

Runs offline with stand-in tools.

critic_sketch.py
"""
critic_sketch.py — Thursday morning: fact-check the morning briefing.
A SIMPLIFIED SKETCH of the CRITIC loop (verify → critique → correct).
The "tools" and the "corrector" are stand-ins so you can run it offline:
    python critic_sketch.py
"""
def verify(claims: dict, sources: dict, tolerance: float = 0.0005) -> list[str]:
    """Compare every number in the draft with the source (0.0005 = 0.05% slack)."""
    issues = []
    for field, source_value in sources.items():
        claimed = claims.get(field)
        if claimed is None:
            issues.append(f"{field}: missing from the draft (source says {source_value})")
        elif abs(claimed - source_value) > tolerance * abs(source_value):
            issues.append(f"{field}: draft says {claimed}, source says {source_value}")
    return issues                       # [] means "nothing wrong" → stop


def critic_loop(claims: dict, fetch_sources, correct, max_iters: int = 3):
    audit_trail = []
    for i in range(1, max_iters + 1):
        sources = fetch_sources()                     # VERIFY: ask the tools
        issues = verify(claims, sources)              # CRITIQUE: what's wrong?
        audit_trail.append({"round": i, "issues": issues})
        if not issues:                                # clean → done
            break
        claims = correct(claims, issues, sources)     # CORRECT: an LLM in real life
    return claims, audit_trail


if __name__ == "__main__":
    draft = {"open_price": 78.29, "ttm_revenue_bn": 45.0, "dividend_ps": 1.80}   # Coca-Cola

    def fetch_sources():          # stand-in for market-data / fundamentals / events APIs
        return {"open_price": 78.37, "ttm_revenue_bn": 46.0, "dividend_ps": 1.84}

    def correct(claims, issues, sources):   # stand-in for "LLM, fix these issues"
        return {**claims, **sources}

    final, trail = critic_loop(draft, fetch_sources, correct)
    for step in trail:
        print(step)
    print("Verified briefing numbers:", final)
📄 Reflexion shape (6.6) reflexion_shape.py

Runs offline with stand-in functions.

reflexion_shape.py
"""
reflexion_shape.py — Thursday afternoon: the SHAPE of a reflexion loop.
Stand-in functions so it runs offline:  python reflexion_shape.py
"""
MAX_TRIALS = 3
memory: list[str] = []                        # long-term memory: lessons, not logs


def actor(task: str, lessons: list[str]) -> dict:
    """Does the screening. Real life: a ReAct agent with the lessons in its prompt."""
    knows = any("negative working capital" in l for l in lessons)
    return {"task": task, "flagged_wc": not knows}


def evaluator(trajectory: dict) -> bool:
    """Reward: did we get it right? (rubric, labelled examples or another model)"""
    return not trajectory["flagged_wc"]


def reflector(trajectory: dict, memory: list[str]) -> str:
    """Writes a short, human-readable lesson about the failure."""
    return ("I treated negative working capital as a red flag. For retailers and "
            "platforms with strong supplier terms it is often a strength; "
            "check the industry first.")


for trial in range(1, MAX_TRIALS + 1):
    trajectory = actor("Screen ShopCo for the buy list", lessons=memory)   # act
    passed = evaluator(trajectory)                                         # score
    print(f"Trial {trial}: {'PASS' if passed else 'FAIL'}  (lessons in memory: {len(memory)})")
    if passed:
        break
    memory.append(reflector(trajectory, memory))                          # learn
📄 Tree of thoughts (6.7) tot_hedge.py

Friday morning's hedge search.

tot_hedge.py
"""
tot_hedge.py — Friday morning: pick a hedge for a big NVDA position before
earnings, using a two-level Tree of Thoughts (beam search).

    Level 1: which hedge?   4 ideas → score each → keep the best 2
    Level 2: how big?       for each kept idea: 3 sizings → score → keep the best 1

Run it:
    pip install anthropic python-dotenv
    python tot_hedge.py
"""
import json
import os

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"


HEDGES_SCHEMA = {                       # "give me a list of named ideas"
    "type": "object",
    "properties": {
        "candidates": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "rationale": {"type": "string"},
                },
                "required": ["name", "rationale"],
                "additionalProperties": False,
            },
        }
    },
    "required": ["candidates"],
    "additionalProperties": False,
}

SCORE_SCHEMA = {                        # "give me one number and why"
    "type": "object",
    "properties": {
        "score": {"type": "integer"},
        "reasoning": {"type": "string"},
    },
    "required": ["score", "reasoning"],
    "additionalProperties": False,
}


def ask_json(prompt: str, schema: dict) -> dict:
    """One LLM call whose reply MUST match `schema` (structured outputs)."""
    response = client.messages.create(
        model=MODEL,
        max_tokens=2048,
        output_config={"format": {"type": "json_schema", "schema": schema}},
        messages=[{"role": "user", "content": prompt}],
    )
    text = next(b.text for b in response.content if b.type == "text")  # first text block
    return json.loads(text)                                            # JSON text → dict


def generate_hedges(portfolio: str, scenario: str, n: int) -> list[dict]:
    """Thought generator, level 1: n hedge ideas in ONE call."""
    prompt = (
        f"Portfolio: {portfolio}\nStress scenario: {scenario}\n"
        f"Propose {n} distinct hedge candidates, each with a short rationale."
    )
    return ask_json(prompt, HEDGES_SCHEMA)["candidates"]


def score_hedge(portfolio: str, scenario: str, hedge: dict) -> dict:
    """State evaluator, level 1: score one idea from 1 to 10."""
    prompt = (
        f"Portfolio: {portfolio}\nStress scenario: {scenario}\n"
        f"Candidate hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Score this hedge from 1 to 10 on protection, cost, and basis risk."
    )
    return ask_json(prompt, SCORE_SCHEMA)


def generate_sizings(portfolio: str, scenario: str, hedge: dict, n: int) -> list[dict]:
    """Thought generator, level 2: n ways to size ONE parent hedge."""
    prompt = (
        f"Portfolio: {portfolio}\nScenario: {scenario}\n"
        f"Parent hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Propose {n} distinct sizings or structures for this hedge "
        f"(e.g. strike, notional, expiry, spread width), each with a short rationale."
    )
    return ask_json(prompt, HEDGES_SCHEMA)["candidates"]


def score_sizing(portfolio: str, scenario: str, hedge: dict, sizing: dict) -> dict:
    """State evaluator, level 2: judged together with its parent."""
    prompt = (
        f"Portfolio: {portfolio}\nScenario: {scenario}\n"
        f"Parent hedge: {hedge['name']} ({hedge['rationale']})\n"
        f"Candidate sizing: {sizing['name']} ({sizing['rationale']})\n"
        f"Score this sizing from 1 to 10 on residual exposure to the catalyst, "
        f"premium cost, and how cleanly it complements the parent hedge."
    )
    return ask_json(prompt, SCORE_SCHEMA)


def best_hedges(portfolio: str, scenario: str, beam_width: int = 2) -> list[dict]:
    # Level 1: pick the best hedge instruments
    candidates = generate_hedges(portfolio, scenario, n=4)                   # ① 4 ideas
    scored = [{**c, **score_hedge(portfolio, scenario, c)} for c in candidates]  # ② + score
    scored.sort(key=lambda x: x["score"], reverse=True)                      # ③ best first
    retained = scored[:beam_width]                                           # ④ prune

    # Level 2: for each retained hedge, pick its best sizing
    for hedge in retained:                                                   # ⑤ per branch
        sizings = generate_sizings(portfolio, scenario, hedge, n=3)
        scored_sizings = [
            {**s, **score_sizing(portfolio, scenario, hedge, s)} for s in sizings
        ]
        scored_sizings.sort(key=lambda x: x["score"], reverse=True)
        hedge["best_sizing"] = scored_sizings[0]                             # ⑥ keep 1
    return retained


if __name__ == "__main__":
    portfolio = "5,000 shares of NVDA held outright (~$5M concentrated single-name position)"
    scenario = ("NVDA reports earnings tonight after the close; "
                "weekly implied volatility is elevated")
    for h in best_hedges(portfolio, scenario):
        print(f"{h['score']:>2}  {h['name']}: {h['reasoning']}")
        s = h["best_sizing"]
        print(f"    └─ best sizing ({s['score']}): {s['name']}: {s['reasoning']}")
📄 LATS (6.8) lats/lats_trim.py

Put this in a folder called lats/, next to the .claude folder below.

lats/lats_trim.py
"""
lats_trim.py — Friday afternoon: cut tech exposure from 40% toward 30% with
Language Agent Tree Search (LATS) on the Claude Agent SDK.

Folder layout (the two skills live next to this script):
    lats_trim.py
    .claude/skills/trade-evaluator/SKILL.md
    .claude/skills/trade-reflector/SKILL.md

Run it:
    pip install claude-agent-sdk anyio python-dotenv
    python lats_trim.py          # 3 iterations, 2 children per expansion, depth ≤ 3
"""
import copy
import json
import math
import re
from pathlib import Path

import anyio
from dotenv import load_dotenv
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, TextBlock, query

load_dotenv()
MODEL = "claude-sonnet-4-6"
PROJECT_DIR = Path(__file__).resolve().parent   # where .claude/skills/ lives
MAX_LESSONS = 5                                 # keep the lesson list short


# ---------- Pure environment (mock) ----------
# In practice you would read real exposures and constraints from your own systems.
INITIAL_MARKET = {
    "tech_exposure_pct": 40.0,
    "target_pct": 30.0,
    "slippage_bps": [],
}


def apply_trim(state, positions, pct):
    """Apply a trim and return (new_state, observation_text). Never mutates `state`."""
    new = copy.deepcopy(state)                               # a private copy per branch
    impact = 5 + len(positions) * 2 + pct * 1.5              # toy slippage model, in bps
    new["slippage_bps"].append(impact)
    new["tech_exposure_pct"] -= pct * len(positions) * 0.4   # toy exposure model
    obs = (
        f"Trimmed {positions} by {pct}% each. Slippage {impact:.1f} bps. "
        f"New tech exposure: {new['tech_exposure_pct']:.1f}%."
    )
    return new, obs


def reached_target(state):
    return state["tech_exposure_pct"] <= state["target_pct"]


# ---------- LATS tree ----------
class Node:
    """One node = the portfolio AFTER this node's trade (the root = before any trade)."""

    def __init__(self, action_hint, state, parent=None):
        self.action_hint = action_hint
        self.state = state
        self.parent = parent
        self.children = []
        self.depth = 0 if parent is None else parent.depth + 1
        self.visits = 0          # N(s): how many scores have flowed through here
        self.value = 0.0         # V(s): running average of those scores, 0..1
        self.is_terminal = False
        self.proposal = None     # the trade that created this node (not for root)
        self.observation = None  # what the environment said about that trade

    def update(self, score):
        # V_new(s) = (V_old(s) * (N(s) - 1) + r) / N(s)   — a running average
        self.visits += 1
        self.value = ((self.value * (self.visits - 1)) + score) / self.visits


def uct(child, parent_visits, w=1.41):
    """UCT = how good it has looked so far + a bonus for being rarely tried."""
    if child.visits == 0:
        return float("inf")                    # never tried → try it first
    n_p = max(parent_visits, 1)
    return child.value + w * math.sqrt(math.log(n_p) / child.visits)


# ---------- 1. Selection ----------
def select(root, k_expand, max_depth):
    """Walk root → leaf via max-UCT until a node is not fully expanded or terminal."""
    node = root
    while (
        not node.is_terminal
        and node.depth < max_depth
        and len(node.children) >= k_expand
    ):
        node = max(node.children, key=lambda c: uct(c, node.visits))
    return node


# ---------- Talking to Claude through the Agent SDK ----------
async def _run_query(prompt, system_prompt, max_turns, skill=None):
    """Send one prompt; return all the text Claude wrote. `skill` loads one skill."""
    options = ClaudeAgentOptions(
        model=MODEL,
        system_prompt=system_prompt,
        max_turns=max_turns,
        cwd=str(PROJECT_DIR),                    # so .claude/skills/ is found
        skills=[skill] if skill else [],         # [] = no skills for this call
    )
    parts = []
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if isinstance(block, TextBlock):
                    parts.append(block.text)
    return "\n".join(parts)


def parse_proposals(text):
    """Pull the JSON array out of the ```json block (or the first [...] found)."""
    m = (re.search(r"```(?:json)?\s*(\[.*?\])\s*```", text, re.S)
         or re.search(r"(\[.*\])", text, re.S))
    if not m:
        return []
    try:
        items = json.loads(m.group(1))
    except json.JSONDecodeError:
        return []
    return [p for p in items
            if p.get("positions") and isinstance(p.get("percent_each"), (int, float))]


def parse_score(text):
    """'... SCORE: 7' → 7 (clamped to 1..10; 1 if missing)."""
    found = re.findall(r"SCORE:\s*(\d+)", text)
    return max(1, min(10, int(found[-1]))) if found else 1


def parse_lesson(text):
    """'LESSON: When X, do Y.' → 'When X, do Y.'"""
    found = re.findall(r"LESSON:\s*(When .+)", text)
    return found[-1].strip() if found else None


# ---------- 2. Expansion: K distinct trims in ONE call ----------
PROPOSE_SYSTEM_PROMPT = """You are a trade-construction agent reducing tech exposure.
You will be asked to propose K distinct candidate trims from a given market state.
The K candidates MUST differ materially from one another -- different ticker
selection, different slice size, or different concentration profile. Mode
collapse to identical or near-identical trims is a failure.
Output exactly one fenced JSON code block and no other text. The block must
contain a JSON array of K objects, each with these fields:
- positions: list of ticker symbols (strings, non-empty)
- percent_each: number, the % to trim from each named position
- rationale: short string explaining the candidate's distinct angle
Example:
```json
[
  {"positions": ["NVDA", "AMD"], "percent_each": 5.0,
   "rationale": "concentrated semis trim"},
  {"positions": ["AAPL", "MSFT", "GOOGL", "META"], "percent_each": 2.5,
   "rationale": "diversified mega-cap shave"}
]
```
"""


async def propose_k_trims(state, k_expand, lessons):
    lessons_block = ""
    if lessons:                                              # reflexion-style memory
        lessons_block = "\n\nLessons from prior attempts:\n- " + "\n- ".join(lessons)
    prompt = (
        f"Current tech exposure: {state['tech_exposure_pct']:.1f}%. "
        f"Target: {state['target_pct']}%. "
        f"K = {k_expand}. Propose {k_expand} materially distinct trim candidates."
        f"{lessons_block}"
    )
    text = await _run_query(prompt, system_prompt=PROPOSE_SYSTEM_PROMPT, max_turns=2)
    return parse_proposals(text)


# ---------- 3. Evaluation: a skill scores each new child ----------
def _trajectory_block(parent_state, proposal, child_state, observation):
    return (
        f"Trajectory:\n"
        f"- Starting tech exposure: {parent_state['tech_exposure_pct']:.1f}%\n"
        f"- Action: trim {proposal['positions']} by {proposal['percent_each']}% each\n"
        f"- Rationale: {proposal.get('rationale', '')}\n"
        f"- Observation: {observation}\n"
        f"- Resulting tech exposure: {child_state['tech_exposure_pct']:.1f}%\n"
        f"- Target: {child_state['target_pct']}%"
    )


EVAL_SYSTEM_PROMPT = """You are evaluating a single tech-trim trajectory.
Use the Skill tool to invoke `trade-evaluator` on the trajectory described.
End your response with a line of the exact form: SCORE: <integer 1-10>
"""


async def evaluate_proposal(parent_state, proposal, child_state, observation):
    prompt = _trajectory_block(parent_state, proposal, child_state, observation)
    return await _run_query(prompt + "\n\nEvaluate this trajectory.",
                            system_prompt=EVAL_SYSTEM_PROMPT, max_turns=4,
                            skill="trade-evaluator")


async def expand(node, k_expand, lessons):
    """Grow `node` by up to k children; return [(child, score 0..1), ...]."""
    new = []
    for p in (await propose_k_trims(node.state, k_expand, lessons))[:k_expand]:
        child_state, obs = apply_trim(node.state, p["positions"], p["percent_each"])
        child = Node(action_hint=p.get("rationale"), state=child_state, parent=node)
        child.proposal, child.observation = p, obs
        child.is_terminal = reached_target(child_state)
        verdict = await evaluate_proposal(node.state, p, child_state, obs)
        node.children.append(child)
        new.append((child, parse_score(verdict) / 10))     # 1..10 → 0.1..1.0
    return new


# ---------- 5. Backpropagation ----------
def backprop(leaf, score):
    """Walk leaf → root, updating value/visits at every ancestor (incl. root)."""
    node = leaf
    while node is not None:
        node.update(score)
        node = node.parent


# ---------- 6. Reflection ----------
REFLECT_SYSTEM_PROMPT = """You are reflecting on a failed tech-trim trajectory.
Use the Skill tool to invoke `trade-reflector` on the trajectory described, then
end your response with a line of the exact form:
LESSON: When <situation>, do <action>.
"""


async def reflect_on_failure(parent_state, proposal, child_state, observation):
    prompt = _trajectory_block(parent_state, proposal, child_state, observation)
    return await _run_query(
        prompt + "\n\nThe target was not reached. Reflect on this trajectory.",
        system_prompt=REFLECT_SYSTEM_PROMPT, max_turns=4, skill="trade-reflector")


# ---------- Printing helpers ----------
def name_of(node):
    if node.parent is None:
        return "root"
    return f"{name_of(node.parent)}/c{node.parent.children.index(node) + 1}"


def all_nodes(node):
    yield node
    for c in node.children:
        yield from all_nodes(c)


def print_tree(root):
    print("\n=== Final tree ===")
    for n in all_nodes(root):
        print(f"{'  ' * n.depth}{name_of(n)}: N={n.visits} V={n.value:.2f} "
              f"exposure={n.state['tech_exposure_pct']:.1f}%")


# ---------- The LATS loop ----------
async def lats_search(n_iterations=3, k_expand=2, max_depth=3):
    root = Node(action_hint=None, state=copy.deepcopy(INITIAL_MARKET))
    lessons = []                                             # long-term memory

    for it in range(1, n_iterations + 1):
        print(f"\n=== Iteration {it} ===")
        node = select(root, k_expand, max_depth)                          # 1 SELECT
        print(f"Selected: {name_of(node)} (depth={node.depth}, "
              f"N={node.visits}, V={node.value:.2f})")
        if node.depth >= max_depth:
            print("Reached max depth on this branch; skipping.")
            node.is_terminal = True
            continue

        new = await expand(node, k_expand, lessons)                       # 2 EXPAND + 3 EVALUATE
        for child, score in new:
            p = child.proposal
            print(f"[add ] {name_of(child)}: positions={p['positions']} "
                  f"pct={p['percent_each']}  score={score * 10:.1f}/10  "
                  f"exposure={child.state['tech_exposure_pct']:.1f}%")
        if not new:
            print("No valid proposals this round.")
            continue

        winners = [c for c, _ in new if c.is_terminal]                    # 4 SIMULATE (1 step)
        if winners:
            print(f"Target reached by {name_of(winners[0])}!")
            return winners[0]

        for child, score in new:                                          # 5 BACKPROPAGATE
            backprop(child, score)

        best_child, _ = max(new, key=lambda cs: cs[1])                    # 6 REFLECT
        verdict = await reflect_on_failure(node.state, best_child.proposal,
                                           best_child.state, best_child.observation)
        lesson = parse_lesson(verdict)
        if lesson and lesson not in lessons:                              # dedupe
            lessons.append(lesson)
            lessons = lessons[-MAX_LESSONS:]                              # cap at 5
            print(f"[lesson] {lesson}")

    print_tree(root)
    leaves = [n for n in all_nodes(root) if n.parent and not n.children]
    best = max(leaves, key=lambda n: (n.value, -n.state["tech_exposure_pct"]))
    print(f"Best leaf: {name_of(best)}  V={best.value:.2f}  "
          f"exposure={best.state['tech_exposure_pct']:.1f}%")
    return best


if __name__ == "__main__":
    anyio.run(lats_search, 3, 2, 3)          # n_iterations, k_expand, max_depth
📄 Skill: trade-evaluator lats/.claude/skills/trade-evaluator/SKILL.md

Save at lats/.claude/skills/trade-evaluator/SKILL.md

lats/.claude/skills/trade-evaluator/SKILL.md
---
name: trade-evaluator
description: Score a partial tech-sector trim trajectory. Use when asked to evaluate how close a trajectory is to the target reduction at acceptable cost.
---

Score the trajectory from 1 to 10 using these criteria:
- 6-10: progress on target exposure exceeds elapsed time fraction, slippage
  below 8 bps per child order, residual risk broadly diversified.
- 3-5: on-pace but slippage between 8 and 15 bps, or concentrated residual.
- 1-2: behind schedule, or slippage above 15 bps on any child order.

Return a single integer score and a one-sentence justification.
📄 Skill: trade-reflector lats/.claude/skills/trade-reflector/SKILL.md

Save at lats/.claude/skills/trade-reflector/SKILL.md

lats/.claude/skills/trade-reflector/SKILL.md
---
name: trade-reflector
description: Write a one-sentence reflection on a failed tech-sector trim. Use when a trajectory ended short of its target exposure reduction.
---

Identify the single most important decision that caused the shortfall (venue
choice, slice size, timing, or name selection) and phrase the lesson as a
conditional rule the agent can apply next time.

Output exactly one line, with no other text, in this exact form:
LESSON: When <situation>, do <action>.