Skip to main content
Glama
market-data-mcp

market-data-mcp

market-data-mcp

An MCP server that gives LLM agents market data, technical indicators, strategy backtests and guarded paper trading.

CI License: MIT Python

What MCP is

The Model Context Protocol is an open standard that lets LLM applications (Claude Desktop, Claude Code, IDEs, custom agents) discover and call tools that external servers provide. This project is one such server. Any MCP client can connect to it over stdio or HTTP.

Related MCP server: trading-mcp-server

Overview

An agent that answers questions like "backtest a 20/50 moving-average crossover on AAPL and compare it with buy-and-hold" needs four things: clean price data, correct indicator math, a backtester without look-ahead bias, and strict limits on anything that can place an order. This server provides all four as typed MCP tools:

  • Backtests run on my event-driven trading-backtester engine. Orders fill at the next bar's open.

  • Indicators are implemented and unit-tested in this repository.

  • Data comes from a pluggable provider. The default is offline and synthetic, so the server works with no keys and no network.

  • Orders go only to Alpaca paper trading, behind three independent guards.

The server is built with the official MCP Python SDK (mcp 2.x). MCPServer is the 2.x name of the SDK's high-level server, which was called FastMCP in 1.x.

Tools

Tool

What it returns

get_quote(symbol)

Last daily close, previous close, change and change %

get_history(symbol, start, end, interval, max_rows)

Compact OHLCV rows [date, open, high, low, close, volume]. 1d, 1wk or 1mo bars. The row cap is enforced on the server.

compute_indicators(symbol, indicators, params, end, lookback)

Latest value of every output, plus the last N bars, for sma, ema, rsi, macd, bollinger and atr

run_backtest(symbol, strategy, params, start, end, cash, commission, slippage_bps, include_benchmark)

Backtest metrics (Sharpe, Sortino, CAGR, max drawdown and more), a trade summary, and buy-and-hold benchmark metrics

list_strategies()

Available strategies (sma, rsi, buyhold) with parameters and defaults

place_paper_order(symbol, side, qty, type, limit_price, confirm)

An Alpaca paper order, or a refusal that explains why and shows the exact order that would have been sent

How the tools are defined:

  • Parameters are typed with pydantic Field constraints, so clients receive a JSON Schema with descriptions, enums and bounds.

  • Results are pydantic models, so they arrive as structured content with an output schema.

  • Data provenance: every data result carries provider and synthetic, so the model can tell real prices from generated ones.

  • Extras:

    • a resource, strategies://list

    • a prompt template, analyze_symbol(symbol, start), which walks the model through quote, history, indicators and two backtests

Architecture

flowchart LR
    C[LLM client<br/>Claude Desktop / Claude Code /<br/>agent / MCP Inspector] <-->|MCP over stdio or<br/>streamable HTTP| S[market-data-mcp<br/>MCPServer + input validation]
    S --> P[MarketDataProvider + TTL cache<br/>synthetic / yfinance / Alpaca]
    S --> I[indicators.py<br/>SMA EMA RSI MACD BB ATR]
    S --> B[trading-backtester<br/>event-driven engine]
    S --> G[order guardrails]
    G --> A[AlpacaPaperBroker<br/>paper endpoint only]
    P --> I
    P --> B

server.py declares the MCP tools. Each tool is a thin wrapper around a plain function in tools.py, so the logic can be tested without MCP.

  • Validation: inputs are checked (symbol regex, date range, interval, row cap and parameter bounds) before any data is fetched. Invalid input comes back as an MCP tool error with a message the model can act on.

  • Providers: they return daily bars through one protocol, and a TTL cache sits in front of them.

  • Backtests: run_backtest fetches extra bars before start so indicators are warmed up, and trades only from start.

Quickstart (offline, no API keys)

The server depends on trading-backtester, which is pinned to its v1.0.0 git tag. In CI it installs normally. For a local checkout next to it:

git clone https://github.com/nirbhaybhirangi/trading-backtester.git
git clone https://github.com/nirbhaybhirangi/market-data-mcp.git && cd market-data-mcp
python -m venv .venv && source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e "../trading-backtester" && pip install -e ".[dev]" --no-deps && pip install "mcp>=2.3,<3" pydantic pytest ruff pre-commit alpaca-py
python examples/client_demo.py

Once the v1.0.0 tag is published, pip install -e ".[dev]" alone is enough, because it pulls trading-backtester from GitHub.

To run the server itself:

market-data-mcp                                         # stdio (default)
market-data-mcp --transport streamable-http --port 8000 # HTTP at http://127.0.0.1:8000/mcp
npx @modelcontextprotocol/inspector market-data-mcp     # browse and call tools in MCP Inspector

Connecting a client

Claude Code (project .mcp.json, or claude mcp add market-data -- market-data-mcp):

{
  "mcpServers": {
    "market-data": {
      "command": "market-data-mcp",
      "env": { "MARKET_DATA_PROVIDER": "synthetic" }
    }
  }
}

Claude Desktop (claude_desktop_config.json). Use the absolute path to the executable inside your virtual environment:

{
  "mcpServers": {
    "market-data": {
      "command": "/path/to/market-data-mcp/.venv/bin/market-data-mcp",
      "env": {
        "MARKET_DATA_PROVIDER": "yfinance",
        "MARKET_DATA_MCP_ALLOW_ORDERS": "false"
      }
    }
  }
}

On Windows the command is C:\\path\\to\\market-data-mcp\\.venv\\Scripts\\market-data-mcp.exe. For real prices, install the extra (pip install -e ".[yfinance]") and set MARKET_DATA_PROVIDER=yfinance.

Configuration

Variable

Default

Purpose

MARKET_DATA_PROVIDER

synthetic

synthetic (offline, generated), yfinance (extra) or alpaca (extra plus keys)

MARKET_DATA_MCP_CACHE_TTL

300

Seconds to cache provider responses

MARKET_DATA_MCP_MAX_ROWS

2000

Server-side cap on get_history rows. The hard limit is 5000.

MARKET_DATA_MCP_ALLOW_ORDERS

false

Orders are refused unless this is exactly true

MARKET_DATA_MCP_MAX_NOTIONAL

1000

Largest estimated order value in USD

ALPACA_API_KEY, ALPACA_SECRET_KEY

none

Alpaca paper keys, for the alpaca provider and place_paper_order

MARKET_DATA_MCP_LOG_LEVEL

INFO

Logs go to stderr, because stdout carries the MCP protocol

ANTHROPIC_API_KEY

none

Only for examples/claude_agent.py

The server also reads a local .env file (see .env.example). Variables that are already set take precedence.

Safety design for orders

place_paper_order is the only tool that changes anything, and each layer below is enforced in code:

  1. Paper only. Orders go through AlpacaPaperBroker from trading-backtester:

    • it builds TradingClient(paper=True) itself

    • it refuses any client whose base URL is not https://paper-api.alpaca.markets

    • it re-checks the URL before every order

    • there is no live-trading option anywhere in either project

  2. Operator switch. Unless the server process runs with MARKET_DATA_MCP_ALLOW_ORDERS=true, every order is refused. A model cannot change the server's environment.

  3. Explicit confirmation. The call must pass confirm=true. The tool description tells the model it may send that only after the user has approved the exact order.

  4. Notional cap. The estimated qty * price must not exceed MARKET_DATA_MCP_MAX_NOTIONAL. Limit orders are priced at the limit; market orders at the latest quote.

  5. No synthetic pricing. A market order is refused while the provider is synthetic, because generated prices must not size a real paper order.

  6. Input validation.

    • side: buy or sell

    • type: market or limit

    • quantity: whole shares from 1 to 100,000

    • limit price: required for limit orders and rejected for market orders

When the guards refuse an order, the result has status="refused". Every failed guard is listed in reasons, and would_submit shows the exact order, so the user can see what would have happened. Broker errors, such as missing keys or an order Alpaca rejects, come back as status="rejected".

Example output

These are real outputs of python examples/client_demo.py, which spawns the server over stdio with the MCP Python client, lists its tools and calls compute_indicators and run_backtest.

Offline run, synthetic provider (default). These numbers describe generated data, not AAPL:

Server exposes 6 tools:
  - get_quote: Latest daily price for a symbol: last close, previous close and percent change.
  - get_history: OHLCV bars between two dates as compact rows [date, open, high, low, close, volume].
  - compute_indicators: Technical indicators on daily bars: SMA, EMA, RSI, MACD, Bollinger Bands and ATR.
  - run_backtest: Backtest a strategy on daily bars with the event-driven trading-backtester engine.
  - list_strategies: Strategies available to run_backtest, with their parameters and defaults.
  - place_paper_order: Place an order on Alpaca PAPER trading (never a live account).

compute_indicators(AAPL, [rsi, macd, bollinger], end=2024-12-31)
  provider=synthetic synthetic=True as_of=2024-12-31
  rsi_14           51.53
  macd             -0.04
  macd_signal      -0.11
  macd_histogram   0.07
  bb_middle        25.95
  bb_upper         26.88
  bb_lower         25.01

run_backtest(AAPL, sma fast=20 slow=50, 2020-01-01..2024-12-31)
  bars=1305 trades=14 (wins 5)
  metric           SMA 20/50  buy & hold
  total_return       -20.12%     -68.58%
  cagr                -4.25%     -20.05%
  sharpe               -0.26       -0.89
  max_drawdown       -28.77%     -72.86%
  provider=synthetic synthetic=True SYNTHETIC data (seeded random walk), not real market prices

Real data: python examples/client_demo.py --provider yfinance. AAPL daily bars come from Yahoo Finance via yfinance (adjusted). Costs are 0.05% commission plus 2 bps slippage, with $100,000 starting cash and 95% allocation. The tool list is identical, so it is omitted:

compute_indicators(AAPL, [rsi, macd, bollinger], end=2024-12-31)
  provider=yfinance synthetic=False as_of=2024-12-31
  rsi_14           56.71
  macd             5.06
  macd_signal      5.53
  macd_histogram   -0.47
  bb_middle        247.82
  bb_upper         257.61
  bb_lower         238.03

run_backtest(AAPL, sma fast=20 slow=50, 2020-01-01..2024-12-31)
  bars=1258 trades=14 (wins 7)
  metric           SMA 20/50  buy & hold
  total_return        88.00%     232.66%
  cagr                13.49%      27.25%
  sharpe                0.70        0.94
  max_drawdown       -26.99%     -30.14%
  provider=yfinance synthetic=False

Backtest results do not predict future returns, and nothing here is investment advice.

Claude agent example (needs an API key)

examples/claude_agent.py spawns the server and converts its MCP tools with the Anthropic SDK's MCP helpers (async_mcp_tool). It then lets the SDK's tool runner (client.beta.messages.tool_runner, model claude-opus-5-5) answer a question such as "Backtest SMA 20/50 on AAPL for 2024 and compare it with buy-and-hold." The order tool is not given to the model.

pip install -e ".[agent]"
export ANTHROPIC_API_KEY=...
python examples/claude_agent.py "Backtest SMA 20/50 on AAPL for 2024 and compare it with buy-and-hold."

This example needs ANTHROPIC_API_KEY, and it was not run against the API while building this repository. Only --dry-run, which connects to the server and converts the five tools without calling the API, was verified.

Project structure

src/market_data_mcp/
  server.py          MCP tool/resource/prompt definitions, CLI (stdio / streamable HTTP)
  tools.py           tool logic as plain functions (tested directly), order guardrails
  schemas.py         pydantic output models
  indicators.py      SMA, EMA, RSI, MACD, Bollinger Bands, ATR
  validation.py      symbol regex, date ranges, intervals, resampling
  config.py          environment settings
  providers/         MarketDataProvider protocol, TTL cache, synthetic / yfinance / Alpaca
examples/            client_demo.py (stdio client), claude_agent.py (tool runner agent)
tests/               pytest suite

Testing

ruff check . && ruff format --check .
pytest -q

The tests run offline against the synthetic provider and cover:

  • indicator math against hand-computed values

  • every tool function called directly

  • validation and caching

  • in-process client-to-server MCP sessions via the SDK's in-memory transport (Client(server))

  • a stdio subprocess session (marked slow, but it still runs by default)

  • the order guardrails: refusal without the environment switch or confirmation, the notional cap, the synthetic-price refusal, and paper-only enforcement against a fake live client

Roadmap

  • Real-time quotes (Alpaca latest trade/quote endpoints) instead of the latest daily close.

  • Intraday intervals.

  • Position and account tools (read-only) and order status/cancel tools for the paper account.

  • More strategies exposed through trading-backtester, and walk-forward results as a tool.

  • Authentication for the HTTP transport, for use beyond localhost.

License

MIT. See LICENSE. Data fetched via yfinance is subject to Yahoo's terms of use, and data fetched from Alpaca is subject to Alpaca's terms.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants like Claude to run backtests, fetch market data, list strategies, and analyze trading algorithms via natural language.
      1,146
      GPL 3.0
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to backtest trading strategies described in plain English, providing access to market data, technical indicators, and comprehensive performance reports.
      13
      1
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to read cited stock news, earnings, and filings; screen stocks; run point-in-time backtests; check portfolios; and query a local dashboard across US, A-share, and Hong Kong markets.
      19 PyPI
      1
      MIT