mcpField
F
finnhub-api

finnhub-api

github.com/adaptationio数据与数据库340 次安装
代码仓库

关于 finnhub-api

finnhub-api 是面向金融数据分析的 FinnHub API 集成指南,供需要获取市场与公司数据的开发者使用。内容涵盖股票、外汇、加密货币、新闻及实时数据,并说明 Python 与 JavaScript SDK 的使用。

主要功能

  1. 01股票报价与历史行情
  2. 02公司基本面与财务报表
  3. 03外汇和加密货币数据
  4. 04市场新闻与事件日历
  5. 05WebSocket 实时行情

适用场景

  1. 01查询股票报价和历史 K 线
  2. 02查看公司财务指标与新闻
  3. 03获取外汇及加密货币行情
  4. 04跟踪财报和 IPO 日历

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/adaptationio/skrillz --skill finnhub-api

安装后在 Claude Code 中输入/finnhub-api确认已加载。

附带文件references/ENDPOINTS.mdscripts/finnhub_client.py

详细介绍

FinnHub API 集成

全面集成 FinnHub 金融数据 API,可访问股票、外汇、加密货币、公司基本面、新闻和实时市场数据。

快速开始

身份验证
# Environment variable (recommended)
export FINNHUB_API_KEY="your_api_key"

# Or in .env file
FINNHUB_API_KEY=your_api_key
基本用法(Python)
import requests
import os

API_KEY = os.getenv("FINNHUB_API_KEY")
BASE_URL = "https://finnhub.io/api/v1"

def get_quote(symbol: str) -> dict:
    """Get real-time quote for a symbol."""
    response = requests.get(
        f"{BASE_URL}/quote",
        params={"symbol": symbol, "token": API_KEY}
    )
    return response.json()

# Example
quote = get_quote("AAPL")
print(f"AAPL: ${quote['c']:.2f} ({quote['dp']:+.2f}%)")
使用官方 SDK
import finnhub

client = finnhub.Client(api_key="your_api_key")

# Get quote
quote = client.quote("AAPL")

# Get company profile
profile = client.company_profile2(symbol="AAPL")

# Get financials
financials = client.company_basic_financials("AAPL", "all")

API 端点参考

股票市场数据
端点描述免费
/quote实时报价✅
/stock/candle历史 OHLCV✅
/stock/profile2公司简介✅
/stock/peers同类公司✅
/company-news公司新闻✅
/stock/metric基本财务数据✅
/stock/financials财务报表✅
/stock/insider-transactions内部人交易⚠️ 需高级版
/stock/insider-sentiment内部人情绪⚠️ 需高级版
基本面数据
端点描述免费
/stock/financials-reportedSEC 申报数据✅
/stock/earnings盈利历史✅
/stock/recommendation分析师评级✅
/stock/price-target目标价格✅
/stock/revenue-estimate营收预测⚠️ 需高级版
/stock/eps-estimateEPS 预测⚠️ 需高级版
外汇和加密货币
端点描述免费
/forex/rates汇率✅
/forex/candle外汇 OHLCV✅
/crypto/candle加密货币 OHLCV✅
/crypto/exchanges加密货币交易所✅
/crypto/symbol加密货币代码✅
新闻和情绪
端点描述免费
/company-news公司新闻✅
/news市场新闻✅
/press-releases新闻稿⚠️ 需高级版
/news-sentiment新闻情绪⚠️ 需高级版
日历事件
端点描述免费
/calendar/earnings盈利日历✅
/calendar/ipoIPO 日历✅
/stock/dividends股息历史✅
/stock/splits股票拆分✅

速率限制

层级每分钟调用次数备注
免费60美股、外汇、加密货币
付费300+按市场定价

速率限制响应头:

  • X-Ratelimit-Limit:每分钟最多调用次数
  • X-Ratelimit-Remaining:剩余调用次数
  • X-Ratelimit-Reset:重置时间戳

常见任务

任务:获取含涨跌幅的股票报价
def get_stock_info(symbol: str) -> dict:
    """Get comprehensive stock info."""
    quote = requests.get(
        f"{BASE_URL}/quote",
        params={"symbol": symbol, "token": API_KEY}
    ).json()

    profile = requests.get(
        f"{BASE_URL}/stock/profile2",
        params={"symbol": symbol, "token": API_KEY}
    ).json()

    return {
        "symbol": symbol,
        "name": profile.get("name"),
        "price": quote["c"],
        "change": quote["d"],
        "change_percent": quote["dp"],
        "high": quote["h"],
        "low": quote["l"],
        "market_cap": profile.get("marketCapitalization"),
        "industry": profile.get("finnhubIndustry")
    }
任务:获取历史蜡烛图数据
import time

def get_candles(symbol: str, resolution: str = "D", days: int = 30) -> dict:
    """
    Get historical OHLCV data.

    Resolutions: 1, 5, 15, 30, 60, D, W, M
    """
    end = int(time.time())
    start = end - (days * 24 * 60 * 60)

    response = requests.get(
        f"{BASE_URL}/stock/candle",
        params={
            "symbol": symbol,
            "resolution": resolution,
            "from": start,
            "to": end,
            "token": API_KEY
        }
    )
    return response.json()
任务:获取盈利日历
def get_earnings_calendar(from_date: str, to_date: str) -> list:
    """Get upcoming earnings releases."""
    response = requests.get(
        f"{BASE_URL}/calendar/earnings",
        params={
            "from": from_date,
            "to": to_date,
            "token": API_KEY
        }
    )
    return response.json().get("earningsCalendar", [])

# Example: Get next week's earnings
earnings = get_earnings_calendar("2025-12-05", "2025-12-12")
任务:获取公司新闻
def get_company_news(symbol: str, days: int = 7) -> list:
    """Get recent company news."""
    from datetime import datetime, timedelta

    end = datetime.now()
    start = end - timedelta(days=days)

    response = requests.get(
        f"{BASE_URL}/company-news",
        params={
            "symbol": symbol,
            "from": start.strftime("%Y-%m-%d"),
            "to": end.strftime("%Y-%m-%d"),
            "token": API_KEY
        }
    )
    return response.json()
任务:获取财务指标
def get_financials(symbol: str) -> dict:
    """Get key financial metrics."""
    response = requests.get(
        f"{BASE_URL}/stock/metric",
        params={
            "symbol": symbol,
            "metric": "all",
            "token": API_KEY
        }
    )
    data = response.json()

    metrics = data.get("metric", {})
    return {
        "pe_ratio": metrics.get("peBasicExclExtraTTM"),
        "pb_ratio": metrics.get("pbQuarterly"),
        "ps_ratio": metrics.get("psAnnual"),
        "roe": metrics.get("roeTTM"),
        "roa": metrics.get("roaTTM"),
        "debt_equity": metrics.get("totalDebt/totalEquityQuarterly"),
        "current_ratio": metrics.get("currentRatioQuarterly"),
        "gross_margin": metrics.get("grossMarginTTM"),
        "operating_margin": metrics.get("operatingMarginTTM"),
        "52w_high": metrics.get("52WeekHigh"),
        "52w_low": metrics.get("52WeekLow"),
        "beta": metrics.get("beta")
    }

WebSocket 实时数据

import websocket
import json

def on_message(ws, message):
    data = json.loads(message)
    if data["type"] == "trade":
        for trade in data["data"]:
            print(f"{trade['s']}: ${trade['p']:.2f} x {trade['v']}")

def on_open(ws):
    # Subscribe to symbols
    ws.send(json.dumps({"type": "subscribe", "symbol": "AAPL"}))
    ws.send(json.dumps({"type": "subscribe", "symbol": "MSFT"}))

ws = websocket.WebSocketApp(
    f"wss://ws.finnhub.io?token={API_KEY}",
    on_message=on_message,
    on_open=on_open
)
ws.run_forever()

错误处理

def safe_api_call(endpoint: str, params: dict) -> dict:
    """Make API call with error handling."""
    params["token"] = API_KEY

    try:
        response = requests.get(f"{BASE_URL}/{endpoint}", params=params)
        response.raise_for_status()

        # Check for rate limit
        remaining = response.headers.get("X-Ratelimit-Remaining")
        if remaining and int(remaining) < 5:
            print(f"Warning: Only {remaining} API calls remaining")

        return response.json()

    except requests.exceptions.HTTPError as e:
        if response.status_code == 429:
            print("Rate limit exceeded. Waiting 60 seconds...")
            time.sleep(60)
            return safe_api_call(endpoint, params)
        raise
    except Exception as e:
        print(f"API error: {e}")
        return {}

免费版与高级版功能

免费版包含
  • 美股实时报价
  • 历史数据(1 年)
  • 公司简介和同类公司
  • 基本财务数据和指标
  • 盈利日历
  • 公司新闻
  • 外汇和加密货币数据
  • WebSocket(美股、外汇、加密货币)
需高级版
  • 内部人交易和情绪
  • SEC 文件
  • ESG 评分
  • 专利数据
  • 国会议员交易
  • 国际市场
  • 营收/EPS 预测
  • 游说数据
  • 更长的历史数据

最佳实践

  1. 缓存静态数据 - 公司简介和指标很少变化
  2. 使用 WebSocket - 获取实时报价,而非轮询
  3. 尽可能批量处理 - 减少 API 调用
  4. 处理速率限制 - 实现指数退避
  5. 安全存储 API 密钥 - 使用环境变量

安装

# Python SDK
pip install finnhub-python

# JavaScript SDK
npm install finnhub

相关技能

  • twelvedata-api - 替代市场数据来源
  • alphavantage-api - 专注于技术指标
  • fmp-api - 专注于基本面分析

参考资料

评论

支持 Markdown