Skip to main content
ClaudeWave
Skill12k estrellas del repoactualizado today

yfinance

yfinance is an open-source Python wrapper for Yahoo Finance that retrieves historical OHLCV data, company information, and financial statements for US stocks, Hong Kong stocks, ETFs, and indices without requiring API keys or registration. Use this skill when backtesting trading strategies or analyzing global market data across multiple exchanges by setting the data source to "yfinance" or "auto" in your configuration.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading /tmp/yfinance && cp -r /tmp/yfinance/agent/src/skills/yfinance ~/.claude/skills/yfinance
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# yfinance

## Overview

yfinance is an open-source Python wrapper for Yahoo Finance, providing global market data (US stocks, HK stocks, ETFs, indices) including historical and real-time quotes. **Completely free, no registration or API key required.**

The project has a built-in yfinance DataLoader (`backtest/loaders/yfinance_loader.py`). When backtesting, set `source: "yfinance"` or `source: "auto"` to invoke it automatically.

For OHLCV bars in agent/swarm work, prefer the `get_market_data` tool when it is available. It routes through the project loader layer, normalizes symbols, removes malformed OHLC rows, and returns strict JSON. Use direct `yfinance` calls mainly for data outside OHLCV coverage such as company info, financial statements, options, holders, and insider transactions.

## Quick Start

Preferred OHLCV tool call:

```json
{
  "codes": ["AAPL.US", "700.HK"],
  "start_date": "2025-01-01",
  "end_date": "2026-01-01",
  "source": "yfinance",
  "interval": "1D"
}
```

If you must write a Python script for OHLCV, use the DataLoader instead of raw `yf.download`:

```python
from backtest.loaders.registry import get_loader_cls_with_fallback

loader = get_loader_cls_with_fallback("yfinance")()
data = loader.fetch(["AAPL.US", "700.HK"], "2025-01-01", "2026-01-01", interval="1D")

for symbol, df in data.items():
    print(symbol, df.tail())
```

## Ticker Format Conversion

The project uses a unified ticker format. The DataLoader automatically converts to yfinance format:

| Project Format | yfinance Format | Market |
|---------------|----------------|--------|
| `AAPL.US` | `AAPL` | US stock |
| `MSFT.US` | `MSFT` | US stock |
| `700.HK` | `0700.HK` | HK stock |
| `9988.HK` | `9988.HK` | HK stock |
| `SPY.US` | `SPY` | US ETF |

**Rules:**
- US stocks: strip the `.US` suffix → use the raw ticker
- HK stocks: keep `.HK`, pad the number to 4 digits (`700` → `0700`)

## Supported Data Types

### 1. Historical OHLCV

Prefer `get_market_data` for OHLCV whenever the tool is available:

```json
{
  "codes": ["AAPL.US", "MSFT.US", "GOOGL.US"],
  "start_date": "2025-01-01",
  "end_date": "2026-01-01",
  "source": "yfinance",
  "interval": "1D",
  "max_rows": 250
}
```

For script-based OHLCV analysis, use the loader:

```python
from backtest.loaders.registry import get_loader_cls_with_fallback

loader = get_loader_cls_with_fallback("yfinance")()

# Single stock
single = loader.fetch(["AAPL.US"], "2025-01-01", "2026-01-01", interval="1D")

# Specific interval
hourly = loader.fetch(["AAPL.US"], "2026-03-01", "2026-03-30", interval="1H")
```

**Supported intervals:**
- Minute-level: `1m`, `2m`, `5m`, `15m`, `30m`, `60m`, `90m`
- Hourly: `1h`
- Daily and above: `1d`, `5d`, `1wk`, `1mo`, `3mo`

**Minute data limits:**
- `1m`: up to 7 days of history
- `2m/5m/15m/30m/60m/90m`: up to 60 days
- `1h`: up to 730 days
- `1d` and above: unlimited

### 2. Company Info

```python
ticker = yf.Ticker("AAPL")

info = ticker.info
print(f"Company: {info.get('longName')}")
print(f"Industry: {info.get('industry')}")
print(f"Market cap: {info.get('marketCap')}")
print(f"PE: {info.get('trailingPE')}")
print(f"EPS: {info.get('trailingEps')}")
print(f"Dividend yield: {info.get('dividendYield')}")
```

### 3. Financial Statements

```python
ticker = yf.Ticker("AAPL")

# Income statement (annual)
income = ticker.financials
# Income statement (quarterly)
income_q = ticker.quarterly_financials

# Balance sheet
balance = ticker.balance_sheet

# Cash flow statement
cashflow = ticker.cashflow

# Earnings data
earnings = ticker.earnings
```

### 4. Dividends and Splits

```python
ticker = yf.Ticker("AAPL")

# Dividend history
dividends = ticker.dividends

# Stock split history
splits = ticker.splits

# All corporate actions
actions = ticker.actions
```

### 5. Institutional Holdings

```python
ticker = yf.Ticker("AAPL")

# Institutional holders
holders = ticker.institutional_holders

# Major holders summary
major = ticker.major_holders

# Insider transactions
insider = ticker.insider_transactions
```

### 6. Indices and ETFs

```python
# Major indices
sp500 = yf.download("^GSPC", start="2025-01-01", end="2026-01-01", progress=False)  # S&P 500
nasdaq = yf.download("^IXIC", start="2025-01-01", end="2026-01-01", progress=False)  # NASDAQ
hsi = yf.download("^HSI", start="2025-01-01", end="2026-01-01", progress=False)      # Hang Seng Index

# ETFs
spy = yf.download("SPY", start="2025-01-01", end="2026-01-01", progress=False)
qqq = yf.download("QQQ", start="2025-01-01", end="2026-01-01", progress=False)
```

### 7. FX Rates

```python
# Currency pairs
usdcny = yf.download("CNY=X", start="2025-01-01", end="2026-01-01", progress=False)
usdhkd = yf.download("HKD=X", start="2025-01-01", end="2026-01-01", progress=False)
eurusd = yf.download("EURUSD=X", start="2025-01-01", end="2026-01-01", progress=False)
```

## Popular Ticker Reference

### US Stocks

| Ticker | Company |
|--------|---------|
| AAPL | Apple |
| MSFT | Microsoft |
| GOOGL | Alphabet (Google) |
| AMZN | Amazon |
| NVDA | NVIDIA |
| META | Meta Platforms |
| TSLA | Tesla |
| BRK-B | Berkshire Hathaway |

### HK Stocks

| Project Format | yfinance Format | Company |
|---------------|----------------|---------|
| 700.HK | 0700.HK | Tencent |
| 9988.HK | 9988.HK | Alibaba |
| 9618.HK | 9618.HK | JD.com |
| 3690.HK | 3690.HK | Meituan |
| 1810.HK | 1810.HK | Xiaomi |
| 2318.HK | 2318.HK | Ping An |

### Major Indices

| Ticker | Index |
|--------|-------|
| ^GSPC | S&P 500 |
| ^DJI | Dow Jones Industrial Average |
| ^IXIC | NASDAQ Composite |
| ^HSI | Hang Seng Index |
| ^N225 | Nikkei 225 |
| ^FTSE | FTSE 100 |

### Sector ETFs

| Ticker | Sector |
|--------|--------|
| XLK | Technology |
| XLF | Financials |
| XLE | Energy |
| XLV | Healthcare |
| XLY | Consumer Discretionary |
| XLP | Consumer Staples |
| XLI | Industrials |
| XLU | Utilities |

## Backtest Usage

### config.json Example

```json
{
  "source": "yfinance",
  "codes": ["AAPL.US", "MSFT.US"],
  "star
vibe-tradingSkill

Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).

adr-hshareSkill

ADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.

akshareSkill

AKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.

alpha-zooSkill

Browse and bench the bundled alpha zoos — prebuilt cross-sectional factor libraries (Kakushadze 101, GTJA 191, Qlib 158, Fama-French / Carhart). Use when the user asks "which alphas exist", wants metadata on a named alpha, or wants to run IC/IR on a whole zoo over a universe.

ashare-pre-st-filterSkill

A 股 ST/*ST 风险预测框架 — 基于最新中报/三季报或业绩预告/快报,预测下一财年是否会因营收、利润、净资产、分红不达标而被风险警示,并将新浪监管处罚记录作为独立证据面纳入风险等级。仅适用于 A 股,不预测财务造假。

asset-allocationSkill

Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.

backtest-diagnoseSkill

Diagnose failed or underperforming backtests, locate the root cause, and fix the issue

behavioral-financeSkill

Behavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.