yahoo-finance

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Yahoo Finance — API Directa (sin yfinance)

Yahoo Finance — 直接API(无需yfinance)

API no oficial de Yahoo Finance. Accedé a datos de acciones, ETFs, crypto, forex, bonos, índices, opciones, fundamentos y noticias mediante requests HTTP directos sin usar
yfinance
ni ningún wrapper.
Base URL:
https://query1.finance.yahoo.com
Alternativa:
https://query2.finance.yahoo.com

这是Yahoo Finance的非官方API。无需使用
yfinance
或任何包装器,直接通过HTTP请求获取股票、ETF、加密货币、外汇、债券、指数、期权、基本面数据和新闻
基础URL:
https://query1.finance.yahoo.com
备用地址:
https://query2.finance.yahoo.com

⚠️ Importante

⚠️ 重要提示

  • Yahoo no tiene API pública oficial desde 2017. Estos endpoints son no oficiales y pueden cambiar sin aviso.
  • Algunos endpoints requieren autenticación via cookie + crumb (abajo se explica).
  • El endpoint
    v8/finance/chart
    funciona sin autenticación (solo User-Agent de navegador).
  • Siempre implementar rate limiting y manejo de errores.

  • Yahoo自2017年起就没有官方公开API。这些是非官方端点,可能会无预警变更。
  • 部分端点需要通过cookie + crumb进行认证(下文会说明)。
  • v8/finance/chart
    端点无需认证(仅需浏览器的User-Agent)。
  • 务必实现速率限制错误处理

Documentación completa

完整文档

Para referencia exhaustiva de todos los endpoints, campos, JSON structures, códigos de error, tickers internacionales, estrategias de rate limiting y ejemplos detallados, ver:
📖 references/API_REFERENCE.md
Ese documento incluye:
  • Los 33 módulos de
    quoteSummary
    con cada campo documentado
  • JSON responses completas de cada endpoint
  • Tickers internacionales (
    .BA
    para Argentina,
    .SA
    para Brasil, etc.)
  • WebSocket streaming
  • Screener, lookup, trending
  • Estrategias de rate limiting con exponential backoff y rotación de User-Agent

如需了解所有端点、字段、JSON结构、错误代码、国际代码、速率限制策略和详细示例,请查看:
📖 references/API_REFERENCE.md
该文档包含:
  • quoteSummary
    33个模块及每个字段的说明
  • 每个端点的完整JSON响应
  • 国际代码(阿根廷用
    .BA
    ,巴西用
    .SA
    等)
  • WebSocket流
  • 筛选器、查询、趋势
  • 带指数退避和User-Agent轮换的速率限制策略

Autenticación: Cookie + Crumb

认证:Cookie + Crumb

Varios endpoints requieren un crumb (token CSRF) que se obtiene con cookies de sesión.
python
import requests

BASE = "https://query1.finance.yahoo.com"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

def yahoo_session():
    """Retorna requests.Session con cookie A3 y crumb."""
    s = requests.Session()
    s.headers.update(HEADERS)
    s.get("https://fc.yahoo.com", timeout=10)
    crumb = s.get(f"{BASE}/v1/test/getcrumb", timeout=10).text.strip()
    s.params = {"crumb": crumb}
    return s
多个端点需要crumb(CSRF令牌),可通过会话cookie获取。
python
import requests

BASE = "https://query1.finance.yahoo.com"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

def yahoo_session():
    """返回包含A3 cookie和crumb的requests.Session对象。"""
    s = requests.Session()
    s.headers.update(HEADERS)
    s.get("https://fc.yahoo.com", timeout=10)
    crumb = s.get(f"{BASE}/v1/test/getcrumb", timeout=10).text.strip()
    s.params = {"crumb": crumb}
    return s

Uso:

使用示例:

s = yahoo_session()

s = yahoo_session()

undefined
undefined

Endpoints según autenticación

按认证要求分类的端点

Sin auth (solo User-Agent)Requieren crumb
v8/finance/chart
(históricos)
v7/finance/quote
(precios)
v1/finance/search
(búsqueda)
v10/finance/quoteSummary
(fundamentos)
v1/finance/trending
(tendencias)
v7/finance/options
(opciones)
v1/finance/lookup
(lookup)
v6/finance/recommendationsbysymbol

无需认证(仅需User-Agent)需要crumb
v8/finance/chart
(历史数据)
v7/finance/quote
(价格)
v1/finance/search
(搜索)
v10/finance/quoteSummary
(基本面数据)
v1/finance/trending
(趋势)
v7/finance/options
(期权)
v1/finance/lookup
(查询)
v6/finance/recommendationsbysymbol
(相关推荐)

Endpoints — Resumen rápido

端点快速概览

1. Históricos OHLCV —
v8/finance/chart

1. OHLCV历史数据 —
v8/finance/chart

ParámetroEjemplos
range
1d
,
5d
,
1mo
,
3mo
,
6mo
,
1y
,
5y
,
10y
,
ytd
,
max
interval
1m
,
5m
,
15m
,
1h
,
1d
,
1wk
,
1mo
events
div,splits
(incluye dividendos y splits)
python
import requests
headers = {"User-Agent": "Mozilla/5.0 (...) Chrome/120.0.0.0 Safari/537.36"}
r = requests.get("https://query1.finance.yahoo.com/v8/finance/chart/AAPL",
                 params={"range": "1y", "interval": "1d", "events": "div,splits"},
                 headers=headers)
data = r.json()["chart"]["result"][0]
参数示例
range
1d
,
5d
,
1mo
,
3mo
,
6mo
,
1y
,
5y
,
10y
,
ytd
,
max
interval
1m
,
5m
,
15m
,
1h
,
1d
,
1wk
,
1mo
events
div,splits
(包含股息和拆股信息)
python
import requests
headers = {"User-Agent": "Mozilla/5.0 (...) Chrome/120.0.0.0 Safari/537.36"}
r = requests.get("https://query1.finance.yahoo.com/v8/finance/chart/AAPL",
                 params={"range": "1y", "interval": "1d", "events": "div,splits"},
                 headers=headers)
data = r.json()["chart"]["result"][0]

data["timestamp"] -> fechas Unix

data["timestamp"] -> Unix时间戳格式的日期

data["indicators"]["quote"][0] -> open, high, low, close, volume

data["indicators"]["quote"][0] -> 开盘价、最高价、最低价、收盘价、成交量

data["indicators"]["adjclose"][0] -> precios ajustados

data["indicators"]["adjclose"][0] -> 调整后价格

data["events"] -> dividendos y splits

data["events"] -> 股息和拆股信息

undefined
undefined

2. Quote —
v7/finance/quote

2. 报价数据 —
v7/finance/quote

python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v7/finance/quote?symbols=AAPL,MSFT,GOOGL")
quotes = r.json()["quoteResponse"]["result"]
for q in quotes:
    print(q["symbol"], q["regularMarketPrice"], q["regularMarketChangePercent"])
Campos:
regularMarketPrice
,
regularMarketChangePercent
,
marketCap
,
trailingPE
,
fiftyTwoWeekHigh/Low
,
dividendYield
,
volume
,
marketState
(PRE/REGULAR/POST/CLOSED).
python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v7/finance/quote?symbols=AAPL,MSFT,GOOGL")
quotes = r.json()["quoteResponse"]["result"]
for q in quotes:
    print(q["symbol"], q["regularMarketPrice"], q["regularMarketChangePercent"])
可用字段:
regularMarketPrice
(常规市场价格)、
regularMarketChangePercent
(常规市场涨跌幅)、
marketCap
(市值)、
trailingPE
(滚动市盈率)、
fiftyTwoWeekHigh/Low
(52周最高/低价)、
dividendYield
(股息率)、
volume
(成交量)、
marketState
(市场状态:PRE/REGULAR/POST/CLOSED)。

3. Fundamentos —
v10/finance/quoteSummary

3. 基本面数据 —
v10/finance/quoteSummary

python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v10/finance/quoteSummary/AAPL",
          params={"modules": "assetProfile,financialData,defaultKeyStatistics,incomeStatementHistory,balanceSheetHistory,cashflowStatementHistory,earnings,recommendationTrend"})
fundamentals = r.json()["quoteSummary"]["result"][0]
profile = fundamentals["assetProfile"]           # sector, industry, employees, description
financials = fundamentals["financialData"]        # EBITDA, revenue, margins, ROE, ROA
stats = fundamentals["defaultKeyStatistics"]      # beta, shares, PE, PEG, short info
Hay 33 módulos disponibles. Ver lista completa en API_REFERENCE.md sección 4.
python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v10/finance/quoteSummary/AAPL",
          params={"modules": "assetProfile,financialData,defaultKeyStatistics,incomeStatementHistory,balanceSheetHistory,cashflowStatementHistory,earnings,recommendationTrend"})
fundamentals = r.json()["quoteSummary"]["result"][0]
profile = fundamentals["assetProfile"]           # 行业板块、细分行业、员工数量、公司描述
financials = fundamentals["financialData"]        # EBITDA、营收、利润率、净资产收益率、资产收益率
stats = fundamentals["defaultKeyStatistics"]      # β系数、股份数、市盈率、市盈增长比率、做空信息
共有33个可用模块。完整列表请查看API_REFERENCE.md第4节

4. Opciones —
v7/finance/options

4. 期权数据 —
v7/finance/options

python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v7/finance/options/AAPL")
data = r.json()["optionChain"]["result"][0]
expirations = data["expirationDates"]
strikes = data["strikes"]
options = data["options"][0]  # calls + puts
python
s = yahoo_session()
r = s.get("https://query1.finance.yahoo.com/v7/finance/options/AAPL")
data = r.json()["optionChain"]["result"][0]
expirations = data["expirationDates"]
strikes = data["strikes"]
options = data["options"][0]  # 认购期权+认沽期权

5. Búsqueda + Noticias —
v1/finance/search

5. 搜索+新闻 —
v1/finance/search

python
r = requests.get("https://query1.finance.yahoo.com/v1/finance/search",
                 params={"q": "Apple", "quotesCount": 3, "newsCount": 5},
                 headers=HEADERS)
data = r.json()
python
r = requests.get("https://query1.finance.yahoo.com/v1/finance/search",
                 params={"q": "Apple", "quotesCount": 3, "newsCount": 5},
                 headers=HEADERS)
data = r.json()

data["quotes"] -> tickers encontrados

data["quotes"] -> 搜索到的代码

data["news"] -> noticias relacionadas

data["news"] -> 相关新闻


---

---

Scripts

脚本

ScriptDescripción
fetch_all.pyScript integral: fetch de histórico + quote + fundamentals + opciones + search + recomendaciones. Genérico para cualquier ticker con argumentos CLI.
fetch_quote.pyFetch rápido de quote + fundamentals por ticker.
download_historical.pyDescarga históricos OHLCV a CSV.
脚本描述
fetch_all.py集成脚本:获取历史数据+报价+基本面数据+期权+搜索+相关推荐。支持通过CLI参数适配任意代码。
fetch_quote.py快速获取指定代码的报价+基本面数据。
download_historical.py将OHLCV历史数据下载为CSV文件。

fetch_all.py — El script principal

fetch_all.py — 主脚本

python scripts/fetch_all.py --ticker AAPL --all                     # Todo lo disponible
python scripts/fetch_all.py --ticker GGAL --all --range 5y --interval 1d  # GGAL con 5 años
python scripts/fetch_all.py --ticker MSFT --chart --range max        # Histórico completo
python scripts/fetch_all.py --ticker NVDA --quote --fundamentals     # Quote + fundamentals
python scripts/fetch_all.py --ticker TSLA --all --all-modules        # Todos los módulos (~33)
python scripts/fetch_all.py --ticker AAPL --options                  # Solo opciones
python scripts/fetch_all.py -t AAPL -o mi_data.json -q               # Output a archivo, quiet
Flags principales:
  • --all
    : fetch de todo (chart, quote, fundamentals, options, search, recommendations)
  • --chart
    : histórico OHLCV
  • --quote
    : precio en tiempo real
  • --fundamentals
    : fundamentos (quoteSummary)
  • --options
    : cadena de opciones
  • --search
    : búsqueda y noticias
  • --range
    /
    --interval
    : control del histórico
  • --modules
    /
    --all-modules
    : módulos de quoteSummary
  • --output
    : archivo JSON de salida
python scripts/fetch_all.py --ticker AAPL --all                     # 获取所有可用数据
python scripts/fetch_all.py --ticker GGAL --all --range 5y --interval 1d  # 获取GGAL的5年数据
python scripts/fetch_all.py --ticker MSFT --chart --range max        # 获取完整历史数据
python scripts/fetch_all.py --ticker NVDA --quote --fundamentals     # 获取报价+基本面数据
python scripts/fetch_all.py --ticker TSLA --all --all-modules        # 获取所有模块(约33个)
python scripts/fetch_all.py --ticker AAPL --options                  # 仅获取期权数据
python scripts/fetch_all.py -t AAPL -o mi_data.json -q               # 输出到文件,静默模式
主要参数:
  • --all
    : 获取全部数据(历史数据、报价、基本面、期权、搜索、相关推荐)
  • --chart
    : 获取OHLCV历史数据
  • --quote
    : 获取实时价格
  • --fundamentals
    : 获取基本面数据(quoteSummary)
  • --options
    : 获取期权链
  • --search
    : 获取搜索结果和新闻
  • --range
    /
    --interval
    : 控制历史数据的范围和间隔
  • --modules
    /
    --all-modules
    : 指定quoteSummary的模块
  • --output
    : 指定JSON输出文件

Prueba real con GGAL (testeado)

GGAL真实测试(已验证)

>> Chart (1y, 1d)... OK 250 bars
>> Quote...             OK Price: $50.33 (-1.62%)
>> Fundamentals...      OK 12 módulos (core)
>> Options...           OK 5 expiration dates, 17 calls, 19 puts
>> Search+News...       OK 5 news items
Guardado en: ggal_temp.json  (123 KB)

>> 历史数据(1年,1天间隔)... 成功 250条数据
>> 报价...             成功 价格: $50.33 (-1.62%)
>> 基本面数据...      成功 12个核心模块
>> 期权...           成功 5个到期日,17份认购期权,19份认沽期权
>> 搜索+新闻...       成功 5条新闻
已保存至: ggal_temp.json  (123 KB)

Tickers internacionales

国际代码

Yahoo Finance usa sufijos para mercados fuera de EE.UU.:
MercadoSufijoEjemplo
Argentina (BCBA)
.BA
GGAL.BA
,
YPFD.BA
Brasil (Bovespa)
.SA
PETR4.SA
,
VALE3.SA
México (BMV)
.MX
WALMEX.MX
Crypto
-USD
BTC-USD
,
ETH-USD
Forex
=X
EURUSD=X
Índices
^
^GSPC
(S&P 500)
Ver lista completa en API_REFERENCE.md sección 14.

Yahoo Finance为美国以外的市场使用后缀:
市场后缀示例
阿根廷(BCBA)
.BA
GGAL.BA
,
YPFD.BA
巴西(Bovespa)
.SA
PETR4.SA
,
VALE3.SA
墨西哥(BMV)
.MX
WALMEX.MX
加密货币
-USD
BTC-USD
,
ETH-USD
外汇
=X
EURUSD=X
指数
^
^GSPC
(标普500)
完整列表请查看API_REFERENCE.md第14节

Rate Limits

速率限制

LímiteComportamiento
~2 req/sSeguro
3-5 req/sProbabilidad alta de 429
>10 req/sIP block temporal
Siempre usar
time.sleep(0.5)
entre requests e implementar exponential backoff.

限制表现
~2次请求/秒安全
3-5次请求/秒大概率触发429错误
>10次请求/秒临时封禁IP
务必在请求之间添加
time.sleep(0.5)
,并实现指数退避机制。

Errores Comunes

常见错误

ErrorCausaSolución
401 Unauthorized
Falta crumbUsar
yahoo_session()
429 Too Many Requests
Rate limitEsperar 30-60s
Bad Request
Crumb expiradoRegenerar crumb
result
vacío
Ticker inválidoVerificar con search primero
Python-requests
block
User-Agent defaultSetear uno de navegador

错误原因解决方案
401 Unauthorized
缺少crumb使用
yahoo_session()
429 Too Many Requests
触发速率限制等待30-60秒
Bad Request
crumb过期重新生成crumb
result
为空
代码无效先通过搜索验证代码
Python-requests
被拦截
默认User-Agent问题设置浏览器的User-Agent

Estructura del skill

技能结构

skills/yahoo-finance/
├── SKILL.md                          # Este archivo (quickstart)
├── references/
│   └── API_REFERENCE.md              # Documentación completa de todos los endpoints
└── scripts/
    ├── fetch_all.py                  # Script integral (recomendado)
    ├── fetch_quote.py                # Quote + fundamentals rápido
    └── download_historical.py        # Históricos a CSV
skills/yahoo-finance/
├── SKILL.md                          # 本文档(快速入门)
├── references/
│   └── API_REFERENCE.md              # 所有端点的完整文档
└── scripts/
    ├── fetch_all.py                  # 集成脚本(推荐使用)
    ├── fetch_quote.py                # 快速获取报价+基本面数据
    └── download_historical.py        # 将历史数据下载为CSV