金融数据服务

MCP Finance Server是一款提供全面金融数据访问的服务,通过Yahoo Finance API集成智能缓存和市场数据覆盖,适用于金融分析、投资决策和量化交易。

  • by locupleto
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 locupleto/mcp-finance

使用说明

MCP Finance Server

A Model Context Protocol (MCP) server providing comprehensive financial data access via Yahoo Finance (yfinance). Designed for Claude Code integration with intelligent caching and extensive market data coverage.

Features

  • 15 Financial Data Tools covering company fundamentals, historical prices, analyst data, and options
  • Smart Caching with TTL-based expiry (1hr/4hr/24hr based on data volatility)
  • International Market Support with exchange suffix handling
  • Comprehensive Coverage: Price history, fundamentals, analyst data, options, news, holders, ESG
  • Production-Ready: Full error handling, type safety, and extensive testing

Quick Start

Installation

# Clone or navigate to the project
cd /Volumes/Work/development/projects/git/mcp-finance

# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Run tests
python test_server.py

Configuration for Claude Code

Add to Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "finance": {
      "command": "/Volumes/Work/development/projects/git/mcp-finance/venv/bin/python3",
      "args": [
        "/Volumes/Work/development/projects/git/mcp-finance/finance_mcp_server.py"
      ]
    }
  }
}

Available Tools

Company Information (3 tools)

get_company_info

Get comprehensive company data including sector, industry, description, key metrics (P/E, market cap, dividend yield), financial metrics (profit margins, ROE, debt ratio), and contact information.

Parameters:

  • symbol (required): Stock ticker (e.g., "AAPL")
  • exchange_suffix (optional): Exchange suffix for international stocks (e.g., "L" for London)

Cache TTL: 24 hours

get_fast_info

Quick-access metrics including current price, market cap, PE ratio. Faster alternative to get_company_info for basic data.

Cache TTL: 1 hour

Historical Data (2 tools)

get_price_history

Get historical OHLCV (Open, High, Low, Close, Volume) price data.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • period (optional): "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max" (default: "1mo")
  • interval (optional): "1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo" (default: "1d")
  • actions (optional): Include dividends/splits (default: true)

Cache TTL: 1 hour

Example:

# Get 6 months of daily data for Apple
get_price_history(symbol="AAPL", period="6mo", interval="1d")

get_actions

Get dividend and stock split history.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • action_type (optional): "all", "dividends", "splits" (default: "all")

Cache TTL: 4 hours

Financial Statements (4 tools)

get_income_statement

Get income statement (P&L) showing revenue, expenses, and net income.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • quarterly (optional): Get quarterly instead of annual data (default: false)

Cache TTL: 24 hours

get_balance_sheet

Get balance sheet showing assets, liabilities, and equity.

Cache TTL: 24 hours

get_cash_flow

Get cash flow statement showing operating, investing, and financing cash flows.

Cache TTL: 24 hours

get_earnings

Get earnings per share (EPS) history.

Cache TTL: 4 hours

Analyst & Market Data (3 tools)

get_analyst_price_targets

Get analyst consensus price targets including current price, low/high/mean/median targets.

Cache TTL: 4 hours

get_recommendations

Get historical analyst recommendations showing rating changes over time.

Cache TTL: 4 hours

get_calendar

Get financial calendar with upcoming events including earnings dates, dividend dates, and estimates.

Cache TTL: 4 hours

Ownership & ESG (3 tools)

get_holders

Get institutional and major shareholder information.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • holder_type (optional): "all", "institutional", "major", "mutualfund" (default: "all")

Cache TTL: 24 hours

get_sustainability

Get ESG (Environmental, Social, Governance) scores ranging from 0-100.

Cache TTL: 24 hours

get_news

Get latest news articles related to the stock.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • limit (optional): Number of news items (default: 10)

Cache TTL: 1 hour

Options (1 tool)

get_options_data

Get options chain data for calls and/or puts.

Parameters:

  • symbol (required)
  • exchange_suffix (optional)
  • expiration_date (optional): Date in YYYY-MM-DD format (uses nearest if not specified)
  • option_type (optional): "both", "calls", "puts" (default: "both")

Cache TTL: 1 hour

International Symbols

For stocks outside the US, append the exchange suffix:

  • US stocks: Just ticker (e.g., AAPL)
  • International: symbol.exchange (e.g., HSBA.L for HSBC London)

Common Exchange Suffixes

  • .L - London Stock Exchange
  • .TO - Toronto Stock Exchange
  • .PA - Euronext Paris
  • .F or .DE - Frankfurt/XETRA
  • .T - Tokyo Stock Exchange
  • .HK - Hong Kong Stock Exchange
  • .AX - Australian Securities Exchange

Caching Strategy

The server implements intelligent caching with TTL-based expiry:

  • 1 hour (3600s): Price data, intraday quotes, news, options
  • 4 hours (14400s): Analyst data, recommendations, estimates, earnings calendar
  • 24 hours (86400s): Company info, financials, ESG, ownership

Repeated queries within the cache window return instantly without hitting the API.

Development

Project Structure

mcp-finance/
├── finance_mcp_server.py   # Main MCP server implementation
├── test_server.py           # Comprehensive test suite
├── requirements.txt         # Python dependencies
├── README.md                # This file
├── CLAUDE.md                # Claude Code usage guide
├── .gitignore               # Git ignore patterns
└── venv/                    # Virtual environment

Running Tests

source venv/bin/activate
python test_server.py

Tests cover:

  • Company information retrieval
  • Price history with different periods/intervals
  • Financial statements (income, balance, cash flow)
  • Analyst data (price targets, recommendations)
  • Options chains
  • Cache performance
  • International symbol handling
  • Error handling

Dependencies

  • mcp >= 1.9.2 - Model Context Protocol SDK
  • yfinance >= 0.2.66 - Yahoo Finance data access
  • pandas >= 2.0.0 - Data manipulation
  • aiohttp >= 3.9.0 - Async HTTP (performance)

Known Limitations

  1. Yahoo Finance Rate Limits: No official rate limit, but aggressive requests may be throttled (mitigated by caching)
  2. Data Availability: Not all symbols have all data types (e.g., ESG for small caps)
  3. International Symbols: Some require specific exchange suffix formatting
  4. Historical Data Depth: Free tier may have limited depth for some symbols
  5. Intraday Data: Limited to recent periods (typically 60 days for minute-level data)

Troubleshooting

Server Not Appearing in Claude

  1. Check config file syntax:

    cat ~/Library/Application\ Support/Claude/claude_desktop_config.json
    
  2. Verify paths are absolute

  3. Restart Claude Desktop

Tool Errors

  1. Check yfinance is working:

    source venv/bin/activate
    python -c "import yfinance as yf; print(yf.Ticker('AAPL').info['longName'])"
    
  2. Run test suite:

    python test_server.py
    

Symbol Not Found

  • Verify symbol exists on Yahoo Finance: https://finance.yahoo.com
  • For international stocks, ensure correct exchange suffix
  • Try using get_fast_info instead of get_company_info for basic checks

Version Information

  • MCP SDK: 1.25.0
  • yfinance: 0.2.66
  • Python: 3.12+

License

MIT

Contributing

Issues and pull requests welcome! Please ensure:

  • All tests pass (python test_server.py)
  • New tools include test cases
  • Documentation updated for new features

Changelog

v1.0.0 (2025-12-19)

  • Initial release
  • 15 financial data tools
  • Smart caching system
  • International market support
  • Comprehensive test suite
  • Full Claude Code integration