Claude Tools

Custom MCP Servers for Claude: Real-Time Stock Trading Signals

Empower Claude AI with live stock data via a custom MCP server to generate real-time trading signals. This guide provides Python code, setup, and deployment for actionable alerts in seconds.

A

Andrew Snyder

AI & Automation Editor

December 21, 2025 min read
Share:

Introduction

In the fast-paced world of stock trading, timely data is everything. Imagine Claude AI, powered by Anthropic's advanced models like Opus, Sonnet, or Haiku, analyzing live market feeds to deliver precise trading signals—buy, sell, or hold recommendations with confidence scores. This is made possible through Model Context Protocol (MCP) servers, lightweight HTTP services that extend Claude's tool-using capabilities by providing real-time context without bloating prompts.

Traditional prompting with static data lags behind market movements, but MCP servers enable dynamic, low-latency data pulls. In this tutorial, we'll build a Python-based MCP server using FastAPI to fetch live stock quotes via yfinance, integrate it with Claude's API, and deploy it for production use. By the end, you'll have a system generating actionable alerts like "AAPL: Buy at $220.50 (RSI oversold, momentum up 2%)."

We'll compare MCP approaches to direct API calls, highlighting why MCP shines for trading workflows.

What is Model Context Protocol (MCP)?

MCP is an open protocol for serving structured context to Claude models. It defines standardized HTTP endpoints that Claude's tool-use feature can invoke seamlessly. Unlike generic APIs, MCP servers are optimized for AI consumption:

  • Endpoints: /context/{type} for data retrieval (e.g., stocks).
  • Responses: JSON schemas matching Claude's tool definitions.
  • Authentication: Optional API keys for security.
  • Streaming: Support for SSE (Server-Sent Events) in advanced setups.

MCP extends Claude's native tools (like computer use or web search) by letting you host custom data pipelines. For developers, it's plug-and-play with the Anthropic SDK.

Why MCP for Real-Time Trading Signals?

Stock markets move in seconds—delayed data means missed opportunities. MCP servers solve this:

  • Real-Time Access: Poll APIs like yfinance or Alpha Vantage on-demand.
  • Scalability: Handle multiple symbols without prompt token limits.
  • Claude Synergy: Opus excels at technical analysis (e.g., RSI, MACD); Haiku for speed.
  • Alerts: Claude generates human-readable signals with risk assessments.

Real-World Impact: A sales team could monitor portfolios; traders automate Discord/Slack bots.

Comparison: MCP Servers vs. Traditional API Integration

AspectMCP ServersDirect API Calls in Prompts
Latency<500ms (server-side caching)2-10s (per prompt rebuild)
Token EfficiencyData fetched on-needFull data in every prompt
ScalabilityHandles 1000s queries/minPrompt size limits (200k tokens)
CustomizationCustom logic (e.g., filters)Basic JSON parsing
Claude FitNative tool useManual extraction
CostFree (yfinance) + hosting (~$5/mo)Higher API tokens

MCP wins for iterative analysis, where Claude calls tools multiple times (e.g., fetch data → analyze → confirm trend).

Prerequisites

  • Python 3.10+
  • Anthropic API key (free tier available)
  • yfinance library (delayed data; upgrade to Polygon.io for true real-time)
  • Docker for deployment

Install basics:

pip install fastapi uvicorn yfinance anthropic python-dotenv

Step 1: Data Source Setup

We'll use yfinance for free stock data (15-min delay). For production, get a free Alpha Vantage key.

Test it:

import yfinance as yf
ticker = yf.Ticker("AAPL")
info = ticker.info
print(f"AAPL Price: ${info['regularMarketPrice']:.2f}")

Key fields: regularMarketPrice, fiftyDayAverage, rsi (via history).

Step 2: Building the MCP Server

Create mcp_server.py with FastAPI. Expose /stocks/{symbol} for quotes and technicals.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import yfinance as yf
import os
from dotenv import load_dotenv

load_dotenv()
app = FastAPI(title="Claude MCP Stock Server")

class StockData(BaseModel):
    symbol: str
    price: float
    change_pct: float
    volume: int
    rsi: float = None
    recommendation: str = "HOLD"

@app.get("/mcp/stocks/{symbol}", response_model=StockData)
async def get_stock_data(symbol: str):
    try:
        ticker = yf.Ticker(symbol.upper())
        info = ticker.info
        hist = ticker.history(period="1mo")
        rsi = None  # Simplified; implement TA-Lib for full RSI
        if not hist.empty:
            # Basic momentum proxy
            rsi = 50 + (hist['Close'].pct_change().mean() * 100)  # Placeholder
        
        data = StockData(
            symbol=symbol.upper(),
            price=info.get('regularMarketPrice', 0),
            change_pct=info.get('regularMarketChangePercent', 0),
            volume=info.get('regularMarketVolume', 0),
            rsi=rsi
        )
        return data
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Run: uvicorn mcp_server:app --reload. Test: curl http://localhost:8000/mcp/stocks/AAPL.

Enhancements: Add caching with Redis, WebSockets for streams.

Step 3: Integrating with Claude API

Define the tool matching the MCP endpoint. Use Anthropic SDK.

import anthropic

client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

tools = [
    {
        "name": "get_stock_data",
        "description": "Fetch real-time stock data for trading analysis.",
        "input_schema": {
            "type": "object",
            "properties": {
                "symbol": {"type": "string", "description": "Stock ticker e.g. AAPL"}
            },
            "required": ["symbol"]
        }
    }
]

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    tools=tools,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Analyze AAPL for trading signals. Use live data. Output: Symbol, Action (BUY/SELL/HOLD), Price, Reason, Confidence (0-100)."
            }
        ]
    }],
    tool_choice="auto"
)

# Claude calls tool; you handle in loop
print(message.content)

Tool Handler: In production, proxy requests to your MCP server.

def handle_tool(tool_call):
    if tool_call.name == "get_stock_data":
        symbol = tool_call.input["symbol"]
        resp = requests.get(f"http://your-mcp-server/mcp/stocks/{symbol}")
        return {"tool_use_id": tool_call.id, "content": resp.json()}

Step 4: Sample Claude Prompts for Signals

Beginner Prompt (Haiku):

"Using the stock data tool, check NVDA. If RSI <30 and price > 50DMA, BUY. Else HOLD."

Advanced Prompt (Opus):

"Fetch data for SPY, QQQ, AAPL. Compute portfolio beta. Recommend allocation shift based on VIX proxy (change_pct). Risk: max 2% drawdown."

Output Example:

  • AAPL: BUY @ $225.12 | RSI: 28 (oversold) | Momentum: +1.8% | Confidence: 85

Step 5: Local Testing

  1. Start MCP server.
  2. Run Claude script.
  3. Observe tool calls → data fetch → signal.

Word of Caution: Not financial advice. Backtest signals; paper trade first.

Step 6: Deployment

Dockerfile:

FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["uvicorn", "mcp_server:app", "--host", "0.0.0.0", "--port", "$PORT"]

requirements.txt:

fastapi
uvicorn
yfinance
pydantic
dotenv

Build/deploy to Railway.app (free tier):

docker build -t mcp-stock .
docker run -p 8000:8000 -e PORT=8000 mcp-stock

For Heroku/Vercel, use Procfile: web: uvicorn mcp_server:app.

Secure with API keys: Add /mcp/stocks/{symbol}?key={yourkey}.

Advanced Features and Comparisons

  • Model Comparison:

    ModelSpeedAnalysis DepthTrading Fit
    HaikuFastestBasic signalsAlerts
    SonnetBalancedTA indicatorsDay trading
    OpusSlowestML forecastsPortfolios
  • True Real-Time: Swap yfinance for Polygon.io WebSockets.

import websocket  # Add streaming endpoint
  • Agents: Chain with Claude Code CLI for backtesting.

  • Integrations: n8n webhook → MCP → Claude → Slack alert.

Monitoring and Scaling

Use Prometheus for metrics. Scale with Kubernetes for high-volume trading desks.

Conclusion

Your custom MCP server transforms Claude into a trading co-pilot. Start local, deploy, iterate. Experiment with crypto (add Binance API) or forex. Join Claude Directory forums for MCP templates.

Total Words: ~1450. Questions? Comment below.

The #1 Newsletter in AI

Stay ahead of the AI curve

The most important updates, news, and content — delivered in one weekly newsletter.

No spam. Unsubscribe anytime. Privacy policy

MCP Servers
Claude Tools
Trading Signals
Real-Time Data
Python
ai-agents
A

About Andrew Snyder

AI & Automation Editor

Andrew covers practical AI automation, workflow design, and the tools teams use to streamline everyday operations.

Comments (0)