finnhub-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

FinnHub API Integration

FinnHub API 集成

Complete integration with FinnHub's financial data API providing access to stocks, forex, crypto, company fundamentals, news, and real-time market data.
与FinnHub金融数据API的完整集成,可访问股票、外汇、加密货币、公司基本面、新闻及实时市场数据。

Quick Start

快速开始

Authentication

身份验证

bash
undefined
bash
undefined

Environment variable (recommended)

环境变量(推荐方式)

export FINNHUB_API_KEY="your_api_key"
export FINNHUB_API_KEY="your_api_key"

Or in .env file

或在.env文件中设置

FINNHUB_API_KEY=your_api_key
undefined
FINNHUB_API_KEY=your_api_key
undefined

Basic Usage (Python)

基础用法(Python)

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()
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:
    """获取标的的实时报价。"""
    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}%)")
undefined
quote = get_quote("AAPL") print(f"AAPL: ${quote['c']:.2f} ({quote['dp']:+.2f}%)")
undefined

Using Official SDK

使用官方SDK

python
import finnhub

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

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

Get quote

获取报价

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

Get company profile

获取公司概况

profile = client.company_profile2(symbol="AAPL")
profile = client.company_profile2(symbol="AAPL")

Get financials

获取财务数据

financials = client.company_basic_financials("AAPL", "all")
undefined
financials = client.company_basic_financials("AAPL", "all")
undefined

API Endpoints Reference

API端点参考

Stock Market Data

股票市场数据

EndpointDescriptionFree
/quote
Real-time quote
/stock/candle
Historical OHLCV
/stock/profile2
Company profile
/stock/peers
Similar companies
/company-news
Company news
/stock/metric
Basic financials
/stock/financials
Financial statements
/stock/insider-transactions
Insider trades⚠️ Premium
/stock/insider-sentiment
Insider sentiment⚠️ Premium
端点描述免费可用
/quote
实时报价
/stock/candle
历史OHLCV数据
/stock/profile2
公司概况
/stock/peers
同类公司
/company-news
公司新闻
/stock/metric
基础财务指标
/stock/financials
财务报表
/stock/insider-transactions
内幕交易⚠️ 付费版
/stock/insider-sentiment
内幕交易情绪⚠️ 付费版

Fundamental Data

基本面数据

EndpointDescriptionFree
/stock/financials-reported
SEC reported
/stock/earnings
Earnings history
/stock/recommendation
Analyst ratings
/stock/price-target
Price targets
/stock/revenue-estimate
Revenue estimates⚠️ Premium
/stock/eps-estimate
EPS estimates⚠️ Premium
端点描述免费可用
/stock/financials-reported
SEC申报数据
/stock/earnings
收益历史
/stock/recommendation
分析师评级
/stock/price-target
目标价
/stock/revenue-estimate
营收预期⚠️ 付费版
/stock/eps-estimate
EPS预期⚠️ 付费版

Forex & Crypto

外汇与加密货币

EndpointDescriptionFree
/forex/rates
Exchange rates
/forex/candle
Forex OHLCV
/crypto/candle
Crypto OHLCV
/crypto/exchanges
Crypto exchanges
/crypto/symbol
Crypto symbols
端点描述免费可用
/forex/rates
汇率
/forex/candle
外汇OHLCV数据
/crypto/candle
加密货币OHLCV数据
/crypto/exchanges
加密货币交易所
/crypto/symbol
加密货币标的

News & Sentiment

新闻与情绪

EndpointDescriptionFree
/company-news
Company news
/news
Market news
/press-releases
Press releases⚠️ Premium
/news-sentiment
News sentiment⚠️ Premium
端点描述免费可用
/company-news
公司新闻
/news
市场新闻
/press-releases
新闻稿⚠️ 付费版
/news-sentiment
新闻情绪⚠️ 付费版

Calendar Events

日历事件

EndpointDescriptionFree
/calendar/earnings
Earnings calendar
/calendar/ipo
IPO calendar
/stock/dividends
Dividend history
/stock/splits
Stock splits
端点描述免费可用
/calendar/earnings
收益日历
/calendar/ipo
IPO日历
/stock/dividends
分红历史
/stock/splits
股票拆分

Rate Limits

速率限制

TierCalls/MinuteNotes
Free60US stocks, forex, crypto
Paid300+Per-market pricing
Rate limit headers:
  • X-Ratelimit-Limit
    : Max calls per minute
  • X-Ratelimit-Remaining
    : Calls remaining
  • X-Ratelimit-Reset
    : Reset timestamp
套餐每分钟调用次数说明
免费版60美股、外汇、加密货币
付费版300+按市场定价
速率限制响应头:
  • X-Ratelimit-Limit
    : 每分钟最大调用次数
  • X-Ratelimit-Remaining
    : 剩余调用次数
  • X-Ratelimit-Reset
    : 重置时间戳

Common Tasks

常见任务

Task: Get Stock Quote with Change

任务:获取包含涨跌幅的股票报价

python
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")
    }
python
def get_stock_info(symbol: str) -> dict:
    """获取全面的股票信息。"""
    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")
    }

Task: Get Historical Candles

任务:获取历史K线数据

python
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()
python
import time

def get_candles(symbol: str, resolution: str = "D", days: int = 30) -> dict:
    """
    获取历史OHLCV数据。

    时间周期: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()

Task: Get Earnings Calendar

任务:获取收益日历

python
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", [])
python
def get_earnings_calendar(from_date: str, to_date: str) -> list:
    """获取即将发布的收益报告。"""
    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")
undefined
earnings = get_earnings_calendar("2025-12-05", "2025-12-12")
undefined

Task: Get Company News

任务:获取公司新闻

python
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()
python
def get_company_news(symbol: str, days: int = 7) -> list:
    """获取近期公司新闻。"""
    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()

Task: Get Financial Metrics

任务:获取财务指标

python
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")
    }
python
def get_financials(symbol: str) -> dict:
    """获取关键财务指标。"""
    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 Real-Time Data

WebSocket实时数据

python
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()
python
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):
    # 订阅标的
    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()

Error Handling

错误处理

python
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 {}
python
def safe_api_call(endpoint: str, params: dict) -> dict:
    """带错误处理的API调用。"""
    params["token"] = API_KEY

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

        # 检查速率限制
        remaining = response.headers.get("X-Ratelimit-Remaining")
        if remaining and int(remaining) < 5:
            print(f"警告:仅剩{remaining}次API调用额度")

        return response.json()

    except requests.exceptions.HTTPError as e:
        if response.status_code == 429:
            print("超出速率限制,等待60秒...")
            time.sleep(60)
            return safe_api_call(endpoint, params)
        raise
    except Exception as e:
        print(f"API错误:{e}")
        return {}

Free vs Premium Features

免费版与付费版功能对比

Free Tier Includes

免费版包含

  • Real-time US stock quotes
  • Historical data (1 year)
  • Company profiles & peers
  • Basic financials & metrics
  • Earnings calendar
  • Company news
  • Forex & crypto data
  • WebSocket (US stocks, forex, crypto)
  • 美股实时报价
  • 历史数据(1年)
  • 公司概况及同类公司
  • 基础财务数据及指标
  • 收益日历
  • 公司新闻
  • 外汇与加密货币数据
  • WebSocket(美股、外汇、加密货币)

Premium Required

需付费版

  • Insider transactions & sentiment
  • SEC filings
  • ESG scores
  • Patent data
  • Congressional trading
  • International markets
  • Revenue/EPS estimates
  • Lobbying data
  • Extended historical data
  • 内幕交易及情绪数据
  • SEC文件
  • ESG评分
  • 专利数据
  • 国会交易数据
  • 国际市场数据
  • 营收/EPS预期
  • 游说数据
  • 扩展历史数据

Best Practices

最佳实践

  1. Cache static data - Company profiles, metrics rarely change
  2. Use WebSocket - For real-time quotes instead of polling
  3. Batch where possible - Reduce API calls
  4. Handle rate limits - Implement exponential backoff
  5. Store API key securely - Use environment variables
  1. 缓存静态数据 - 公司概况、指标等数据很少变动
  2. 使用WebSocket - 获取实时报价时替代轮询方式
  3. 尽可能批量处理 - 减少API调用次数
  4. 处理速率限制 - 实现指数退避策略
  5. 安全存储API密钥 - 使用环境变量

Installation

安装

bash
undefined
bash
undefined

Python SDK

Python SDK

pip install finnhub-python
pip install finnhub-python

JavaScript SDK

JavaScript SDK

npm install finnhub
undefined
npm install finnhub
undefined

Related Skills

相关技能

  • twelvedata-api
    - Alternative market data source
  • alphavantage-api
    - Technical indicators focus
  • fmp-api
    - Fundamental analysis focus
  • twelvedata-api
    - 替代市场数据源
  • alphavantage-api
    - 专注技术指标
  • fmp-api
    - 专注基本面分析

References

参考资料