finnhub-api について
finnhub-api は、FinnHub の金融データを扱う開発者向けの統合ガイドです。株式、外国為替、暗号資産、企業情報、ニュース、リアルタイムデータを扱い、Python と JavaScript の SDK 利用例も示します。
主な機能
- 01株価と過去の価格データ
- 02企業基本情報と財務諸表
- 03外国為替と暗号資産データ
- 04市場ニュースとイベントカレンダー
- 05WebSocket によるリアルタイムデータ
活用シーン
- 01株価と過去のローソク足の確認
- 02企業指標とニュースの調査
- 03外国為替と暗号資産データの取得
- 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-reported | SEC 報告データ | ✅ |
/stock/earnings | 業績履歴 | ✅ |
/stock/recommendation | アナリスト評価 | ✅ |
/stock/price-target | 目標株価 | ✅ |
/stock/revenue-estimate | 売上高予測 | ⚠️ プレミアム |
/stock/eps-estimate | EPS 予測 | ⚠️ プレミアム |
外国為替と暗号資産
| エンドポイント | 説明 | 無料 |
|---|---|---|
/forex/rates | 為替レート | ✅ |
/forex/candle | 外国為替の OHLCV | ✅ |
/crypto/candle | 暗号資産の OHLCV | ✅ |
/crypto/exchanges | 暗号資産取引所 | ✅ |
/crypto/symbol | 暗号資産のシンボル | ✅ |
ニュースとセンチメント
| エンドポイント | 説明 | 無料 |
|---|---|---|
/company-news | 企業ニュース | ✅ |
/news | 市場ニュース | ✅ |
/press-releases | プレスリリース | ⚠️ プレミアム |
/news-sentiment | ニュースのセンチメント | ⚠️ プレミアム |
カレンダーイベント
| エンドポイント | 説明 | 無料 |
|---|---|---|
/calendar/earnings | 決算カレンダー | ✅ |
/calendar/ipo | IPO カレンダー | ✅ |
/stock/dividends | 配当履歴 | ✅ |
/stock/splits | 株式分割 | ✅ |
レート制限
| プラン | 呼び出し回数/分 | 備考 |
|---|---|---|
| 無料 | 60 | 米国株、外国為替、暗号資産 |
| 有料 | 300 以上 | 市場ごとの料金 |
レート制限ヘッダー:
X-Ratelimit-Limit:1 分あたりの最大呼び出し回数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 予測
- ロビー活動データ
- より長期間の過去データ
ベストプラクティス
- 静的データをキャッシュする - 企業プロフィールや指標はめったに変更されません
- WebSocket を使用する - ポーリングの代わりにリアルタイムの株価取得に使用します
- 可能な場合はバッチ処理する - API 呼び出しを減らします
- レート制限に対応する - 指数バックオフを実装します
- API キーを安全に保管する - 環境変数を使用します
インストール
# Python SDK
pip install finnhub-python
# JavaScript SDK
npm install finnhub
関連スキル
twelvedata-api- 代替の市場データソースalphavantage-api- テクニカル指標に特化fmp-api- ファンダメンタル分析に特化
参考資料
コメント
Markdown 対応