A financial analysis agent pulls live market data, crunches the numbers, and writes up the analysis for you. Instead of tabbing between Yahoo Finance, a spreadsheet, and ChatGPT, you build one system that does all three.
The agent uses yfinance for free market data (no API key), OpenAI for reasoning, and tool calling to glue them together. You ask “How does AAPL look compared to MSFT?” and the agent fetches prices, computes moving averages and RSI, then writes an actual analysis.
Fetching Market Data with yfinance
Start with the tools. Each tool is a plain Python function that the LLM can call by name.
| |
These functions return plain dicts. No classes, no abstractions. The LLM sees the output as JSON and reasons over it.
One thing to watch: yfinance returns numpy types (numpy.float64, numpy.int64) which json.dumps chokes on. We handle that shortly.
Building the Agent with Tool Calling
Wire the tools into OpenAI’s function calling using the tools parameter. Define the schemas, then build the agent loop.
| |
The loop is the core pattern. The LLM decides which tools to call (often multiple in one turn via parallel tool calling), you execute them, and feed results back as tool messages. The loop continues until the model responds with plain text instead of tool calls.
Notice tool_choice="auto" – this lets the model decide when it has enough data to stop fetching and start writing. For financial analysis, it typically makes 4-6 tool calls before producing the final report.
Adding Financial Calculations
The agent is smarter when it can compute technical indicators itself rather than asking the LLM to do math. Here’s the calculate_technical_indicators function referenced above.
| |
The RSI calculation uses the standard 14-period lookback. Values above 70 signal overbought, below 30 oversold. The agent sees these labels in the tool output and incorporates them into its analysis.
You can extend this pattern easily. Want Bollinger Bands? Add a tool. Want to compare PE ratios across a sector? Add a tool. The LLM figures out when to call what – you just need to give it good descriptions in the tool schema.
A few things to keep in mind for the calculations:
- SMA vs EMA: The 20-day SMA lags more than the EMA. The agent gets both so it can discuss crossover signals.
- Volatility: We annualize by multiplying daily std by the square root of 252 (trading days per year). This is standard but assumes normal distribution of returns, which stocks don’t perfectly follow.
- RSI edge case: If
avg_lossis zero (stock went up every day in the window), RSI is 100. Theif avg_loss != 0guard handles this.
Common Errors and Fixes
yfinance returns empty data for a valid ticker. This happens when the ticker got delisted or when Yahoo Finance is having issues. Always check hist.empty before running calculations.
| |
TypeError: Object of type float64 is not JSON serializable. This is the numpy serialization issue. The serialize_result function we wrote handles it, but you can also cast inline:
| |
Rate limiting from Yahoo Finance. If you hit yfinance hard with many tickers in quick succession, you’ll get HTTPError 429. Add a small delay between calls:
| |
Tool call arguments are invalid JSON. Rarely, the LLM generates malformed JSON in tool_call.function.arguments. Wrap the parse in a try/except:
| |
KeyError on financial statement fields. Not every company reports the same line items. yfinance returns whatever Yahoo Finance has, and the field names can vary. Always use .get() with a default:
| |
A production agent should also handle OpenAI API errors (rate limits, timeouts) with retries. The openai library raises openai.RateLimitError and openai.APITimeoutError which you can catch and retry with exponential backoff.
Related Guides
- How to Build a Tool-Calling Agent with Claude and MCP
- How to Build an API Testing Agent with LLMs and Requests
- How to Build a SQL Query Agent with LLMs and Tool Calling
- How to Build a Slack Bot Agent with LLMs and Bolt
- How to Build a Code Generation Agent with LLMs
- How to Build a Log Analysis Agent with LLMs and Regex Tools
- How to Build a Contract Analysis Agent with LLMs and PDF Parsing
- How to Build a Monitoring Agent with Prometheus Alerts and LLM Diagnosis
- How to Build a Customer Support Agent with RAG and Tool Calling
- How to Build a Document QA Agent with PDF Parsing and Tool Use