financial-analyst
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@financial-analystcompare Apple and Microsoft YTD performance and plot it"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
AI Financial Analyst Agent
Autonomous multi-agent stock research and visualization engine powered by CrewAI, FastMCP, yfinance, and local open-weight LLMs (DeepSeek-R1 / Ollama).
1. Overview
Retrieving, analyzing, and visualizing stock market data usually requires manually writing Python scripts, juggling yfinance and matplotlib parameters, and debugging code execution.
The AI Financial Analyst Agent accepts natural language queries (such as "Show me Tesla's YTD performance" or "Compare Apple and Microsoft stocks for the past year") and autonomously:
Parses ticker symbols, timeframes, and actions into structured Pydantic schemas.
Generates clean, production-ready Python visualization scripts using
yfinanceandmatplotlib.Validates & executes the generated code in a sandboxed subprocess with strict timeouts and error handling.
Exposes the entire pipeline as standard MCP (Model Context Protocol) tools ready for Claude Desktop and Claude Code.
Related MCP server: Yahoo Finance MCP Server
2. Architecture
flowchart TD
User([User Prompt / MCP Client]) -->|Tool Call: analyze_stock| Server[FastMCP Server: server.py]
Server -->|Kickoff| Crew[CrewAI Pipeline: finance_crew.py]
subgraph CrewAI Sequential Process
A1[Agent 1: Stock Data Analyst] -->|Structured Query Analysis| A2[Agent 2: Senior Python Developer]
A2 -->|Draft Python Script| A3[Agent 3: Senior Code Execution Expert]
A3 -->|Review & Self-Correction Loop| A2
end
Crew -->|Raw Output| Sanitizer[Output Sanitizer: utils/sanitize.py]
Sanitizer -->|Strip <think> & Fences| Validator[AST Code Validator: utils/validate.py]
Validator -->|Clean Validated Script| Saver[Save Code: outputs/<ticker>_<timeframe>.py]
Saver -->|Subprocess Execution| Executor[Sandbox Executor: utils/executor.py]
Executor -->|Render Chart PNG| Output[outputs/<ticker>_<timeframe>.png]
Output -->|Result & Chart Path| UserAgent Roles
Agent | Role | Responsibility | Output |
Query Parser | Stock Data Analyst | Extracts ticker symbol(s), validates timeframes, determines action. |
|
Code Writer | Senior Python Developer | Writes self-contained Python scripts targeting | Python code string |
Code Executor | Code Execution Expert | Reviews code, ensures imports and file saving syntax are valid. | Working script |
3. Key Hardening Features
Output Sanitization Layer: DeepSeek-R1 reasoning models emit
<think>...</think>blocks and markdown fences.utils/sanitize.pystrips reasoning traces and extracts clean Python code before execution.AST Syntax Validation: All scripts are parsed via
ast.parse()prior to disk persistence or execution, preventing syntax errors and invalid f-strings.Subprocess Sandbox Execution: Replaced unsafe in-process
exec()with isolatedsubprocess.run([python, script], timeout=30, capture_output=True).Bounded Retry Loop: Agent delegation and re-generation are strictly bounded to a maximum of 3 attempts with human-readable error messages.
Multi-LLM Provider Support: Run blazing fast in the cloud with Groq (
llama-3.3-70b-versatileordeepseek-r1-distill-llama-70b), 100% free locally with Ollama (deepseek-r1:7b), or cloud OpenAI (gpt-4o) via.env.
4. Getting Started
Prerequisites
Python 3.12+
Ollama installed and running:
ollama pull deepseek-r1:7b ollama serve
Installation
Clone the repository and enter the directory:
git clone https://github.com/anshul/financial-analyst-agent.git cd "financial analysis"Create and activate a virtual environment:
python -m venv .venv # Windows PowerShell: .\.venv\Scripts\Activate.ps1 # macOS / Linux: source .venv/bin/activateInstall dependencies:
pip install -r requirements.txtConfigure environment variables:
cp .env.example .envEdit
.envif you wish to change the LLM provider, Ollama base URL, or logging level.
5. Usage
A. Running as an MCP Server (Claude Desktop / Claude Code)
Run the server over stdio transport:
python server.pyTo connect to Claude Desktop, add the server to your claude_desktop_config.json:
{
"mcpServers": {
"financial-analyst": {
"command": "C:\\Users\\anshu\\code\\financial analysis\\.venv\\Scripts\\python.exe",
"args": [
"C:\\Users\\anshu\\code\\financial analysis\\server.py"
],
"cwd": "C:\\Users\\anshu\\code\\financial analysis"
}
}
}Available MCP Tools
analyze_stock(query: str): Converts natural language financial requests into validated Python analysis scripts.save_code(code: str, filename: Optional[str] = None): Validates AST and saves script tooutputs/.run_code_and_show_plot(script_path: Optional[str] = None): Safely executes the script and produces the.pngchart.list_saved_analyses(): Lists all historical scripts and charts generated.
B. Running as a CLI Script
You can run the multi-agent crew directly:
python finance_crew.pyC. Running the Streamlit Web Application
Launch the interactive dashboard in your browser:
streamlit run app.pyThis starts a local web server (typically at http://localhost:8501) featuring natural language query input, real-time agent code generation, sandboxed chart execution, and a historical gallery of previous analyses.
6. Running Tests
The test suite includes 54 unit and integration tests covering sanitization, AST validation, subprocess execution, timeout handling, file persistence, MCP tools, and the Streamlit web app:
pytest -v7. Known Limitations & Roadmap
Indian Tickers (NSE/BSE): Yahoo Finance requires
.NSor.BOsuffixes (e.g.RELIANCE.NS). Future versions will support automatic suffix detection.Rate Limits: Intensive query bursts may be rate-limited by Yahoo Finance. A local SQLite/Parquet caching layer is planned.
Fundamentals Agent: A 4th agent pulling P/E, EPS, and market capitalization alongside price charts is planned for v1.1.
8. License
This project is licensed under the MIT License.
This server cannot be deployed
Maintenance
Related MCP Connectors
Real SEC, 13F, insider, congress & macro data your AI agent can cite. Hosted MCP, 24 tools.
Global stock research, ML forecasts, valuation signals, screeners & portfolio tracking in Claude
Hosted MCP for stocks, options, Greeks, brokers, order previews, alerts, and workflows.
MCP server exposing the Backtest360 engine API as tools for AI agents.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceExposes TradingView technical indicators and OHLCV data through MCP tools for Claude Desktop or any MCP-aware client.23-
- AlicenseNot gradedqualityAmaintenanceProvides real-time stock market data for Claude Desktop and MCP-compatible clients, enabling natural language queries for quotes, historical prices, company profiles, financial statements, analyst ratings, comparisons, news, options, holdings, dividends, estimates, symbol search, and market status.54118MIT
- AlicenseNot gradedqualityDmaintenanceMCP server for stock prices, historical data, FX rates, and ticker search, powered by yfinance with no API key required. Designed for Claude Desktop.1Apache 2.0
- AlicenseNot gradedqualityDmaintenanceProvides interactive stock charts and financial data tools using MCP Apps. Enables natural language queries for stock quotes, charts, financials, earnings, and market movers with a free FMP API key.2MIT