{"slug": "how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api", "title": "How to Build an AI Trading Bot with Claude and the EODHD API", "summary": "A developer demonstrates how to build an AI trading bot that combines the EODHD API for market data with Anthropic's Claude large language model for reasoning, replacing rule-based logic with contextual judgment. The tutorial shows how to fetch end-of-day prices and live quotes via EODHD, then prompt Claude to output structured buy/hold/sell decisions with reasoning, aiming to adapt to market shifts that static rules miss.", "body_md": "Most trading bots are just if-statements wearing a costume.\n\nRSI below 30, buy. Moving averages cross, sell. That works fine until the market does something the rules didn't anticipate, and then the bot keeps executing the same logic anyway, because it can't actually think.\n\nIf you're:\n\nthis is for you.\n\nA rule-based bot doesn't understand the market. It pattern-matches against a formula someone wrote months ago.\n\nEarnings surprise. A sudden news event. A sector rotation nobody coded for. The bot has no way to account for any of it, because it was never built to interpret context, only to check conditions.\n\nDevelopers usually discover this the hard way. They backtest a strategy, watch it perform well on historical data, deploy it, and then spend the next few months tweaking thresholds every time the market shifts. The bot isn't wrong. It's just blind.\n\nThere's also the data problem underneath all of this. Plenty of hobby projects lean on scraped Yahoo Finance endpoints or free tiers that cap out fast, and both tend to fail exactly when you need them most.\n\nA trading bot doesn't need more rules. It needs reasoning.\n\nThat's a different kind of system entirely. Instead of \"if X then Y,\" you want something closer to \"given this data, what would a reasonable analyst conclude, and why.\"\n\nLarge language models are good at exactly that kind of contextual judgment, as long as you feed them clean, structured data instead of asking them to guess.\n\nThis tutorial combines two pieces:\n\n**EODHD API** for market data. End-of-day prices, real-time quotes, fundamentals, and historical data through a single REST interface, without maintaining scrapers that break every time a website changes its HTML.\n\n**Claude** for the reasoning layer. Given a snapshot of price action, volume, and basic fundamentals, Claude produces a structured decision (buy, hold, sell) along with the reasoning behind it, in a format your code can actually parse and act on.\n\nYou could swap either piece out. The point isn't \"use these exact two tools forever,\" it's showing how the pattern works so you can adapt it.\n\nWant reliable market data without building your own scraping layer?\n\nEODHD covers over 150,000 tickers with a generous free tier and no rate-limit surprises mid-project.\n\n[Get your free EODHD API key →]\n\nYou'll need two API keys: one from EODHD, one from Anthropic.\n\n```\npip install requests anthropic python-dotenv\n```\n\nStore your keys in a `.env`\n\nfile:\n\n```\nEODHD_API_KEY=your_eodhd_key_here\nANTHROPIC_API_KEY=your_anthropic_key_here\n```\n\nStart with a function that grabs recent price history and a live quote for a given ticker.\n\n``` python\nimport os\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\nEODHD_KEY = os.getenv(\"EODHD_API_KEY\")\n\ndef get_market_data(ticker: str, exchange: str = \"US\"):\n    symbol = f\"{ticker}.{exchange}\"\n\n    # Last 30 days of end-of-day prices\n    eod_url = f\"https://eodhd.com/api/eod/{symbol}\"\n    eod_params = {\n        \"api_token\": EODHD_KEY,\n        \"period\": \"d\",\n        \"fmt\": \"json\",\n        \"order\": \"d\",\n    }\n    eod_resp = requests.get(eod_url, params=eod_params).json()[:30]\n\n    # Live quote\n    quote_url = f\"https://eodhd.com/api/real-time/{symbol}\"\n    quote_params = {\"api_token\": EODHD_KEY, \"fmt\": \"json\"}\n    quote_resp = requests.get(quote_url, params=quote_params).json()\n\n    return {\n        \"ticker\": ticker,\n        \"current_price\": quote_resp.get(\"close\"),\n        \"change_pct\": quote_resp.get(\"change_p\"),\n        \"volume\": quote_resp.get(\"volume\"),\n        \"recent_history\": eod_resp,\n    }\n```\n\nThis gives you a clean payload: current price, percentage change, volume, and 30 days of history. No scraping, no broken HTML selectors.\n\nThis is the part that separates it from a rule-based bot. Instead of hardcoding thresholds, you hand Claude the data and ask for a structured judgment call.\n\n``` python\nimport json\nfrom anthropic import Anthropic\n\nclient = Anthropic(api_key=os.getenv(\"ANTHROPIC_API_KEY\"))\n\ndef get_trading_decision(market_data: dict) -> dict:\n    prompt = f\"\"\"You are a trading analyst reviewing market data for {market_data['ticker']}.\n\nCurrent price: {market_data['current_price']}\nChange today: {market_data['change_pct']}%\nVolume: {market_data['volume']}\nRecent 30-day history: {json.dumps(market_data['recent_history'][:10])}\n\nBased on this data, provide a trading decision. Respond ONLY with valid JSON in this exact format:\n{{\n  \"decision\": \"buy\" | \"hold\" | \"sell\",\n  \"confidence\": 0.0 to 1.0,\n  \"reasoning\": \"2-3 sentence explanation grounded in the data provided\"\n}}\"\"\"\n\n    response = client.messages.create(\n        model=\"claude-sonnet-4-6\",\n        max_tokens=300,\n        messages=[{\"role\": \"user\", \"content\": prompt}],\n    )\n\n    raw_text = response.content[0].text.strip()\n    return json.loads(raw_text)\n```\n\nThe key detail here is the response format. Asking for structured JSON, not a paragraph, is what makes this usable in an actual pipeline instead of a chat window.\n\n``` python\ndef run_analysis(ticker: str):\n    data = get_market_data(ticker)\n    decision = get_trading_decision(data)\n\n    print(f\"\\n{ticker} — Decision: {decision['decision'].upper()}\")\n    print(f\"Confidence: {decision['confidence']}\")\n    print(f\"Reasoning: {decision['reasoning']}\")\n\n    return decision\n\nif __name__ == \"__main__\":\n    run_analysis(\"AAPL\")\n```\n\nSample output:\n\n```\nAAPL — Decision: HOLD\nConfidence: 0.62\nReasoning: Price is up 0.8% on below-average volume, suggesting limited\nconviction behind the move. Recent history shows consolidation rather than\na clear trend, so waiting for a volume-confirmed breakout makes more sense\nthan acting now.\n```\n\nThat reasoning field is the whole point. You get a decision plus the logic behind it, which you can log, review, and adjust over time. A rule-based bot never gives you that.\n\nBefore connecting this to anything resembling a real account, run it against a paper trading environment.\n\nAlpaca is a solid option here. Its paper trading API mirrors the live trading endpoints exactly, so you can route Claude's decisions through simulated buy and sell orders and see how the strategy would have performed, with fake money and real market conditions.\n\n``` python\nimport alpaca_trade_api as tradeapi\n\nalpaca = tradeapi.REST(\n    os.getenv(\"ALPACA_API_KEY\"),\n    os.getenv(\"ALPACA_SECRET_KEY\"),\n    \"https://paper-api.alpaca.markets\",\n)\n\ndef execute_paper_trade(ticker: str, decision: dict):\n    if decision[\"decision\"] == \"hold\":\n        print(f\"No action for {ticker}, holding position.\")\n        return\n\n    side = \"buy\" if decision[\"decision\"] == \"buy\" else \"sell\"\n\n    alpaca.submit_order(\n        symbol=ticker,\n        qty=1,\n        side=side,\n        type=\"market\",\n        time_in_force=\"day\",\n    )\n    print(f\"Paper {side} order submitted for {ticker}.\")\n```\n\nRun `execute_paper_trade`\n\nafter `get_trading_decision`\n\nand you have a full loop: EODHD for data, Claude for reasoning, Alpaca for execution, all without a single dollar at risk.\n\nThis is also where you'd start tracking accuracy. Log every decision, compare it against what actually happened three or five days later, and you'll quickly see whether the reasoning holds up or needs a better prompt.\n\nFrom here you can build:\n\nAn LLM adds contextual reasoning that fixed rules can't replicate on their own.\n\nClean, reliable market data matters more than people expect. Claude is only as good as what you feed it, and EODHD removes the guesswork of scraping or rate-limited free APIs.\n\nThis is a starting point, not a production system. Position sizing, stop losses, and proper risk management live outside the scope of this tutorial, and skipping them before going live is how paper gains turn into real losses.\n\n❓ Do I need trading experience to build this?\n\n✅ No. You need basic Python and an understanding of what a buy, hold, or sell decision means. The reasoning comes from Claude, not from you having to encode strategy logic manually.\n\n❓ Is this real algorithmic trading?\n\n✅ It's a form of it, specifically an LLM-assisted decision layer rather than a pure quantitative model. Traditional algo trading uses fixed mathematical rules; this approach adds a reasoning step on top of the data.\n\n❓ Can I connect this to a real brokerage account?\n\n✅ Technically yes, since Alpaca's live and paper APIs share the same structure. Don't, until you've backtested extensively and added proper risk controls. This tutorial is educational, not a plug-and-play trading system.\n\n❓ Does EODHD provide real-time data or only end-of-day?\n\n✅ Both. EODHD offers end-of-day historical data going back years, plus real-time and delayed quotes depending on your plan, which is why it works for both the historical context and the live price checks in this tutorial.\n\nIf you're a software or API company looking to explain your product through high-quality educational content, not marketing fluff, feel free to connect with me on LinkedIn: [Kevin Meneses González](https://www.linkedin.com/in/kevin-meneses-gonzalez/)\n\nBuilding something with market data?\n\nEODHD gives you 30+ years of historical data, real-time quotes, and fundamentals in one API.\n\n[Start free with EODHD →]\n\nMore tutorials like this\n\nI write about fintech APIs, Python, and AI agents every week.\n\n[Read more on kevinmeneses.com →]\n\n*Looking for technical content for your company? I can help — LinkedIn · kevinmenesesgonzalez@gmail.com*", "url": "https://wpnews.pro/news/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api", "canonical_source": "https://dev.to/kevin_menesesgonzlez/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api-1l2a", "published_at": "2026-08-05 13:52:53+00:00", "updated_at": "2026-08-05 14:02:55.036009+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-products", "developer-tools"], "entities": ["Claude", "EODHD API", "Anthropic"], "alternates": {"html": "https://wpnews.pro/news/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api", "markdown": "https://wpnews.pro/news/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api.md", "text": "https://wpnews.pro/news/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api.txt", "jsonld": "https://wpnews.pro/news/how-to-build-an-ai-trading-bot-with-claude-and-the-eodhd-api.jsonld"}}