stock_market_mcp
๐ง stock_market_mcp
FoodForBrains ยท Feeding your brain the data it needs to decide.
A Model Context Protocol (MCP) server that analyzes stocks and returns a scored BUY / HOLD / SELL assessment, so you can ask your AI client "which stocks should I look at?" and get data-backed answers.
Works for the Indian market (NSE/BSE) and US market out of the box.
๐ Full documentation: the wiki โ setup, tools reference, architecture, backtesting and FAQ.
APIs used
API | Purpose | Key needed? |
Yahoo Finance (via | Quotes, price history, fundamentals, news โ the primary data source for all analysis tools | No (free) |
Alpha Vantage (optional) | Extra company-overview data ( | Yes โ free key at https://www.alphavantage.co/support/#api-key |
Alpha Vantage free-tier notes (verified live): the free key is rate-limited to ~25 requests/day, 1 request/sec โ exceeding it returns an "Information" notice instead of data. Also, Alpha Vantage's
OVERVIEWendpoint works for US symbols (e.g.AAPLโ) but returns empty data for NSE/BSE symbols (RELIANCE.BSEโ) โ Indian-market coverage comes entirely from Yahoo Finance, which is why Yahoo is the primary source.
Tools
Tool | What it does |
| Current price + day change for a symbol |
| SMA 20/50/200, RSI-14, MACD + signal, 52-week range, daily volatility |
| Full technical + fundamental analysis โ 0โ100 score, BUY/HOLD/SELL, with reasons |
| Analyze & rank up to 15 symbols (defaults to NSE large caps) |
| Side-by-side P/E, margins, ROE, debt/equity, dividend yield, 1-year return |
| Index snapshot โ India (NIFTY 50) or US (S&P 500) |
| Recent news headlines for a symbol |
| Optional Alpha Vantage company overview (needs API key) |
| Record a BUY/HOLD/SELL decision + rationale + price in the decision journal |
| Review logged decisions vs current prices (return since, outcome verdict) |
| Three separate grounded reports (fundamentals / technical / sentiment) for one symbol |
Prompts
Prompt | What it does |
| TradingAgents-style structured workflow: gather grounded reports โ bull case โ bear case โ risk check โ decision โ log it. (Inspired by TauricResearch/TradingAgents, adapted for NSE/BSE.) |
Decision journal
Every log_decision call is stored in MongoDB (stock_data.decision_journal, configurable via MONGODB_URI/MONGODB_DB_NAME). If MongoDB is unreachable, the journal automatically falls back to a local decision_journal.json. review_decisions closes the loop: it prices each open decision and marks the outcome CORRECT / WRONG / NEUTRAL โ so recommendations are measured, not forgotten.
Grounded data snapshots
analyze_stock and analyst_reports embed a timestamped data_snapshot โ every indicator value the score is computed from, with its source. Follows the TradingAgents principle that analysis claims must trace to a verified data snapshot, never LLM memory.
Symbol formats
Market | Format | Example |
NSE (India) |
|
|
BSE (India) |
|
|
US | plain ticker |
|
Setup
Prerequisites
Python 3.10+ (tested on 3.13)
pip
An MCP client (ZCode, Claude Desktop, or any MCP-compatible client)
(Optional) Alpha Vantage API key
1. Get the code
git clone https://github.com/AnupamSinha/stock_market_mcp.git
cd stock_market_mcp2. Install dependencies
pip install -r requirements.txtThis installs mcp (the MCP SDK) and yfinance.
macOS note: if HTTPS calls fail with an SSL certificate error, run
pip install certifi. The server already usescertifiautomatically when present.
3. Configure the Alpha Vantage key (optional)
Create a .env file in the project root (or export an env var). The server loads .env automatically at startup โ existing environment variables take precedence:
# .env
ALPHA_VANTAGE_API_KEY=your_key_here
ALPHA_VANTAGE_BASE_URL=https://www.alphavantage.co/queryEnv var | Default | Description |
| (empty) | Alpha Vantage key; empty disables only the |
|
| Alpha Vantage endpoint |
All other tools work with no configuration at all.
Run
python3 server.pyThe server runs on stdio โ it's not a web server; an MCP client launches it and talks to it over stdin/stdout. You normally don't run it by hand; the client config below does it for you.
Configure your MCP client
ZCode
Add to ~/.zcode/cli/config.json (user scope โ available in every workspace):
{
"mcp": {
"servers": {
"stock_market_mcp": {
"command": "python3",
"args": ["/absolute/path/to/stock_market_mcp/server.py"]
}
}
}
}Restart ZCode (or start a new session) โ the tools appear as mcp__stock_market_mcp__* and connect automatically.
Claude Desktop
Edit the config file:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"stock_market_mcp": {
"command": "python3",
"args": ["/absolute/path/to/stock_market_mcp/server.py"]
}
}
}Restart Claude Desktop and start a new conversation โ the tools icon (hammer) should show the stock tools.
Use absolute paths in both configs. If
python3isn't found, use the full path (which python3to find it).
Verify it works
Run an end-to-end test with a real MCP client handshake:
python3 - <<'EOF'
import asyncio, json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
params = StdioServerParameters(command="python3", args=["server.py"])
async with stdio_client(params) as (r, w):
async with ClientSession(r, w) as s:
await s.initialize()
tools = await s.list_tools()
print("TOOLS:", [t.name for t in tools.tools])
res = await s.call_tool("analyze_watchlist", {"symbols": "RELIANCE.NS,ITC.NS"})
print(json.loads(res.content[0].text)["ranked"])
asyncio.run(main())
EOFExpected output: the 8 tool names and a ranked list with scores and recommendations.
Example prompts (once connected)
"Analyze my watchlist and tell me which stocks to consider buying"
"Do a technical analysis of TCS.NS"
"Compare RELIANCE.NS, HDFCBANK.NS and INFY.NS"
"What's the latest news on INFY.NS?"
"Analyze AAPL and MSFT and tell me which looks better"
Troubleshooting
Symptom | Fix |
Tools don't appear in the client | Start a new conversation/session; check the absolute path to |
|
|
SSL / |
|
Alpha Vantage returns an "Information" message | Free-tier rate limit hit (~25 req/day) โ wait, or rely on the Yahoo-based tools |
| Check |
Empty result for an NSE symbol from | Known: Alpha Vantage no longer serves Indian fundamentals โ use |
| Yahoo throttles bursts; retry after a short pause |
Project structure
stock_market_mcp/
โโโ server.py # The MCP server (FastMCP, stdio transport)
โโโ backtest.py # Backtest harness for the scoring rules (5y NSE, monthly)
โโโ requirements.txt # mcp, yfinance
โโโ .env # Optional: ALPHA_VANTAGE_API_KEY (never committed)
โโโ decision_journal.json # Journal fallback when MongoDB is down (never committed)
โโโ .gitignore
โโโ README.mdBacktesting
backtest.py replays the technical half of the scoring rules over ~5 years of
NIFTY-100 price history, month by month, and measures forward 1/3/6/12-month
returns by score bucket and quintile against the NIFTY 50 benchmark:
python3 backtest.pyFindings so far (see the script header for limitations): the technical score has modest short-horizon (1โ3 month) ranking power; BUY and HOLD levels are indistinguishable at longer horizons; the SELL cutoff never triggers on the technical-only score. Treat the scoring weights as tunable, not settled.
Acknowledgements
The multi-agent workflow shape โ grounded analyst reports, bull-vs-bear debate, risk check, decision journal with outcome review โ is inspired by TauricResearch/TradingAgents (Apache-2.0), re-implemented here as a lightweight, India-focused (NSE/BSE) MCP server. Thanks to the TradingAgents team for open-sourcing the ideas.
About FoodForBrains
FoodForBrains builds tools that make market information digestible โ analysis you can actually reason about, with every number traceable to its source. This project is part of that mission: grounded data in, transparent reasoning out.
Disclaimer
All output is educational analysis generated from public market data โ it is not financial advice. The BUY/HOLD/SELL scores are a screening aid based on simple technical and fundamental rules; do your own research and consult a financial advisor before investing.
License
MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/AnupamSinha/stock_market_mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server