Introducing

Querying Financial Markets with the Polgon.io MCP server, Claude 4, and Pydantic AI

Aug 1, 2025

What if you could simply ask a question in plain English, like "How is APPL performing right now compared to AMZN?", and get a structured, reliable answer based on the most up to date information?

Thanks to the convergence of high-fidelity data, powerful AI models, and modern development frameworks, this is now possible. This tutorial will walk you through building a simple but powerful AI financial analyst. We'll use a stack that combines Polygon.io's real time market data (via the Polygon.io MCP server) with the reasoning capabilities of Anthropic's Claude 4, all tied together with the Pydantic AI agent framework.

This is all the code any AI agent needs to query real time stock market data.

Tech Stack Breakdown

We'll be using these key components to create our AI financial analyst:

  • Polygon.io: Our foundation and source of truth. Polygon.io provides the institutional-grade, low-latency financial data that our agent needs to provide accurate answers.
  • Polygon.io MCP Server: An experimental Model Context Protocol (MCP) server that acts as a universal translator. It exposes the Polygon.io API as a set of "tools" that an AI can understand and use without needing to know the specifics of REST or WebSockets.
  • Anthropic's Claude 4: The "brain" of our operation. Claude is a frontier AI model with advanced reasoning capabilities. It can understand a user's natural language question, formulate a plan, and decide which tools to use to find the answer.
  • Pydantic AI: A Python framework that brings structure, type-safety, and reliability to our AI agent. It ensures that the AI's output is predictable and correctly formatted, turning a non-deterministic model into a dependable application component.
  • Rich: A Python library for beautiful formatting in the terminal. While the agent does the heavy lifting,
    rich
    makes the output easy to read. It allows for color, styling, tables, and progress bars, turning a standard terminal output into a more user-friendly and visually appealing display.

Tutorial

Prerequisites

Before we start, make sure you have the following:

  • Python 3.10+
  • UV
  • A Polygon.io API key (you can get one by signing up for an account here)
  • An Anthropic API key (you can get one by signing up for an account here)

Clone the repo

You can find the code for this tutorial in our Polygon.io community space. Head over there and run the following in a terminal. Then, cd into the market parser directory.

git clone https://github.com/polygon-io/community.git
cd community/examples/rest/market-parser-polygon-mcp

Create an .env file

Run the following command to copy the example .env file.

cp .env_example .env

Open the file and paste in your API keys for Polygon.io and Anthropic. Make sure to save the file.

open -e .env

Run the solution

Run the following command to run the cli interface.

uv run market_parser_demo.py

At this point, you should see the following - where it asks you to enter in a query.

Enter in the following as just an example:

Get the latest price of Tesla

You should see a response similar to the below, showing the latest price of Tesla.

Now, while this query was simple - you can also give it other more advanced questions. As always, be specific in your prompting. The better the prompt - the better the response.

If you want to quit, type the word

exit
and hit enter.

Other example queries

For reference, here are some other examples of things you can ask and responses you could expect to get back.

Look back from today to five years ago. Return the total return on investment for Microsoft

Crypto has been up and down recently. Search the latest news, and tell me why

And you can even go further, asking it to do deep analysis and reporting on multiple tickers. Keep in mind this is not me giving you financial advice.

Consider an investment between Meta, Amazon, and Google. Which one is the best bet based on returns, earnings, latest news, and market sentiment

Code breakdown

The code is pretty simple. All of it is in one file in the code repository called

market_parser_demo.py
and is under 150 lines.

MCP server connection

To add in the Polygon.io MCP server to an agentic workflow, you simply need to point it to the repository.

def create_polygon_mcp_server():
    ...
    return MCPServerStdio(
        command="uvx",
        args=[
            "--from",
            "git+https://github.com/polygon-io/mcp_polygon@v0.4.0",
            "mcp_polygon"
        ],
        env=env
    )

Agentic workflow

Configuring the agent couldn't be more simple for this use case. You pass in a model, which in this case is Claude 4 sonnet, the MCP server we created, and a system prompt. This gives the LLM access to any and all tools the MCP server has access to.

Within the agent configuration below, there is a

system_prompt
that gives the agentic flow more more context. This could be more refined to further fit your specific use case.

agent = Agent(
    model="anthropic:claude-4-sonnet-20250514",
    mcp_servers=[server],
    system_prompt=(
        "You are an expert financial analyst. "
        "Note that when using Polygon tools, "
        "prices are already stock split adjusted. "
        "`Use` the latest data available. "
        "Always double check your math. "
        "For any questions about the current date, "
        "use the 'get_today_date' tool. "
        "For long or complex queries, "
        "break the query into logical subtasks and "
        "process each subtask in order."
    )
)

Message history

Additionally, the solution is configured to send over the entire message history of the conversation to the LLM in order to provide additional context.

response = await agent.run(
    user_input,
    message_history=message_history
)

Enhancement opportunities

While this demo allows you to utilize most of the Polygon.io endpoints in a simple CLI chat interface, there are some feature enhancements that could be done to the repository to make it better.

  • Better message history
  • Error handling
  • Task subdivision for larger queries
  • Model customization
  • Integration with other services

Wrap-up

Accessing real time and historical stock market data shouldn't be hard. Polygon.io's MCP server, alongside Anthopic's Claude 4 and Pydantic AI's agent framework, make it super easy.

Again, you can find the GitHub repository for this demo here, and Polygon.io has a generous free tier that is super easy to sign up for.

So what are you waiting for?

Clone the repo. Run the CLI. Talk to the market.


The examples, demos, and outputs produced with this project are generated by artificial intelligence and large language models. You acknowledge that this project and any outputs are provided "AS IS", may not always be accurate and may contain material inaccuracies even if they appear accurate because of their level of detail or specificity, outputs may not be error free, accurate, current, complete, or operate as you intended, you should not rely on any outputs or actions without independently confirming their accuracy, and any outputs should not be treated as financial or legal advice. You remain responsible for verifying the accuracy, suitability, and legality of any output before relying on it.

From the blog

See what's happening at polygon.io

benzingadata partnership Feature Image
announcement

Benzinga Data Now Available on Polygon.io

Polygon.io is excited to announce a new partnership with Benzinga, significantly enhancing our financial data offerings. Benzinga’s detailed analyst ratings, corporate guidance, earnings reports, and structured financial news are now available through Polygon’s REST APIs.

hunting anomalies in the stock market Feature Image
tutorial

Hunting Anomalies in the Stock Market

This tutorial demonstrates how to detect short-lived statistical anomalies in historical US stock market data by building tools to identify unusual trading patterns and visualize them through a user-friendly web interface.