Creating stock market reports using Open AI's GPT-5 and Agent SDK with the Polygon.io MCP server in under 200 lines of code
Aug 19, 2025
What if we could investigate a certain ticker's performance over a period of time or compare two securities against one another - including news, sentiment, earnings, and more? Plus, save that analysis in a report.
Well, now you can. This tutorial will walk you through building a stock market analysis agent. We'll use a stack that combines Polygon.io's real time and historical market data (via the Polygon.io MCP server) with the brand new advanced capabilities of OpenAI's GPT-5, all tied together with the easy to use Open AI Agent SDK.
Tech Stack Breakdown
We'll be using these key components to create our stock market agentic workflow:
Polygon.io: The bedrock and authoritative data provider. Polygon.io delivers high-grade, low-latency financial information that our agent relies upon for factual accuracy.
Polygon.io MCP Server: This presents the Polygon.io API as agent-friendly tools—so our AI doesn’t need to grapple with REST specifics. Think USB-C cable for a LLM.
OpenAI's GPT-5: OpenAI’s most advanced flagship model, released in August 2025, serving as the new default across ChatGPT and the API.
OpenAI's Agent SDK: A developer toolkit crafted to build agent-driven applications with minimal complexity. The Agents SDK offers streamlined, composable primitives—Agents (configured LLMs with instructions, model parameters, and tool access), plus mechanisms such as handoffs and built-in observability for debugging and tracing agent behaviors
Rich: A Python library that enhances terminal output with elegant design. Rich transforms plain console text into visually rich output with color, styling, tables, and progress bars—making the agent’s results both functional and delightful to read.
Tutorial
Prerequisites
Before we start, make sure you have the following:
A Polygon.io API key (you can get one by signing up for an account here)
An OpenAI 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 GPT-5 directory.
git clone https://github.com/polygon-io/community.git
cd community/examples/rest/gpt5-openai-agents-sdk-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 OpenAI. Make sure to save the file.
open -e .env
Run the solution
Run the following command to run the demo.
uv run main.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 Microsoft
You should see a response similar to the below, showing the latest price of Apple.
Now, while that 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.
Lets try something more advanced. Note - this query might take some time due to the extensive research it will need to do.
Do a deep dive on Microsoft over the last three years. Save a report with your findings.
After the agentic flow finishes, you should see something similar to this in the terminal window.
And, since I asked it to save a report in my prompt - you'll notice a new markdown file in the reports folder with all of the information from the investigation. You can do this with any prompt you provide. It will also remember context as you send in more messages.
At this point, you could even go further, asking it to do deep analysis and reporting on multiple tickers, like comparing Microsoft to Amazon or Google.
Keep in mind this agentic flow is not financial advice.
OpenAI also has an awesome debugging tool called the Traces dashboard. It will automatically pick up all of the steps that the demo makes. You can then click into each step, and see what/if any errors appear.
If you want to quit, type the word
exit
and hit enter.
Code breakdown
The code is pretty simple. All of it is in one file in the code repository called
main.py
and is under 200 lines.
If aren't familiar, the OpenAI's Agent SDK uses four primitives to create agentic workflows. The following is pulled directly from this site.
Agents, which are LLMs equipped with instructions and tools
Handoffs, which allow agents to delegate to other agents for specific tasks
Guardrails, which enable validation of agent inputs and outputs
Sessions, which automatically maintains conversation history across agent runs
In the demo we use three of these. Let's checkout how.
Agent
This is the core of any agentic workflow. In our example the agent has the following:
Name: can be anything
Instructions: what you want the agent to do specifically
MCP Server: how we point our agent to a MCP server (note you can point to more than one)
Tools: how we point the agent to any custom tool or tools in our code
Input Guardrails: a custom function you want the agent to do first
Model: what specific model you would like to use
Model Settings: allows you to configure context window sizing
In our case, we are only using one agent, but you could enhance this to have multiple agents, using handoffs. For example, an agent specific dedicated to reviewing just news.
analysis_agent = Agent(
name="Financial Analysis Agent",
instructions=(
"Financial analysis agent. Steps:\n""1. Verify finance-related using guardrail\n""2. Call Polygon tools precisely; pull the minimal required data.\n""3. Include disclaimers.\n""4. Offer to save reports if not asked by the user to save a
report.\n\n""RULES:\n""Double-check math; limit news to ≤3 articles/ticker in date range.\n""If the user asks to save a report, save it to the reports folder
using the save_analysis_report tool.\n""When using any polygon.io data tools, be mindful of how much data you
pull based \n""on the users input to minimize context being exceeded.\n""If data unavailable or tool fails, explain gracefully — never
fabricate.\n""TOOLS:\n""Polygon.io data, save_analysis_report\n""Disclaimer: Not financial advice. For informational purposes only."),
mcp_servers=[server],
tools=[save_analysis_report],
input_guardrails=[InputGuardrail(guardrail_function=finance_guardrail)],
model=OpenAIResponsesModel(model="gpt-5", openai_client=AsyncOpenAI()),
model_settings = ModelSettings(truncation="auto")
)
Guardrails
A guardrail is meant to confirm that a certain set of criteria have been met. This code gets ran first after an agent is triggered. In our case, we want to make sure any query put into the flow actually relates to finance. You'll notice we use a Pydanticoutput model with a boolean and reasoning for the true or false result.
The guardrail is essentially a tiny sub agent with its own specific instructions to follow. If the query isn't finance related, it will use a tripwire exception type.
classFinanceOutput(BaseModel):"""Structured result from the guardrail check.
""" is_about_finance: bool reasoning: str
guardrail_agent = Agent(
name="Guardrail check",
instructions=
"""Classify if the user query is finance-related.
Include: stocks, ETFs, crypto, forex, market news, fundamentals,
economic indicators, ROI calcs, corporate actions.
Exclude: non-financial topics (cooking, general trivia, unrelated tech).
Disambiguate: if term (e.g., Apple, Tesla) could be both, check for
finance context words (price, market, earnings, shares). If unclear,
return non-finance.
Output: is_about_finance: bool, reasoning: brief why/why not.""",
output_type=FinanceOutput,
)
asyncdeffinance_guardrail(context, agent, input_data):"""Validate that the prompt is finance-related before running the
agent.
""" result = await Runner.run(guardrail_agent, input_data,
context=context)
final_output = result.final_output_as(FinanceOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not final_output.is_about_finance,
)
Sessions
In to maintain memory in a longer conversation, we use a session. You can persist this or reset it during a chat. For this demo, it resets after each run of the application.
session = SQLiteSession("finance_conversation")
Tools
There are two ways to create and use tools for an agent. One is to connect to a MCP (model context protocol) server. The other is to define custom tools. In this demo, we do both.
The MCP server for Polygon.io provides access to our entire suite of API endpoints. You just need an API key. Note that while you have access to all the endpoints, you will need to appropriate license tier attached your API key.
This code sets up the MCP server for you without having to run it separately.
defcreate_polygon_mcp_server():"""Create a stdio MCP server instance configured with POLYGON_API_KEY.
""" api_key = os.getenv("POLYGON_API_KEY")
ifnot api_key:
raise Exception("POLYGON_API_KEY not set in environment.")
return MCPServerStdio(params={
"command": "uvx",
"args": ["--from", "git+https://github.com/polygon-
io/mcp_polygon@v0.4.0", "mcp_polygon"],
"env": {**os.environ, "POLYGON_API_KEY": api_key}
})
Sometimes, you also need to define custom tools. You do this with an
function_tool
marker at the top of the code block. The below tool allows our agent to write and save reports to the machine's file system.
This demo is a simple one file demonstration to showcase the art of the possible. There are several enhancements that could be made.
Multi-agent handoffs: Delegate to specialized agents (news, fundamentals, technicals) for better results.
LLM context clearing between topic changes
Stronger guardrails
Report output models using Pydantic
Config and limits: YAML/ENV config for model, date-range caps, per-tool rate limits, and retries.
Wrap-up
Running stock market analysis shouldn't be hard. Polygon.io's MCP server, alongside OpenAI's GPT-5 and Agent SDK, make it easy peasy.
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 Demo. 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.
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.
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.