关于 fmp-api
fmp-api 是 Financial Modeling Prep 稳定版 API 的金融数据集成指南,适用于使用 Python 获取公司基本面与市场资料的开发者。内容涵盖财务报表、估值、SEC 文件、交易数据及日历,并说明免费与付费功能范围。
主要功能
- 01获取实时报价与历史价格
- 02查询财务报表、指标和比率
- 03读取 DCF 估值与公司资料
- 04访问 SEC 文件及持仓交易数据
- 05查询财报、IPO 与经济日历
适用场景
- 01分析公司的财务报表与估值
- 02查看股票价格和历史行情
- 03检索 SEC 文件及机构持仓资料
- 04跟踪财报发布与经济事件日程
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ adaptationio/ skrillz --skill fmp-api安装后在 Claude Code 中输入/fmp-api确认已加载。
附带文件references/ENDPOINTS.mdscripts/fmp_client.py
详细介绍
Financial Modeling Prep (FMP) API 集成
全面的金融数据 API,专注于基本面分析、SEC 文件、机构持仓(13F)、国会议员交易数据和预计算估值。
快速入门
身份验证
# Environment variable (recommended)
export FMP_API_KEY="your_api_key"
# Or in .env file
FMP_API_KEY=your_api_key
基本用法(Python)
import requests
import os
API_KEY = os.getenv("FMP_API_KEY")
BASE_URL = "https://financialmodelingprep.com/stable"
def get_quote(symbol: str) -> dict:
"""Get real-time quote for a symbol."""
response = requests.get(
f"{BASE_URL}/quote",
params={"symbol": symbol, "apikey": API_KEY}
)
data = response.json()
return data[0] if data else {}
# Example
quote = get_quote("AAPL")
print(f"AAPL: ${quote['price']:.2f} ({quote['changePercentage']:+.2f}%)")
重要:新版端点格式
FMP 已迁移至 /stable/ 端点。旧版 /api/v3/ 端点需要现有订阅。
# NEW format (use this)
BASE_URL = "https://financialmodelingprep.com/stable"
# OLD format (legacy only)
# BASE_URL = "https://financialmodelingprep.com/api/v3"
API 端点参考
股票报价与价格
| 端点 | 描述 | 免费 |
|---|---|---|
/quote | 实时报价 | ✅ |
/quote-short | 快速获取价格 | ✅ |
/historical-price-eod/full | 历史日终数据 | ✅ |
/historical-price-intraday | 日内价格 | ⚠️ 付费 |
/pre-post-market-quote | 延长交易时段报价 | ⚠️ 付费 |
财务报表
| 端点 | 描述 | 免费 |
|---|---|---|
/income-statement | 损益表 | ✅ |
/balance-sheet-statement | 资产负债表 | ✅ |
/cash-flow-statement | 现金流量表 | ✅ |
/income-statement-growth | 收入增长 | ✅ |
/key-metrics | 关键指标 | ✅ |
/financial-ratios | 财务比率 | ✅ |
/enterprise-values | 企业价值 | ✅ |
估值与分析
| 端点 | 描述 | 免费 |
|---|---|---|
/discounted-cash-flow | DCF 估值 | ✅ |
/historical-discounted-cash-flow | 历史 DCF | ✅ |
/rating | 公司评级 | ✅ |
/historical-rating | 评级历史 | ✅ |
/company-outlook | 公司完整数据 | ✅ |
机构与内部人士数据
| 端点 | 描述 | 免费 |
|---|---|---|
/institutional-holder | 机构持有人 | ⚠️ 付费 |
/mutual-fund-holder | 共同基金持有人 | ⚠️ 付费 |
/insider-trading | 内部人士交易 | ⚠️ 付费 |
/form-13f | 13F 文件 | ⚠️ 付费 |
/senate-trading | 参议院交易 | ⚠️ 付费 |
/house-trading | 众议院交易 | ⚠️ 付费 |
筛选与发现
| 端点 | 描述 | 免费 |
|---|---|---|
/stock-screener | 筛选股票 | ⚠️ 付费 |
/stock-grade | 股票评级 | ✅ |
/search | 搜索代码 | ✅ |
/search-name | 按名称搜索 | ✅ |
/profile | 公司简介 | ✅ |
日历与事件
| 端点 | 描述 | 免费 |
|---|---|---|
/earnings-calendar | 财报日期 | ✅ |
/ipo-calendar | IPO 日期 | ✅ |
/stock-dividend-calendar | 股息 | ✅ |
/stock-split-calendar | 股票拆分 | ✅ |
/economic-calendar | 经济事件 | ✅ |
SEC 文件
| 端点 | 描述 | 免费 |
|---|---|---|
/sec-filings | 所有 SEC 文件 | ✅ |
/rss-feed-sec-filings | SEC RSS 订阅源 | ✅ |
速率限制
| 套餐 | 每日调用次数 | 每分钟调用次数 | 价格 |
|---|---|---|---|
| 免费 | 250 | 不适用 | $0 |
| Starter | 不限 | 300 | $22/月 |
| Premium | 不限 | 750 | $59/月 |
| Ultimate | 不限 | 3,000 | $149/月 |
免费套餐限制:
- 约 100 个示例代码(AAPL、TSLA、AMZN 等)
- 仅提供日终数据
- 500MB 带宽(滚动 30 天)
常见任务
任务:获取财务报表
def get_financials(symbol: str, period: str = "annual") -> dict:
"""Get comprehensive financial statements."""
income = requests.get(
f"{BASE_URL}/income-statement",
params={"symbol": symbol, "period": period, "apikey": API_KEY}
).json()
balance = requests.get(
f"{BASE_URL}/balance-sheet-statement",
params={"symbol": symbol, "period": period, "apikey": API_KEY}
).json()
cashflow = requests.get(
f"{BASE_URL}/cash-flow-statement",
params={"symbol": symbol, "period": period, "apikey": API_KEY}
).json()
return {
"income_statement": income[0] if income else {},
"balance_sheet": balance[0] if balance else {},
"cash_flow": cashflow[0] if cashflow else {}
}
# Example
financials = get_financials("AAPL")
print(f"Revenue: ${financials['income_statement'].get('revenue', 0):,.0f}")
任务:获取关键指标与比率
def get_key_metrics(symbol: str) -> dict:
"""Get important financial metrics."""
metrics = requests.get(
f"{BASE_URL}/key-metrics",
params={"symbol": symbol, "period": "annual", "apikey": API_KEY}
).json()
ratios = requests.get(
f"{BASE_URL}/financial-ratios",
params={"symbol": symbol, "period": "annual", "apikey": API_KEY}
).json()
latest_metrics = metrics[0] if metrics else {}
latest_ratios = ratios[0] if ratios else {}
return {
"market_cap": latest_metrics.get("marketCap"),
"pe_ratio": latest_ratios.get("priceEarningsRatio"),
"pb_ratio": latest_ratios.get("priceToBookRatio"),
"roe": latest_ratios.get("returnOnEquity"),
"roa": latest_ratios.get("returnOnAssets"),
"debt_equity": latest_ratios.get("debtEquityRatio"),
"current_ratio": latest_ratios.get("currentRatio"),
"gross_margin": latest_ratios.get("grossProfitMargin"),
"operating_margin": latest_ratios.get("operatingProfitMargin"),
"net_margin": latest_ratios.get("netProfitMargin"),
"dividend_yield": latest_ratios.get("dividendYield"),
"payout_ratio": latest_ratios.get("payoutRatio")
}
任务:获取 DCF 估值
def get_dcf_valuation(symbol: str) -> dict:
"""Get pre-computed DCF valuation."""
response = requests.get(
f"{BASE_URL}/discounted-cash-flow",
params={"symbol": symbol, "apikey": API_KEY}
)
data = response.json()
if data:
dcf = data[0]
return {
"symbol": dcf.get("symbol"),
"dcf_value": dcf.get("dcf"),
"stock_price": dcf.get("stockPrice"),
"upside": ((dcf.get("dcf", 0) / dcf.get("stockPrice", 1)) - 1) * 100
}
return {}
# Example
dcf = get_dcf_valuation("AAPL")
print(f"DCF Value: ${dcf['dcf_value']:.2f} ({dcf['upside']:+.1f}% upside)")
任务:获取公司简介
def get_company_profile(symbol: str) -> dict:
"""Get comprehensive company information."""
response = requests.get(
f"{BASE_URL}/profile",
params={"symbol": symbol, "apikey": API_KEY}
)
data = response.json()
if data:
profile = data[0]
return {
"name": profile.get("companyName"),
"symbol": profile.get("symbol"),
"sector": profile.get("sector"),
"industry": profile.get("industry"),
"market_cap": profile.get("mktCap"),
"price": profile.get("price"),
"beta": profile.get("beta"),
"ceo": profile.get("ceo"),
"website": profile.get("website"),
"description": profile.get("description"),
"employees": profile.get("fullTimeEmployees"),
"exchange": profile.get("exchange"),
"ipo_date": profile.get("ipoDate")
}
return {}
任务:获取财报日历
def get_earnings_calendar(from_date: str, to_date: str) -> list:
"""Get upcoming earnings announcements."""
response = requests.get(
f"{BASE_URL}/earnings-calendar",
params={
"from": from_date,
"to": to_date,
"apikey": API_KEY
}
)
return response.json()
# Example
from datetime import datetime, timedelta
today = datetime.now()
next_week = today + timedelta(days=7)
earnings = get_earnings_calendar(
today.strftime("%Y-%m-%d"),
next_week.strftime("%Y-%m-%d")
)
for e in earnings[:5]:
print(f"{e['symbol']}: {e['date']} ({e.get('time', 'N/A')})")
任务:获取历史价格
def get_historical_prices(symbol: str, start: str = None, end: str = None) -> list:
"""Get historical end-of-day prices."""
params = {"symbol": symbol, "apikey": API_KEY}
if start:
params["from"] = start
if end:
params["to"] = end
response = requests.get(
f"{BASE_URL}/historical-price-eod/full",
params=params
)
data = response.json()
return data.get("historical", [])
# Example
prices = get_historical_prices("AAPL", "2025-01-01", "2025-12-01")
print(f"Got {len(prices)} days of data")
任务:搜索公司
def search_companies(query: str, limit: int = 10) -> list:
"""Search for companies by name or symbol."""
response = requests.get(
f"{BASE_URL}/search",
params={
"query": query,
"limit": limit,
"apikey": API_KEY
}
)
return response.json()
# Example
results = search_companies("Apple")
for r in results[:5]:
print(f"{r['symbol']}: {r['name']} ({r['exchangeShortName']})")
任务:获取 SEC 文件
def get_sec_filings(symbol: str, filing_type: str = None) -> list:
"""Get SEC filings for a company."""
params = {"symbol": symbol, "apikey": API_KEY}
if filing_type:
params["type"] = filing_type # 10-K, 10-Q, 8-K, etc.
response = requests.get(
f"{BASE_URL}/sec-filings",
params=params
)
return response.json()
# Example: Get 10-K filings
filings = get_sec_filings("AAPL", "10-K")
for f in filings[:3]:
print(f"{f['type']}: {f['fillingDate']} - {f['link']}")
错误处理
def safe_api_call(endpoint: str, params: dict) -> dict:
"""Make API call with error handling."""
params["apikey"] = API_KEY
try:
response = requests.get(f"{BASE_URL}/{endpoint}", params=params)
data = response.json()
# Check for error messages
if isinstance(data, dict) and "Error Message" in data:
print(f"API Error: {data['Error Message']}")
return {}
# Check for empty response
if not data:
print(f"No data returned for {endpoint}")
return {}
return data
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
return {}
except ValueError as e:
print(f"JSON decode error: {e}")
return {}
免费与付费功能
免费套餐包含
- 每日 250 次 API 调用
- 约 100 个示例代码
- 财务报表
- 关键指标与比率
- DCF 估值
- 公司简介
- 财报日历
- SEC 文件列表
- 基础历史数据
付费功能(Starter 及以上)
- 不限股票代码
- 日内数据
- 股票筛选器
- 国际股票
- 机构持仓
- 共同基金持仓
- ETF 持仓明细
付费功能(Premium+)
- 更高的速率限制
- 13F 文件
- 内幕交易
- 国会交易(参议院/众议院)
- 分析师预估
- 财报电话会议文字稿
- 延长交易时段数据
FMP 独有功能
- 预计算 DCF - 可直接使用的估值
- 国会交易 - 参议院/众议院 STOCK Act 数据
- 13F 文件 - 机构持仓分析
- 标准化财务数据 - 规范化的报表项目
- 公司展望 - 一个端点汇集所有数据
- 评级系统 - 专有的公司评级
最佳实践
- 使用稳定端点 - 使用
/stable/,而非/api/v3/ - 缓存静态数据 - 公司简介、历史数据
- 监控每日限额 - 250 次调用很快就会用完
- 批量查询股票代码 - 在支持的情况下
- 存储财务数据 - 它们仅按季度更新
- 使用 company-outlook - 一次调用即可获取所有数据
安装
# Recommended Python wrapper
pip install --upgrade FinancialModelingPrep-Python
# Basic usage
from fmp_python.fmp import FMP
fmp = FMP(api_key="your_api_key")
profile = fmp.get_company_profile("AAPL")
相关技能
finnhub-api- 实时行情和新闻twelvedata-api- 技术指标alphavantage-api- 经济指标
参考资料
评论
支持 Markdown