Kevin Meneses
โ† Back to articles

I Built an AI Agent That Tries to Prove My Stock Thesis Wrong

AI AgentsStock AnalysisEODHDClaudePythonInvestingFintech
I Built an AI Agent That Tries to Prove My Stock Thesis Wrong

Most investors don't lose money because they lack information.

They lose money because they only read the information that agrees with them.

You buy a stock because "margins are improving". From that moment, every headline that says margins looks like proof. The quarter where operating margin fell by half? You skim past it. The insider selling? Probably taxes.

That's confirmation bias. And it doesn't show up in your spreadsheet. It's the filter you use to read the spreadsheet.

If you're:

  • holding a position you haven't stress-tested in months,
  • writing investment memos for a fund or a newsletter,
  • or building AI tools for stock analysis,

this matters.

The problem: AI makes confirmation bias worse

Ask ChatGPT "Is Tesla improving its margins?" and you'll get a confident answer. Ask it "Why is Tesla improving its margins?" and it will happily explain why. Without real financial data, an LLM tends to agree with the question.

So most "AI stock analysis" tools end up as yes-men.

They summarize. They cheer. They rarely say "your numbers don't support this."

The fix isn't a smarter model. It's a different job description.

The solution: an AI agent built to prove you wrong

I built an AI stock analysis agent with one instruction: try to disprove the thesis.

You give it a ticker and a thesis like "Tesla is improving its margins". The agent pulls real fundamentals and news from the EODHD API, runs 9 deterministic checks in Python, then uses Claude with 8 data tools to dig for counter-evidence.

It returns:

  • Contradictions: numbers that go against the thesis, with the quarter and the source.
  • Missing data: what the dataset can't show (segments, guidance, one-off items).
  • Open questions: what you still need to answer before you trust the thesis.

On Tesla, the rules engine alone found 9 contradictions. Real data, last reported quarter.

The code is below. It runs on the free EODHD demo key for TSLA, AAPL and MSFT. Get an EODHD API key to test it on any stock.


How the AI stock analysis agent works

AI stock analysis agent workflow: thesis, EODHD APIs, rules engine, Claude agent, report

Two layers on purpose:

  1. Rules engine (red_flags.py): plain Python, the same output every run, and it works with no API key. Example: "gross margin went up but operating margin went down โ†’ opex absorbed the gain."
  2. Agent (thesis_breaker.py): Claude checks those flags, calls tools for more data, searches the news for context, and writes the open questions. It can only cite numbers that a tool returned.

Real example: testing "Tesla is improving its margins"

Data: EODHD fundamentals and news, last reported quarter 2026-09-30 (fetched 2026-11-28).

QuarterRevenue $bnGross %Operating %Net %
2025-09-3028.0917.995.784.89
2025-12-3124.9020.125.663.37
2026-03-3122.3921.084.202.19
2026-06-3028.2416.831.413.95
2026-09-3028.0519.592.562.81

If you only look at gross margin, the thesis looks fine: 17.99% โ†’ 19.59% year over year. The agent looks further down the income statement:

  1. Operating margin fell by half year over year. 5.78% โ†’ 2.56%. Two years ago it was 10.79%.
  2. The gross margin gain didn't reach operating profit. R&D + SG&A went from 11.4% to 17.0% of revenue.
  3. Interest income is a big part of profit. In 2026-03-31, interest income was $0.43bn against $0.94bn of operating income.
  4. FCF after stock comp is negative. Over the last 4 quarters, FCF minus SBC = โˆ’$0.99bn, with SBC at $4.3bn.
  5. Cash flow leaned on working capital. $2.59bn of the $6.26bn in Q3 operating cash flow came from working capital.
  6. Inventory days went up. 48 โ†’ 57.
  7. Revenue is flat. $28.09bn โ†’ $28.05bn, so scale isn't helping margins.
  8. EPS missed estimates in 3 of the last 6 quarters, including โˆ’38.9% in 2026-06-30.
  9. Insiders are selling. 20 open-market sells, 0 buys.

Verdict: the thesis is contradicted if "margins" means operating or net margin. It only holds for gross margin.

This is a research tool, not investment advice.


Inside the code

Three pieces do the work. Here is the core of each one.

1. Pull fundamentals and news from EODHD

import requests

def eodhd(endpoint, **params):
    params |= {"api_token": EODHD_API_KEY, "fmt": "json"}
    r = requests.get(f"https://eodhd.com/api/{endpoint}", params=params, timeout=60)
    r.raise_for_status()
    return r.json()

fund = eodhd("fundamentals/TSLA.US")          # statements, EPS history, insiders
news = eodhd("news", s="TSLA.US", limit=50)   # articles + sentiment
income = fund["Financials"]["Income_Statement"]["quarterly"]

2. A deterministic red-flag check

Every check compares the same quarter year over year and fires only when the numbers contradict a bullish reading.

last, year_ago = margins[-1], margins[-5]

if last["gross_margin_pct"] > year_ago["gross_margin_pct"] and    last["operating_margin_pct"] < year_ago["operating_margin_pct"]:
    flags.append({
        "severity": "high",
        "claim": "Gross margin improved, but none of it reached operating profit",
        "evidence": f"Gross {year_ago['gross_margin_pct']}% -> {last['gross_margin_pct']}%, "
                    f"operating {year_ago['operating_margin_pct']}% -> {last['operating_margin_pct']}%",
    })

3. The agent: Claude with tools and one job

import anthropic
from anthropic import beta_tool

SYSTEM = """You are a short-seller's research analyst. Your only job is to try to
DISPROVE the user's investment thesis. Every number you cite must come from a tool."""

@beta_tool
def get_margins(quarters: int = 9) -> str:
    """Quarterly revenue and gross / operating / net margins."""
    return json.dumps(company.margins(quarters))

# ...7 more tools: cash quality, balance sheet, EPS surprises, insiders, news search...

runner = anthropic.Anthropic().beta.messages.tool_runner(
    model="claude-opus-5-5",
    max_tokens=16000,
    system=SYSTEM,
    tools=[get_margins, get_cash_quality, get_balance_sheet, get_earnings_surprises,
           get_insider_activity, search_news, get_data_gaps, get_profile],
    output_config={"effort": "high"},
    messages=[{"role": "user", "content": f"Thesis: {thesis}
Flags: {flags}"}],
)
for message in runner:   # the SDK runs the tool loop for you
    final = message

The system prompt is the whole trick. Same model, same data, different job: "explain" gets you a cheerleader, "disprove" gets you an analyst.


Run the agent in Python

pip install anthropic requests

Rules only (no LLM, uses the free EODHD demo key, which covers TSLA, AAPL and MSFT):

python thesis_breaker.py TSLA.US "Tesla is improving its margins" --offline

Full agent:

export EODHD_API_KEY=your_eodhd_key
export ANTHROPIC_API_KEY=your_anthropic_key
python thesis_breaker.py NKE.US "Nike's turnaround is restoring margins" --out nike.md

Options: --effort low|medium|high|xhigh|max (default high), --refresh to skip the local cache, and --out to save the report.

The thesis can be in any language. The report comes back in the same one.


5 prompts that make the agent sharper

The agent is only as good as the thesis you give it. A vague thesis gets a vague answer. These five prompts help before and after the run. Paste them into Claude or any LLM, together with the agent's report when the prompt asks for it.

1. Turn a hunch into a testable thesis

I think [COMPANY] is a good investment because [YOUR REASON].
Rewrite this as one falsifiable sentence with a metric, a direction and a time frame.
Example: "Operating margin will be higher in Q4 2026 than in Q4 2025."
Then list the 3 numbers that would prove it wrong.

2. Run a pre-mortem

It is 12 months from now and my position in [COMPANY] is down 40%.
My original thesis was: "[THESIS]".
Write the 5 most likely reasons it failed, ranked by probability.
For each one, name the line of the financial statements where I would have seen it first.

3. Set your kill criteria before the data arrives

My thesis is: "[THESIS]".
Define 3 to 5 concrete conditions that would make me sell or stop believing it.
Each condition must be a number I can check in a quarterly report (e.g. "operating margin below 3% for two quarters").

4. Stress-test the agent's report

Here is the report from an agent that tried to disprove my thesis:
[PASTE REPORT]
For each contradiction, tell me if it is structural (will persist) or temporary (one-off, timing, accounting).
Then tell me which single contradiction matters most and why.

5. Turn open questions into an action list

Here are the open questions from my thesis review:
[PASTE OPEN QUESTIONS]
For each one, tell me where to find the answer: 10-Q/10-K section, earnings call, investor presentation, or industry data.
Then write the 3 questions I would ask management on the next earnings call.

Prompts 1 to 3 run before the agent. Prompts 4 and 5 run after it.


Key takeaways

  • Ask the AI to disprove you, not to explain you. The job description changes the answer more than the model does.
  • Gross margin is not "margins". Tesla's gross margin rose year over year while operating margin fell by half. One line of the income statement can hide the whole story.
  • Rules first, LLM second. Deterministic checks give you the same answer every run and work for free. The LLM adds context, news and questions on top of numbers it can't invent.

Why EODHD for financial data

The agent is only as good as its data. One EODHD key gives you:

  • Fundamentals: 10+ years of quarterly income statements, balance sheets and cash flows, plus EPS history, insider transactions and analyst ratings, in a single call.
  • Financial news with per-article sentiment, filterable by ticker.
  • Coverage of 70+ exchanges, so the same agent works on European, Asian and emerging-market stocks.

The demo key only covers three tickers. To test your own theses on any company:

Get your EODHD API key here, then run the agent on the stock you're most sure about. That's the one it should test first.


FAQs

Can AI analyze stocks?

Yes, but only as well as the data you give it. An LLM without financial data guesses and tends to agree with how you frame the question. Connected to fundamentals and news through an API like EODHD, it can check a thesis against reported numbers and cite the quarter it found them in.

How do I avoid confirmation bias when investing?

Write your thesis down as one testable sentence, then look specifically for evidence against it. This agent automates that step: it compares year-over-year margins, cash flow quality, inventory, EPS surprises and insider activity, and lists every number that contradicts you.

What data does the agent use?

EODHD's Fundamentals API (quarterly income statement, balance sheet, cash flow, EPS history, insider transactions) and EODHD's Financial News API (articles with sentiment scores). The agent cannot use numbers that don't come from those tools.

Is there a free stock fundamentals API?

EODHD offers a free demo key that covers TSLA, AAPL and MSFT on every endpoint, which is enough to run this project. To analyze other tickers you need a paid EODHD plan that includes fundamentals.

Can I run the agent without an LLM API key?

Yes. Run it with --offline and it uses only the rules engine: 9 deterministic checks in plain Python, with no API cost. The Claude agent adds news context, verifies the flags and writes the open questions.

Which model does the agent use?

Claude Opus 5.5 (claude-opus-5-5) through the Anthropic Python SDK's tool runner. You can lower the cost with --effort low or --effort medium.

Does it work for theses other than margins?

Yes. The tools cover growth, cash generation, balance sheet strength, earnings quality and insider behavior. Try "Nike's turnaround is working" or "Apple's services business is driving profit growth".


Project structure

FileWhat it does
eodhd_data.pyEODHD client with local cache, plus evidence builders (margins, cash quality, balance sheet, EPS, insiders, news search, data gaps)
red_flags.py9 deterministic contradiction checks
thesis_breaker.pyCLI + Claude agent (tool runner, 8 tools, server-side refusal fallback)
sample_report_TSLA.mdReal output on Tesla

Most investors don't need more conviction. They need someone, or something, paid to disagree with them.


Looking for technical content for your company? I write educational articles about APIs, fintech and AI tools for developer audiences (not marketing fluff). Let's talk: LinkedIn ยท kevinmenesesgonzalez@gmail.com

I Built an AI Agent That Tries to Prove My Stock Thesis Wrong