global-stock-data
美股港股全栈数据工具包(官方源优先)— 十七层架构·50+端点·18数据源·全部零鉴权。在原有行情/K线/技术指标(MA/MACD/RSI/KDJ/布林带)/基本面/资金面/期权/SEC Filing/工具八层之上,新增:CBOE官方期权链(完整希腊字母+IV+0DTE流+异动识别)、FINRA全市场每日空头成交量、SEC EDGAR申报事件流(Form4内部人/8-K/13F机构持仓)、EDGAR全市场横截面筛选、美债收益率曲线/CFTC COT/财报日历;V2.1 新增全球利率汇率层(BIS 38家央行政策利率、欧洲央行汇率/利率/欧元区收益率曲线、纽约联储SOFR/EFFR、美联储H.10汇率/H.6货币存量、美国财政部国债拍卖/联邦债务),Yahoo K线修复全历史日线与时区并支持日本/台湾/韩国/印度/欧洲等市场代码;V2.2 新增CBOE波动率指数历史与VIX期限结构、FINRA做空余额(每月两期)、SEC Form 4内部人逐笔交易与13F机构持仓解析、台股官方OpenAPI(证交所+柜买中心,可商用)、美国能源信息署EIA原油/天然气价格与库存;V2.3 新增美国宏观层(美国劳工统计局BLS公共API免注册:CPI/核心CPI/非农/失业率/时薪/PPI/JOLTS职位空缺/进口价格/ECI/生产率,附官方发布日程与修订规则,劳工部每周初请/续请失业金)。每个数据源标注合规级别与条款原文。内嵌全部调用代码,自包含零依赖外部文件。适用于美股港股个股分析、全市场筛选、财报解读、期权与0DTE策略、做空数据追踪、内部人交易与13F持仓、SEC文件检索、资金流与机构持仓分析、全球利率汇率与央行政策跟踪、VIX波动率、台股、原油天然气、美国CPI/非农/失业金等宏观数据与发布日程等场景。
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/simonlin1212--global-stock-data)HTML
<a href="/listings/simonlin1212--global-stock-data"><img src="/api/listings/simonlin1212--global-stock-data/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
**3 steps, 2 minutes.**
# 1. Create the skill directory mkdir -p ~/.claude/skills/global-stock-data # 2. Download SKILL.md curl -o ~/.claude/skills/global-stock-data/SKILL.md \ https://raw.githubusercontent.com/simonlin1212/global-stock-data/main/SKILL.md # 3. Install the dependency pip install requests # Windows only: also install tzdata so Yahoo K-line dates use the exchange's time zone pip install tzdata
⚠️ **Before using the SEC or US macro (BLS) layers, set `SEC_CONTACT` in SKILL.md to your real name and email.** SEC requires a declared User-Agent; requests without one are rejected as an *Undeclared Automated Tool*, and the BLS website returns 403. The code raises a clear error if you forget.
Launch Claude Code and say "check AAPL's financials" — the skill activates on its own. **Codex / OpenClaw users:** paste SKILL.md into your system prompt or project context file; the embedded Python runs as-is.
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 4,323 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- ---
- name: global-stock-data
- description: 美股港股全栈数据工具包(官方源优先)— 十七层架构·50+端点·18数据源·全部零鉴权。在原有行情/K线/技术指标(MA/MACD/RSI/KDJ/布林带)/基本面/资金面/期权/SEC Filing/工具八层之上,新增:CBOE官方期权链(完整希腊字母+IV+0DTE流+异动识别)、FINRA全市场每日空头成交量、SEC EDGAR申报事件流(Form4内部人/8-K/13F机构持仓)、EDGAR全市场横截面筛选、美债收益率曲线/CFTC COT/财报日历;V2.1 新增全球利率汇率层(BIS 38家央行政策利率、欧洲央行汇率/利率/欧元区收益率曲线、纽约联储SOFR/EFFR、美联储H.10汇率/H.6货币存量、美国财政部国债拍卖/联邦债务),Yahoo K线修复全历史日线与时区并支持日本/台湾/韩国/印度/欧洲等市场代码;V2.2 新增CBOE波动率指数历史与VIX期限结构、FINRA做空余额(每月两期)、SEC Form 4内部人逐笔交易与13F机构持仓解析、台股官方OpenAPI(证交所+柜买中心,可商用)、美国能源信息署EIA原油/天然气价格与库存;V2.3 新增美国宏观层(美国劳工统计局BLS公共API免注册:CPI/核心CPI/非农/失业率/时薪/PPI/JOLTS职位空缺/进口价格/ECI/生产率,附官方发布日程与修订规则,劳工部每周初请/续请失业金)。每个数据源标注合规级别与条款原文。内嵌全部调用代码,自包含零依赖外部文件。适用于美股港股个股分析、全市场筛选、财报解读、期权与0DTE策略、做空数据追踪、内部人交易与13F持仓、SEC文件检索、资金流与机构持仓分析、全球利率汇率与央行政策跟踪、VIX波动率、台股、原油天然气、美国CPI/非农/失业金等宏观数据与发布日程等场景。
- origin: custom
- version: 2.3.0
- ---
- > 📦 项目主页:https://github.com/simonlin1212/global-stock-data — 更新、反馈、支持作者
- >
- > 作者:Simon 林 · X [@linsizhen](https://x.com/linsizhen) · 邮箱:simonlin0423@gmail.com
- # 美股港股全栈数据工具包 V2.3 — 官方源优先
- 十七层数据架构,50+ 个端点,18 个数据源,全部零鉴权,实测可用(2026-07-24 全量回归验证;V2.1 新增与修复部分 2026-10-11 实测;V2.2 新增部分 2026-10-12 实测;V2.3 新增部分 2026-11-02 实测)。层数按「原有八层 + V2.0 五层(CBOE 期权链单算一层)+ V2.1 一层 + V2.2 两层(台股、能源)+ V2.3 一层(美国宏观)」计;V2.2 的波动率指数、做空余额、Form 4 / 13F 解析是原有层里的新小节,不另计层。
- **V2.0 设计原则:官方源优先。** 新增层的主力数据取自美国政府(SEC EDGAR / Treasury / CFTC)、
- 自律组织(FINRA)与交易所(CBOE / Nasdaq)的公开端点;V2.1 再加国际清算银行、欧洲央行、
- 美联储、纽约联储四家官方机构;V2.2 再加台湾证交所、柜买中心与美国能源信息署 EIA;V2.3 再加美国劳工部(劳工统计局 BLS + 每周失业金申领)。**每个数据源都标注了合规级别与条款原文**
- (见下方「数据源合规分级」)——"官方"不等于"可自由使用",各源差异极大。
- **本工具只分发代码,不分发、不转售任何市场数据**;数据由使用者自行按各源条款获取。
- **使用方式:** 将本文件放入 `~/.claude/skills/global-stock-data/SKILL.md`,Claude Code 会自动识别并在美股/港股相关对话中激活。
- ```
- 行情层(实时/延时)
- ├── 新浪财经 → 美股 gb_XXXX 36字段 / 港股 rt_hkXXXXX 25字段
- ├── 腾讯财经 → 美股 usXXXX 71字段 / 港股 r_hkXXXXX 78字段
- └── 东财 push2 → 美股/港股 secid 实时行情,含中文名/涨跌幅/换手率
- K线层(日/周/月/分钟)
- ├── 新浪 → 美股日K (回溯至1984年)
- └── Yahoo chart → 美股+港股+日本/台湾/韩国/印度/欧洲等 (v8 API, 零crumb, 全历史日线) [D级]
- 技术指标层(纯计算,零额外依赖)
- └── MA/EMA + MACD + RSI + KDJ + 布林带 基于K线OHLCV,纯Python计算
- 基本面层
- ├── 东财 datacenter → 美股/港股三表(资产负债+利润+现金流) + GMAININDICATOR(关键指标)
- ├── Yahoo crumb → 23个模块(财务数据+关键指标+分析师+机构持仓)
- └── SEC EDGAR XBRL → 美股503个GAAP指标 (仅美股)
- 资金面层
- └── 东财 push2his → 日级资金流(主力/大单/中单/小单) 美股+港股
- 期权层(仅美股)
- └── Yahoo crumb → 期权链(calls+puts, 所有到期日) 仅美股(港股期权不在Yahoo覆盖范围)
- SEC Filing层(仅美股)
- ├── EDGAR submissions → 10-K/10-Q/8-K 完整Filing列表
- └── EDGAR XBRL → 结构化财务指标(营收/净利/EPS等)
- 工具层
- ├── 东财 search → 股票搜索(中英文, 含市场代码映射)
- ├── 东财 push2 → 全市场股票列表(涨跌幅/成交量排名, 美股5925只+港股18000+只)
- ├── Yahoo search → 新闻资讯(按股票代码)
- └── SEC CIK mapping → ticker↔CIK 映射 (仅美股)
- ━━━ 以下为 V2.0 新增(官方源优先)━━━
- 期权层·CBOE 官方(仅美股)⭐
- └── CBOE cdn → 全链 + IV + delta/gamma/vega/theta/rho + 0DTE + 异动flow [C级·需授权]
- 做空层(仅美股)⭐
- └── FINRA Reg SHO → 全市场每日空头成交量(实测12,112只) + 个股时序 + 排行 [B级]
- 申报事件流(仅美股)⭐
- ├── EDGAR 每日索引 → Form4内部人/8-K/13F机构持仓/144,当日全量 [S级]
- └── EDGAR 全文检索 → 2001至今所有申报正文,按关键词+表单+日期 [S级]
- 全市场横截面(仅美股)⭐
- └── EDGAR frames → 任意XBRL标签一次拿全市场(实测1,842~5,309家)=免费screener [S级]
- 宏观 / 日历 ⭐
- ├── Treasury → 美债收益率曲线(1M~30Y, 每日) [S级]
- ├── CFTC → COT 持仓报告 [S级]
- └── Nasdaq → 财报日历(含盘前盘后+EPS预期) [D级]
- ━━━ 以下为 V2.1 新增 ━━━
- 全球利率 / 汇率 / 央行 ⭐
- ├── BIS → 38家央行政策利率(一次取全) [S级]
- ├── ECB → 欧元参考汇率 + ECB三大利率 + 欧元区收益率曲线 [S级]
- ├── 纽约联储 → SOFR / EFFR / OBFR / TGCR / BGCR [S级·须附声明]
- ├── 美联储 → H.10 美元对23种货币 + H.6 M1/M2 [S级]
- └── 财政部 → 国债拍卖结果与日程 + 联邦债务 + 国债平均利率 [S级]
- ━━━ 以下为 V2.2 新增 ━━━
- 波动率(仅美股)⭐
- └── CBOE 指数文件 → VIX 1990起日线 + VIX9D/3M/6M/1Y 期限结构 + VVIX/SKEW/OVX/GVZ [C级·需授权]
- 做空余额(仅美股)⭐
- └── FINRA 每月两期 → 全美未平仓空头(实测22,595只) + 回补天数 + 排行 [B级]
- 内部人交易 / 机构持仓(仅美股)⭐
- ├── SEC Form 4 → 逐笔买卖(价格/股数/交易后持股/申报是否勾10b5-1) + 买卖汇总 [S级]
- └── SEC 13F → 机构季度持仓明细(按市值排序 + 占比) [S级]
- 台股 ⭐
- └── 证交所 + 柜买中心 OpenAPI → 全市场最新行情/本益比/月营收/融资融券/除权息 [S级·注明来源]
- 能源 ⭐
- └── EIA → 原油/天然气每周库存 [S级] + WTI(1986起)/布伦特/Henry Hub 现货日价 [B级·转载 Refinitiv]
- ━━━ 以下为 V2.3 新增 ━━━
- 美国宏观 ⭐
- ├── 劳工统计局 BLS → CPI/核心CPI/非农/失业率/时薪/PPI/JOLTS/进口价格/ECI/生产率 + 任意序列号 [S级·注明来源与取数日期]
- ├── 劳工统计局 BLS → 官方发布日程(每次发布的日期和美东时间) [S级]
- └── 劳工部 ETA → 每周初请/续请失业金(1967起) [S级]
- ```
- ---
- ## 端点路由速查(按需定位,不必通读全文)
- | 我想要… | 去哪层 | 主力源 | 合规级 |
- |---|---|---|---|
- | 实时/延时报价 | Layer 1 | 新浪 / 腾讯 / 东财 | C |
- | K 线(日/周/月;日本/台湾/韩国/印度/欧洲等换代码后缀) | Layer 2 | 新浪 / Yahoo | C·D |
- | 技术指标 MA/MACD/RSI/KDJ/布林 | Layer 3 | 本地计算 | — |
- | 财报三表 / 关键指标 / 分析师 / 机构持仓 | Layer 4 | 东财 / Yahoo / EDGAR | C·D·S |
- | 日级资金流 | Layer 5 | 东财 | C |
- | **期权链 + 希腊字母 + IV + 0DTE + 异动flow** | **Layer 6.1** | **CBOE 官方** ⭐ | C |
- | 期权链(无希腊字母,后备) | Layer 6.2 | Yahoo | D |
- | 10-K/10-Q/8-K 列表、XBRL 财务 | Layer 7 | SEC EDGAR | **S** |
- | 搜索 / 新闻 / CIK 映射 / 全市场列表 | Layer 8 | 东财 / Yahoo / SEC | C·D·S |
- | **全市场每日空头成交量、个股空头占比** | **Layer 9.1** | **FINRA Reg SHO** ⭐ | B |
- | **当日申报流:Form 4 内部人 / 8-K / 13F** | **Layer 10.1** | **EDGAR 每日索引** ⭐ | **S** |
- | **申报全文检索(2001 至今正文)** | **Layer 10.2** | **EDGAR FTS** ⭐ | **S** |
- | **全市场基本面横截面(免费 screener)** | **Layer 11** | **EDGAR frames** ⭐ | **S** |
- | 美债收益率曲线 / CFTC COT / 财报日历 | Layer 12 | Treasury / CFTC / Nasdaq | S·D |
- | **全球央行政策利率** | **Layer 13.1** | **BIS** ⭐ | **S** |
- | **欧元汇率 / ECB 利率 / 欧元区收益率曲线** | **Layer 13.2** | **欧洲央行** ⭐ | **S** |
- | **SOFR / EFFR 等美元参考利率** | **Layer 13.3** | **纽约联储** ⭐ | **S** |
- | **美元对 23 种货币汇率 / M1·M2** | **Layer 13.4** | **美联储** ⭐ | **S** |
- | **国债拍卖结果与日程 / 联邦债务** | **Layer 13.5** | **财政部 FiscalData** ⭐ | **S** |
- | **VIX 历史 / 期限结构 / VVIX / SKEW** | **Layer 6.3** | **CBOE 官方** ⭐ | C |
- | **做空余额(未平仓空头)/ 回补天数** | **Layer 9.2** | **FINRA** ⭐ | B |
- | **内部人逐笔买卖(Form 4)** | **Layer 10.3** | **SEC EDGAR** ⭐ | **S** |
- | **机构 13F 持仓明细** | **Layer 10.4** | **SEC EDGAR** ⭐ | **S** |
- | **台股最新行情 / 本益比 / 月营收 / 融资融券** | **Layer 14** | **证交所 / 柜买中心** ⭐ | **S** |
- | **原油 / 天然气每周库存** | **Layer 15** | **EIA** ⭐ | **S** |
- | **原油 / 天然气现货日价** | **Layer 15** | **EIA(转载 Refinitiv)** ⭐ | B |
- | **美国 CPI / 非农 / 失业率 / PPI / JOLTS 等宏观数据** | **Layer 16.1–16.2** | **劳工统计局 BLS** ⭐ | **S** |
- | **CPI、非农等下次什么时候发布** | **Layer 16.3** | **劳工统计局 BLS** ⭐ | **S** |
- | **每周初请 / 续请失业金** | **Layer 16.4** | **劳工部 ETA** ⭐ | **S** |
- ⭐ = V2.0 / V2.1 / V2.2 / V2.3 新增,且为 yfinance 与多数开源方案不具备的能力。
- ---
- ## 数据源合规分级(取用前必读 — 各级均引条款原文)
- > 下表结论来自 **逐家实读各源条款原文**(2026-07-24;V2.1 于 2026-10-11 复核 Yahoo / Nasdaq,
- > 并新读 BIS / ECB / 美联储理事会 / 纽约联储 4 家新增官方源;V2.2 于 2026-10-12 新读台湾证交所 / 柜买中心
- > 使用条款、台湾《政府资料开放授权条款》与 EIA;V2.3 于 2026-11-02 新读美国劳工统计局 BLS 版权页与 API 使用条款、劳工部版权页),除标明「本工具的判断」处外都不是推断。引号内为原文。
- > **各源差异极大,"官方"不等于"可自由使用"。**
- ### S 级 — 可自由使用(含商用与再分发;部分要求注明来源)
- | 源 | 依据(原文) |
- |---|---|
- | **SEC EDGAR** | 官网明示:*"Anyone can access and download this information **for free**"*、*"We **allow scripted access** to sec.gov content"*。**硬性要求**:`Current max request rate: 10 requests/second`,且必须声明 User-Agent(格式 `Company Name AdminContact@domain.com`),否则触发 *"Undeclared Automated Tool"* / Access Denied |
- | **US Treasury / CFTC** | 美国联邦政府作品不受版权保护(17 U.S.C. §105)。FiscalData 接口文档:*"Our API is **open**, meaning that it does not require a user account or registration for a token."* ⚠️ 收益率曲线页与 CFTC 的条款正文**未逐条核验**,按政府数据惯例归此级 |
- | **美联储理事会** | *"Unless otherwise indicated, information on Board's website is in the **public domain** and may be copied and distributed without permission. Please **cite to the Board** as the source of the information."* |
- | **纽约联储** | *"The New York Fed grants you a non-exclusive license… to use, copy, and distribute Content for your **personal or business purposes**. You may: Access the Content, manually or **through an automated process** or device…"* ⚠️ 对外展示或分发参考利率(SOFR / EFFR 等)时**必须附上**这段声明(方括号为原文所有,按原文脚注由使用者填写):*"The [NAME OF DATA or CONTENT] is subject to the Terms of Use posted at newyorkfed.org. The New York Fed is not responsible for publication of the [DATA NAME] by [NAME OF PUBLISHER], does not [sanction] or [endorse] any particular republication, and has no liability for your use."* |
- | **BIS 国际清算银行** | *"The use of the statistics is **unrestricted**, provided that: if the statistics are reproduced, the BIS must be **cited** in your publication or product as the source of the statistics…"* |
- | **欧洲央行 ECB** | *"All publicly available ESCB statistics may be **reused free of charge** on the condition that the source is quoted (e.g. "Source: ECB statistics.") and that the statistics (including metadata) are **not modified**."* |
- | **美国能源信息署 EIA**(库存等 EIA 自己的数据) | *"U.S. government publications are in the **public domain** and are not subject to copyright protection."* 转载时应注明来源与发布日期,如 *"Source: U.S. Energy Information Administration (Oct 2008)."* ⚠️ EIA 网站上转载的第三方数据不在此列,见 B 级的 EIA 现货价格 |
- | **台湾证交所 / 柜买中心 OpenAPI** | **授权**:本工具用到的 13 个数据集都登记在台湾「政府资料开放平台」,授权方式为《政府资料开放授权条款-第1版》:*「授權使用者不限目的、時間及地域、非專屬、不可撤回、免授權金進行利用」*,但须按条款的「显名声明」**注明来源**,否则视为未取得授权。两家网站条款的知识产权一节写明,经授权给政府资料开放平台的资料 *「不在此限」*,同时要求转载 *「清楚註明資料來源,並確保資料完整性,不得任意增刪」*。**程序下载**:网站条款禁止 *「非依(交易所)同意之方式」* 用自动程序下载;两家的 OpenAPI 说明页都写 *「歡迎各位介接使用」*,证交所的还直接链接上述授权条款——官方开放的程序接口即为其同意的方式(本工具的理解)。⚠️ 柜买中心的 OpenAPI 页没有链接授权条款,平台上登记的多是同一份数据的网页下载地址,归 S 级是**本工具的判断**。两家网页上逐股查历史的接口不在此列,本工具不用 |
- | **美国劳工统计局 BLS** | 版权页(Last Modified August 5, 2016):*"everything that we publish, both in hard copy and electronically, is in the **public domain**, except for previously copyrighted photographs and illustrations. You are free to use our public domain material without specific permission, although we do ask that you **cite the Bureau of Labor Statistics** as the source."* API 使用条款(Last Modified August 30, 2023)另要求:*"Users of the public API should **cite the date** that data were accessed or retrieved using the API. Users must clearly state that “BLS.gov cannot vouch for the data or analyses derived from these data after the data have been retrieved from BLS.gov.”"*,*"Users may not modify or falsely represent content accessed through BLS.gov and still cite the source as BLS.gov."*,BLS 徽标不得使用。**硬性限制**:免 key 版每天 25 次请求、每次 25 个序列、10 年;*"If BLS reasonably believes that a user has attempted to exceed or circumvent these limits, that user's access to the API may be permanently or temporarily blocked."* 网站使用政策:*"BLS also reserves the right to block robots that do not contain information that can be used to contact the owner."*(实测不带邮箱的 User-Agent 一律 403,本工具用 `SEC_CONTACT`) |
- | **美国劳工部 ETA**(每周失业金申领) | 劳工部版权页:*"Materials created by the federal government are generally part of the **public domain** and may be used, reproduced and distributed without permission."* 不得以暗示与劳工部有关联或受其认可的方式使用;可注明来源 *"U.S. Department of Labor and/or https://www.dol.gov"* |
- ### B 级 — 数据文件系主动公开,但站点条款含限制
- | 源 | 依据(原文) |
- |---|---|
- | **FINRA** | Reg SHO 每日文件与做空余额(short interest)双周文件都是 FINRA 主动发布供下载的数据文件;但其 Terms of Use 同时禁止 *"use any process to monitor or copy the FINRA Website **in bulk**, or use any **data mining, scraping or harvesting tools (including robots)**"*,且站点声明 *"FINRA Data provides **non-commercial use** of data"*。→ **下载已发布的数据文件属常规用法;批量爬站点页面不属于。商用前请自行向 FINRA 确认。** |
- | **EIA 现货价格**(WTI / 布伦特 / Henry Hub) | EIA 数据说明页写明这些现货价的来源是 *"Refinitiv, an LSEG business"*;EIA 版权页 "Protected materials" 一节:第三方授权给 EIA 的材料,*"Transmission or reproduction of protected items beyond that allowed by fair use… requires the written permission of the copyright owners"*。→ **页面公开、个人研究可用;商用或再分发前请自行确认**(归 B 级是本工具的判断) |
- ### C 级 — 使用需事先授权,或条款未核实
- | 源 | 依据(原文) |
- |---|---|
- | **CBOE**(期权链 6.1 + 波动率指数 6.3) | Use of Content 政策:使用任何 Cboe Content 须 *"receive **approval in advance** from Cboe"*,并须 *"**execution of a license agreement**"*;政策**不区分**商用/非商用、不区分实时/延时。→ **本工具的 CBOE 期权层仅供个人研究;商业用途或再分发前,须先向 Cboe 申请授权。** |
- | 东财 / 新浪 / 腾讯 | 站点前端接口,未见针对接口的公开授权条款。仅供个人研究,勿用于商业产品或再分发 |
- ### D 级 — 条款禁止未经许可的自动抓取(V2.1 复核后新增此级)
- | 源 | 依据(原文) | 本工具里用到它的地方 |
- |---|---|---|
- | **Yahoo Finance** | 条款禁止 *"access or collect data, or attempt to access or collect data, from our Services using **any automated means**, devices, programs, algorithms or methodologies, including but not limited to robots, spiders, scrapers… **for any purpose without our express, prior permission**."* | 美股 K 线备源、**港股 K 线(唯一来源)**、其他市场 K 线、英文关键指标、分析师、机构持仓、期权后备、新闻 |
- | **Nasdaq** | 条款(Last Updated: May 11, 2026)禁止 *"access or use the Service, or **any process, whether automated or manual**, to capture data or content from the Service… for any reason"*,并禁止未经书面许可把内容用于 *"any other form of data analysis software… including, but not limited to, scraping, data mining"*;授权范围 *"solely for your **personal, non-commercial use**"* | Layer 12 财报日历 `earnings_calendar()` |
- > **为什么 D 级保留代码,而 HKEX 直接排除?** 坦白说,两者条款性质相同。区别只在于有没有替代:
- > Yahoo 是本工具港股 K 线、美港以外市场 K 线的唯一来源,Nasdaq 是财报日历唯一免 key 的来源;
- > HKEX CCASS 则是可有可无的增量。所以 D 级代码保留、条款原文照贴——
- > **仅供个人学习研究,风险自负,不得商用或再分发;用不用由你按条款自行判断。**
- ### ⛔ 已排除的源
- | 源 | 原因 |
- |---|---|
- | **HKEX(CCASS 港股席位持股)** | 其 Terms of Use 明文禁止 *"any '**robot**', '**bot**', '**spider**', '**scraper**' or other automated device... to access, obtain, copy, monitor or republish any portion of the Website"*,禁止 *"text or data mining or web scraping"*,且适用于 *"**whether or not for gain**"*(不论是否营利)。→ **本工具不提供 CCASS 抓取代码。** 需要港股席位持股/南向资金数据者,请通过 HKEX 授权渠道或其网页人工查询 |
- ### 给使用者的三条硬规则
- 1. **商业用途**:只依赖 **S 级**(SEC EDGAR / Treasury / CFTC / 美联储 / 纽约联储 / BIS / ECB / EIA 库存 / 台湾证交所 / 柜买中心 / 美国劳工部 BLS 与 ETA),并按各源要求注明来源。B 级需自行确认,C 级须先取得授权,D 级不得商用。
- 2. **再分发**:本工具**只分发代码,不分发任何市场数据**。你也不应把 B/C/D 级源取得的数据对外分发。
- 3. **限速**:所有官方源请求已内置节流(见「官方源统一出口」)。**不要绕过它**——SEC 的 10 req/s 是官方硬上限;BLS 免 key 版每天 25 次,也不要用多个 IP 或进程绕开。
- ---
- ## When to Activate
- - 用户要查**美股/港股**行情(价格/涨跌幅/成交量)
- - 用户要拉 K 线(日线/周线/月线/分钟线)
- - 用户要看**财报**(资产负债表/利润表/现金流量表)
- - 用户要看**关键财务指标**(PE/PB/ROE/利润率/目标价)
- - 用户要看**分析师预期**(EPS预测/评级/目标价区间)
- - 用户要看**机构持仓**(前十大机构/持股比例)
- - 用户要看**资金流向**(主力/大单/中单/小单净流入)
- - 用户要查**期权链**(calls/puts/到期日/Greeks)
- - 用户要查 **SEC Filing**(10-K/10-Q/8-K/年报/季报)
- - 用户要做**美股财报量化分析**(从 XBRL 拉多年营收/净利/EPS 趋势)
- - 用户要**搜索股票**(中英文均可)
- - 用户要看**美股/港股新闻**
- - 用户要看**全市场涨跌幅排名**(当日涨幅/跌幅最大的股票)
- - 用户要做**全市场筛选**(遍历美股/港股列表做初筛)
- - 用户要看**关键财务指标概览**(营收/净利/EPS/ROE/ROA/资产负债率 中文版)
- - 用户要看**技术指标**(MACD/RSI/KDJ/布林带/均线)
- - 用户要判断**金叉死叉/超买超卖/变盘信号**
- - 用户要查**日本/台湾/韩国/印度/欧洲/澳洲/加拿大等市场**的 K 线(Yahoo 换代码后缀)
- - 用户要看**全球央行政策利率**、美联储/欧央行利率、SOFR/EFFR
- - 用户要看**汇率**(欧元或美元对各国货币)、欧元区国债收益率、美国国债拍卖、联邦债务、M1/M2
- - 用户要看 **VIX 恐慌指数**历史、波动率期限结构(正常 / 倒挂)、VVIX / SKEW
- - 用户要看**做空余额**、空头回补天数、轧空候选
- - 用户要看**内部人买卖**(高管 / 董事增减持明细)或**机构 13F 持仓**(如伯克希尔持仓)
- - 用户要查**台股**最新行情、本益比 / 殖利率 / 股价净值比、月营收、融资融券、除权息(官方可商用数据)
- - 用户要看**原油 / 天然气**现货价格或 EIA 每周库存
- - 用户要看**美国 CPI / 核心 CPI、非农、失业率、时薪、PPI、JOLTS 职位空缺、进口价格、ECI、生产率**,或这些数据**下次什么时候发布**、发布后会不会修订
- - 用户要看美国**每周初请 / 续请失业金**人数
- - 关键词:美股、港股、AAPL、苹果、腾讯、00700、TSLA、特斯拉、BABA、阿里巴巴、行情、K线、财报、PE、PB、ROE、分析师、目标价、期权、call、put、SEC、10-K、年报、季报、资金流、主力、机构持仓、新闻、涨幅排名、全市场、筛选、关键指标、MACD、RSI、KDJ、布林带、均线、金叉、死叉、超买、超卖、技术分析、日股、台股、韩股、印度股、欧股、央行、政策利率、加息、降息、SOFR、EFFR、汇率、欧元、日元、收益率曲线、国债拍卖、美债、联邦债务、M2、VIX、恐慌指数、波动率、期限结构、做空余额、空头回补、轧空、内部人、高管减持、Form 4、13F、巴菲特持仓、台积电、台股本益比、月营收、原油、WTI、布伦特、天然气、EIA 库存、美国宏观、CPI、核心CPI、通胀、非农、就业报告、失业率、平均时薪、PPI、JOLTS、职位空缺、初请失业金、续请失业金、ECI、劳动生产率、劳工统计局、BLS、经济数据日历
- ---
- ## Prerequisites
- ```bash
- pip install requests
- # Windows 另装 tzdata,Yahoo K 线才能按交易所时区算日期(Linux / macOS 自带)
- pip install tzdata
- ```
- | 依赖 | 版本要求 | 用途 |
- |------|---------|------|
- | requests | any | 所有 HTTP API 直连 |
- > **极简依赖:** 仅需 requests,所有数据源均为直连 HTTP API,零第三方数据封装。
- ---
- ## 市场代码规则
- ### 东财 secid 前缀(push2/push2his 用)
- | 前缀 | 市场 | 示例 |
- |------|------|------|
- | 105 | 美股 NASDAQ | `105.AAPL`, `105.TSLA` |
- | 106 | 美股 NYSE | `106.BABA`, `106.JD` |
- | 107 | 美股 ETF/其他 | `107.CRSH` |
- | 116 | 港股 | `116.00700`, `116.09988` |
- > **如何判断 105/106/107?** 调 `stock_search()` 获取 `MktNum` 字段自动映射。
- ### Yahoo Finance 代码格式
- | 市场 | 格式 | 示例 |
- |------|------|------|
- | 美股 | 直接 ticker | `AAPL`, `TSLA`, `BABA` |
- | 港股 | 四/五位数字 + `.HK` | `0700.HK`, `9988.HK` |
- | 日本 | 四位代码 + `.T` | `7203.T`(丰田) |
- | 台湾 上市 / 上柜 | 代码 + `.TW` / `.TWO` | `2330.TW`(台积电), `6488.TWO` |
- | 韩国 KOSPI / KOSDAQ | 六位代码 + `.KS` / `.KQ` | `005930.KS`(三星), `247540.KQ` |
- | 印度 NSE | 代码 + `.NS` | `RELIANCE.NS` |
- | 英国 / 德国 / 法国 / 荷兰 / 瑞士 | `.L` / `.DE` / `.PA` / `.AS` / `.SW` | `SHEL.L`, `SAP.DE`, `MC.PA`, `ASML.AS`, `NESN.SW` |
- | 新加坡 / 澳洲 / 加拿大 / 巴西 | `.SI` / `.AX` / `.TO` / `.SA` | `D05.SI`, `BHP.AX`, `RY.TO`, `PETR4.SA` |
- | 主要指数 | `^` 开头 | `^GSPC` 标普 · `^N225` 日经 · `^HSI` 恒指 · `^KS11` · `^TWII` · `^NSEI` · `^FTSE` · `^GDAXI` · `^FCHI` · `^STOXX50E` · `^AXJO` · `^GSPTSE` · `^STI` · `^BVSP` |
- | 汇率 / 期货 | `=X` / `=F` | `JPY=X`(美元兑日元), `GC=F`(黄金), `CL=F`(原油) |
- > 表中 37 个示例代码 2026-10-11 全部实测能取到 K 线。注意:① 价格是**当地货币**,伦敦是**便士**(`SHEL.L` 3793.5 = 37.935 英镑);
- > ② 印度孟买所 `.BO` 实测只返回 1 根 bar,**用 `.NS`**;③ 台股 Yahoo 成交量比台湾证交所自己的数据约少 10%,开高低收一致;
- > ④ A 股 `.SS` / `.SZ` 也能取,但 A 股请用姊妹项目 a-stock-data。⑤ Yahoo 条款禁止未经许可的自动抓取,见「数据源合规分级」。
- ### 东财 datacenter SECUCODE 格式
- | 市场 | 格式 | 示例 |
- |------|------|------|
- | 美股 NASDAQ | `TICKER.O` | `AAPL.O`, `TSLA.O` |
- | 美股 NYSE | `TICKER.N` | `BABA.N`, `JD.N` |
- | 港股 | `CODE.HK` | `00700.HK`, `09988.HK` |
- ---
- ## 共用 Helper 函数
- ### Yahoo Finance crumb 管理器
- Yahoo quoteSummary/options 等 v7/v10 接口需要 cookie+crumb。以下 helper 自动获取并缓存:
- ```python
- import requests
- _yahoo_session = None
- def get_yahoo_session() -> requests.Session:
- """获取带 crumb 的 Yahoo Finance session(自动缓存)"""
- global _yahoo_session
- if _yahoo_session and hasattr(_yahoo_session, '_crumb'):
- return _yahoo_session
- s = requests.Session()
- s.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
- # Step 1: 获取 cookie
- s.get('https://fc.yahoo.com', timeout=10)
- # Step 2: 获取 crumb
- r = s.get('https://query2.finance.yahoo.com/v1/test/getcrumb', timeout=10)
- r.raise_for_status()
- s._crumb = r.text
- _yahoo_session = s
- return s
- def yahoo_quote_summary(symbol: str, modules: list[str]) -> dict:
- """Yahoo quoteSummary 统一查询"""
- s = get_yahoo_session()
- r = s.get(f'https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}', params={
- 'modules': ','.join(modules),
- 'crumb': s._crumb,
- }, timeout=15)
- r.raise_for_status()
- results = r.json().get('quoteSummary', {}).get('result', [{}])
- return results[0] if results else {}
- ```
- ### 东财数据中心统一查询
- ```python
- UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
- DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"
- def eastmoney_datacenter(report_name: str, columns: str = "ALL",
- filter_str: str = "", page_size: int = 50,
- sort_columns: str = "", sort_types: str = "-1") -> list[dict]:
- """东财数据中心统一查询"""
- params = {
- "reportName": report_name, "columns": columns,
- "filter": filter_str, "pageNumber": "1", "pageSize": str(page_size),
- "sortColumns": sort_columns, "sortTypes": sort_types,
- "source": "WEB", "client": "WEB",
- }
- r = requests.get(DATACENTER_URL, params=params, headers={"User-Agent": UA}, timeout=15)
- d = r.json()
- if d.get("result") and d["result"].get("data"):
- return d["result"]["data"]
- return []
- ```
- ---
- ### 官方源统一出口(限流 + UA 声明)— V2.0 新增
- V2.0 起新增的 Layer 9–16 全部走这个出口。它负责三件事:**按源限速**、**SEC / BLS User-Agent 声明**、
- **友好错误提示**。V2.3 起传 `data`(表单)或 `json_body` 时改发 POST(BLS 多序列查询、劳工部申领表单要用)。
- > ⚠️ **使用前必改**:把 `SEC_CONTACT` 换成你自己的真实姓名与邮箱。
- > SEC 官方要求声明 User-Agent,未声明会被判定为 *Undeclared Automated Tool* 并拒绝服务。
- > V2.3 起美国劳工统计局 BLS(Layer 16)也用它:BLS 网站会拦不带联系方式的程序(实测直接 403)。
- ```python
- import requests, re, time, threading
- # ⚠️⚠️ 必改:SEC 要求 UA 含真实联系方式,格式 "Company Name AdminContact@domain.com"
- # V2.3 起 BLS(Layer 16)也用这一行
- SEC_CONTACT = "your-name your-email@example.com"
- class DataNotAvailable(RuntimeError):
- """该日/该标的确实没有数据(如非交易日、文件尚未发布)——可安全回退到下一个候选日。
- 与配置错误、网络错误区分开:后者必须立刻抛给调用方,
- 否则「SEC_CONTACT 没配」会被日期回退循环吞掉,最后伪装成「没找到数据」。
- """
- class _RateLimiter:
- """线程安全的最小间隔节流器(用锁,避免并发下被击穿)"""
- def __init__(self, max_per_sec: float):
- self._interval = 1.0 / float(max_per_sec)
- self._last = 0.0
- self._lock = threading.Lock()
- def wait(self) -> None:
- with self._lock:
- gap = self._interval - (time.monotonic() - self._last)
- if gap > 0:
- time.sleep(gap)
- self._last = time.monotonic()
- # 各源限速:SEC 官方硬上限 10/s,此处取 8/s 留余量;其余为自律保护值
- _LIMITS = {
- "sec.gov": _RateLimiter(8),
- "finra.org": _RateLimiter(4),
- "cboe.com": _RateLimiter(4),
- "nasdaq.com": _RateLimiter(2),
- "bls.gov": _RateLimiter(2), # BLS 官方上限 50 次 / 10 秒;免 key 版另有每天 25 次(见 Layer 16)
- "doleta.gov": _RateLimiter(2),
- "_default": _RateLimiter(5),
- }
- def _limiter_for(url: str) -> _RateLimiter:
- for host, lim in _LIMITS.items():
- if host != "_default" and host in url:
- return lim
- return _LIMITS["_default"]
- def _is_object_missing(resp) -> bool:
- """
- 正向识别「资源确实不存在」。
- ⚠️ SEC Archives 与 FINRA CDN 都托管在 S3 上,而 S3 在调用方没有
- ListBucket 权限时,对**不存在的对象**返回 `403 AccessDenied`(XML)
- 而不是 404 NoSuchKey。实测 2026-07-24 两个源行为一致。
- 真正的拒绝长得完全不同(SEC 的 UA 未声明返回 ~4.8KB HTML 页面),
- 所以这里按 Content-Type + XML 错误码正向判定,
- 而不是用「排除法」——否则限流/封禁会被伪装成「没数据」。
- """
- if resp.status_code == 404:
- return True
- if resp.status_code != 403:
- return False
- ctype = (resp.headers.get("Content-Type") or "").lower()
- head = (resp.text or "")[:500]
- return "xml" in ctype and "<Code>AccessDenied</Code>" in head
- def official_get(url: str, params: dict = None, headers: dict = None,
- timeout: int = 30, as_json: bool = False, raw: bool = False,
- data: dict = None, json_body: dict = None):
- """
- V2.0 官方源统一出口:自动节流 + UA 处理 + 友好错误。
- as_json=True 返回 dict,raw=True 返回 bytes(XML 不声明字符集时用),否则返回 str。
- data / json_body:给了任一个就改发 POST(表单 / JSON),V2.3 新增。
- 异常语义:资源不存在 → DataNotAvailable(调用方可回退到下一个候选日);
- 配置/限流/网络 → RuntimeError(必须冒泡)。
- """
- if "sec.gov" in url or "bls.gov" in url:
- if "your-email@example.com" in SEC_CONTACT:
- raise RuntimeError(
- "请先把 SEC_CONTACT 改成你的真实姓名与邮箱 —— SEC 与 BLS 都要求程序在 "
- "User-Agent 里留联系方式:SEC 不留返回 Undeclared Automated Tool 错误,BLS 网站直接 403。")
- h = {"User-Agent": SEC_CONTACT, "Accept-Encoding": "gzip, deflate"}
- else:
- h = {"User-Agent": UA}
- h.update(headers or {})
- _limiter_for(url).wait()
- try:
- if data is not None or json_body is not None:
- r = requests.post(url, params=params, data=data, json=json_body, headers=h, timeout=timeout)
- else:
- r = requests.get(url, params=params, headers=h, timeout=timeout)
- r.raise_for_status()
- except requests.HTTPError as e:
- resp = e.response
- code = resp.status_code
- low = (resp.text or "")[:4000].lower()
- # ① 正向识别:资源确实不存在(404,或 S3 风格的 403 AccessDenied)
- if _is_object_missing(resp):
- raise DataNotAvailable(
- f"HTTP {code} {url[:80]} — 资源不存在(该日无数据/尚未发布)") from e
- # ② SEC 的 UA 未声明(返回 HTML 页,含 Undeclared Automated Tool)
- if code == 403 and "undeclared" in low:
- raise RuntimeError(
- f"SEC 拒绝请求:User-Agent 未被识别为已声明。"
- f"当前 SEC_CONTACT={SEC_CONTACT!r},"
- f"格式应为 'Company Name AdminContact@domain.com'") from e
- # ②b BLS 拦截不带联系方式的程序,也会临时封请求过快的地址
- if code == 403 and "bls.gov" in url:
- raise RuntimeError(
- f"BLS 拒绝请求(HTTP 403):请确认 SEC_CONTACT 里是真实邮箱(当前 {SEC_CONTACT!r});"
- f"也可能是请求太频繁被临时封,稍后再试") from e
- # ③ 其余一律视为真错误,必须冒泡(限流/封禁/权限/接口变更)
- body = re.sub(r"\s+", " ", re.sub(r"(?s)<(script|style).*?</\1>|<[^>]+>", " ", resp.text or "")).strip()
- hint = {400: "参数错误:" + (body[:200] or "(官方未给原因)"),
- 403: "被拒绝:限流、封禁或权限问题(已排除「资源不存在」)",
- 404: "端点不存在:接口可能已变更",
- 429: "请求过快:已内置节流,若仍触发请调低 _LIMITS"}.get(code, "")
- raise RuntimeError(f"HTTP {code} {url[:80]} — {hint}") from e
- except requests.RequestException as e:
- raise RuntimeError(f"请求失败 {url[:80]} — {type(e).__name__}: {e}") from e
- return r.json() if as_json else (r.content if raw else r.text)
- # ── 异常约定(V2.0)──
- # DataNotAvailable : 该日/该标的确实没有数据(非交易日、文件未发布、标的无期权…)
- # → 调用方可安全回退到下一个候选日
- # RuntimeError : 配置错误(SEC_CONTACT 未改)、限流、网络故障
- # → 必须冒泡给使用者,不可伪装成「没数据」
- # ValueError : 参数错误(如把港股代码传给仅支持美股的层)
- def assert_us_ticker(ticker: str) -> str:
- """Layer 6.1 / 9 / 10 / 11 仅支持美股;传入港股代码时给出明确提示"""
- t = str(ticker).upper()
- if t.endswith(".HK") or (t.isdigit() and len(t) in (4, 5)):
- raise ValueError(f"'{ticker}' 看起来是港股代码;该层仅支持美股。"
- f"港股请用 Layer 1-5 的港股端点。")
- if not t.replace(".", "").replace("-", "").isalnum():
- raise ValueError(f"无效的 ticker: '{ticker}'")
- return t
- ```
- > `requests` 会自动解压 gzip 响应,因此上面带 `Accept-Encoding` 是安全的。
- > 若你改用 `urllib` 自行实现,**必须手动 `gzip.decompress`**,否则 SEC 返回的内容会解析失败。
- ---
- ## Layer 1: 行情层
- ### 1.1 美股实时行情 — 新浪 + 腾讯
- 两个独立数据源,任一可用即可。新浪字段侧重价格成交,腾讯字段更全(含52周高低/市值/PE)。
- ```python
- import requests, re
- def us_stock_quote_sina(ticker: str) -> dict:
- """
- 新浪美股行情 — 36字段
- ticker: 纯字母,如 "AAPL", "TSLA", "BABA"
- """
- url = f"https://hq.sinajs.cn/list=gb_{ticker.lower()}"
- r = requests.get(url, headers={
- "Referer": "https://finance.sina.com.cn/",
- "User-Agent": UA,
- }, timeout=10)
- r.encoding = "gbk"
- text = r.text
- m = re.search(r'"(.+)"', text)
- if not m:
- return {}
- fields = m.group(1).split(",")
- if len(fields) < 30:
- return {}
- return {
- "name": fields[0], # 中文名
- "price": float(fields[1]), # 最新价
- "change_pct": float(fields[2]), # 涨跌幅 %
- "timestamp": fields[3], # 时间
- "prev_close": float(fields[26]), # 昨收
- "open": float(fields[5]), # 开盘
- "high": float(fields[6]), # 最高
- "low": float(fields[7]), # 最低
- "volume": float(fields[10]) if fields[10] else 0, # 成交量
- "high_52w": float(fields[8]) if fields[8] else 0, # 52周最高
- "low_52w": float(fields[9]) if fields[9] else 0, # 52周最低
- "market_cap": float(fields[12]) if fields[12] else 0, # 市值
- "eps": float(fields[13]) if fields[13] else 0, # EPS
- "pe": float(fields[14]) if fields[14] else 0, # PE
- }
- def us_stock_quote_tencent(ticker: str) -> dict:
- """
- 腾讯美股行情 — 71字段
- ticker: 纯字母,如 "AAPL"
- """
- url = f"https://qt.gtimg.cn/q=us{ticker.upper()}"
- r = requests.get(url, timeout=10)
- r.encoding = "gbk"
- text = r.text
- m = re.search(r'"(.+)"', text)
- if not m:
- return {}
- fields = m.group(1).split("~")
- if len(fields) < 52: # 需读到 fields[51](PB),美股正常返回 71 个
- return {}
- # ⚠️ 下标以实测为准,勿照抄港股那套(两市布局不同,见本节末「腾讯行情字段对照表」)
- return {
- "name": fields[1], # 中文名
- "name_en": fields[46], # 英文名,如 "Apple Inc."
- "price": float(fields[3]) if fields[3] else 0,
- "prev_close": float(fields[4]) if fields[4] else 0,
- "open": float(fields[5]) if fields[5] else 0,
- "volume": int(float(fields[6])) if fields[6] else 0,
- "high": float(fields[33]) if fields[33] else 0,
- "low": float(fields[34]) if fields[34] else 0,
- "high_52w": float(fields[48]) if fields[48] else 0,
- "low_52w": float(fields[49]) if fields[49] else 0,
- "change_pct": float(fields[32]) if fields[32] else 0,
- "float_market_cap": float(fields[44]) if fields[44] else 0, # 流通市值,亿美元
- "market_cap": float(fields[45]) if fields[45] else 0, # 总市值,亿美元
- "eps": float(fields[47]) if fields[47] else 0,
- "pe": float(fields[39]) if fields[39] else 0,
- "pb": float(fields[51]) if fields[51] else 0,
- "currency": fields[35], # "USD"
- "timestamp": fields[30],
- }
- ```
- ### 1.2 港股实时行情 — 腾讯 + 新浪
- ```python
- def hk_stock_quote_tencent(code: str) -> dict:
- """
- 腾讯港股行情 — 78字段(最全)
- code: 五位数字,如 "00700", "09988"
- """
- url = f"https://qt.gtimg.cn/q=r_hk{code}"
- r = requests.get(url, timeout=10)
- r.encoding = "gbk"
- text = r.text
- m = re.search(r'"(.+)"', text)
- if not m:
- return {}
- fields = m.group(1).split("~")
- if len(fields) < 76: # 需读到 fields[75](币种),港股正常返回 78 个
- return {}
- # ⚠️ 下标以实测为准,与美股那套不同(见本节末「腾讯行情字段对照表」)
- return {
- "name": fields[1], # 中文名
- "code": fields[2], # 五位代码,如 "00700"(旧版误当英文名)
- "name_en": fields[46], # 英文名,如 "TENCENT"
- "price": float(fields[3]) if fields[3] else 0,
- "prev_close": float(fields[4]) if fields[4] else 0,
- "open": float(fields[5]) if fields[5] else 0,
- "high": float(fields[33]) if fields[33] else 0,
- "low": float(fields[34]) if fields[34] else 0,
- "volume": int(float(fields[6])) if fields[6] else 0, # 成交量(股)
- "amount": float(fields[37]) if fields[37] else 0, # 成交额
- "change_pct": float(fields[32]) if fields[32] else 0,
- "pe": float(fields[39]) if fields[39] else 0,
- "pb": float(fields[58]) if fields[58] else 0,
- "high_52w": float(fields[48]) if fields[48] else 0,
- "low_52w": float(fields[49]) if fields[49] else 0,
- "float_market_cap": float(fields[44]) if fields[44] else 0, # 流通市值,亿港元
- "market_cap": float(fields[45]) if fields[45] else 0, # 总市值,亿港元
- "currency": fields[75], # "HKD"
- "timestamp": fields[30],
- }
- def hk_stock_quote_sina(code: str) -> dict:
- """
- 新浪港股行情 — 25字段
- code: 五位数字,如 "00700"
- """
- url = f"https://hq.sinajs.cn/list=rt_hk{code}"
- r = requests.get(url, headers={
- "Referer": "https://finance.sina.com.cn/",
- "User-Agent": UA,
- }, timeout=10)
- r.encoding = "gbk"
- text = r.text
- m = re.search(r'"(.+)"', text)
- if not m:
- return {}
- fields = m.group(1).split(",")
- if len(fields) < 15:
- return {}
- return {
- "name_en": fields[0],
- "name": fields[1], # 中文名
- "open": float(fields[2]) if fields[2] else 0,
- "prev_close": float(fields[3]) if fields[3] else 0,
- "high": float(fields[4]) if fields[4] else 0,
- "low": float(fields[5]) if fields[5] else 0,
- "price": float(fields[6]) if fields[6] else 0,
- "change": float(fields[7]) if fields[7] else 0,
- "change_pct": float(fields[8]) if fields[8] else 0,
- "volume": float(fields[12]) if fields[12] else 0,
- "amount": float(fields[11]) if fields[11] else 0,
- }
- ```
- #### 腾讯行情字段对照表(`qt.gtimg.cn` · 2026-07-26 实测校准)
- ⚠️ **美股与港股的字段布局不同,不能共用一套下标。** 美股返回 71 个字段,港股 78 个。
- 下面每个下标都以真实响应逐个核对过(`usAAPL` / `hk00700`),网上流传的映射表多处有误。
- | 含义 | 美股下标 | 港股下标 | 实测值(AAPL / 00700) |
- |---|---|---|---|
- | 中文名 | 1 | 1 | 苹果 / 腾讯控股 |
- | 代码 | 2 | 2 | AAPL.OQ / 00700 |
- | **英文名** | **46** | **46** | Apple Inc. / TENCENT |
- | 现价 | 3 | 3 | 333.02 / 434.600 |
- | 昨收 / 今开 | 4 / 5 | 4 / 5 | — |
- | 成交量 | 6 | 6 | ⚠️ 港股带小数位(`22959603.0`),必须 `int(float(x))` |
- | 涨跌幅 % | 32 | 32 | 3.53 / -2.38 |
- | 当日最高 / 最低 | 33 / 34 | 33 / 34 | — |
- | **币种** | **35** | **75** | USD / HKD |
- | **PE** | **39** | **39** | 40.32 / 15.87 |
- | **流通市值**(亿本币) | **44** | **44** | 48881.62 / 39516.08 |
- | **总市值**(亿本币) | **45** | **45** | 48911.83 / 39516.08 |
- | EPS | 47 | — | 8.26(333.02 ÷ 8.26 = 40.32 ✓ 与 PE 自洽) |
- | **52 周最高 / 最低** | **48 / 49** | **48 / 49** | 334.99·200.72 / 677.7·411.0 |
- | **PB** | **51** | **58** | 45.93 / 3.14 |
- **市值单位是「亿本币」,不是股数**:AAPL 总市值 48911.83(亿美元)= 现价 333.02 × 总股本 14,687,356,000,可用 `fields[62]` 的总股本反算核对。港股同理,单位为亿港元。
- **自行复现命令**(行号 N ↔ 数组下标 N−1):
- ```bash
- curl -s "https://qt.gtimg.cn/q=usAAPL" | iconv -f GBK -t UTF-8 | tr '~' '\n' | cat -n
- curl -s "https://qt.gtimg.cn/q=hk00700" | iconv -f GBK -t UTF-8 | tr '~' '\n' | cat -n
- ```
- > 港股 `hk` 与 `r_hk` 两种前缀返回的字段布局完全一致(均 78 个),可互换。
- > 感谢 [@HoRiZonn0](https://github.com/HoRiZonn0) 在 issue #2 中提供的完整对照,本表据此逐条复测后修订。
- ### 1.3 东财 push2 实时行情 — 美股 + 港股
- 东财 push2 接口,通过 secid 统一查询美股/港股实时行情。优点:有中文名、换手率、涨跌幅,且 secid 可由 `stock_search()` 自动获取。
- ```python
- def stock_quote_eastmoney(ticker_or_code: str, secid_prefix: int = 105) -> dict:
- """
- 东财 push2 实时行情 — 美股+港股统一接口
- 美股: stock_quote_eastmoney("AAPL", 105) # NASDAQ
- stock_quote_eastmoney("BABA", 106) # NYSE
- 港股: stock_quote_eastmoney("00700", 116)
- 返回: 最新价/开高低收/成交量/成交额/换手率/涨跌幅/中文名
- secid_prefix 说明: 105=NASDAQ, 106=NYSE, 107=US_ETF, 116=港股
- 如不确定前缀,先调 stock_search() 获取 mkt_num
- """
- url = "https://push2.eastmoney.com/api/qt/stock/get"
- params = {
- "secid": f"{secid_prefix}.{ticker_or_code}",
- "fields": "f43,f44,f45,f46,f47,f48,f55,f57,f58,f59,f60,f170",
- }
- r = requests.get(url, params=params, timeout=10)
- d = r.json().get("data")
- if not d:
- return {}
- # f59 = 小数位数, 价格字段需除以 10^f59 还原真实值
- dec = d.get("f59", 3)
- divisor = 10 ** dec
- def _p(key):
- v = d.get(key)
- if v is None or v == "-":
- return None
- return round(v / divisor, dec)
- return {
- "code": d.get("f57"), # 股票代码
- "name": d.get("f58"), # 中文名
- "price": _p("f43"), # 最新价
- "high": _p("f44"), # 最高
- "low": _p("f45"), # 最低
- "open": _p("f46"), # 开盘
- "volume": d.get("f47"), # 成交量(股)
- "amount": d.get("f48"), # 成交额
- "turnover_rate": d.get("f55"), # 换手率(%)
- "prev_close": _p("f60"), # 昨收
- "change_pct": round(d["f170"] / 100, 2) if d.get("f170") is not None else None, # 涨跌幅(%)
- }
- ```
- ---
- ## Layer 2: K线层
- ### 2.1 美股 K 线 — 新浪(主)+ Yahoo(备)
- 两个独立数据源。新浪最长可回溯到 1984 年;Yahoo 带复权收盘 `adj_close`(含分红),支持周/月/分钟线和按起止日期取。
- > ⚠️ **V2.1 修复**:旧版 `range_="max"` 拿到的是季线/月线却标成日线,日期还随使用者电脑时区漂移(在纽约看港股会早一天),周/月线末尾还多出一根只含最新一天的 bar。现已全部修正;周/月/季线改由日线按交易所当地日历合并,详见 CHANGELOG。
- > **注意:** 东财 push2his kline/get 端点实测不返回美股/港股数据(2026-05-20 验证),仅支持 A 股。美股/港股 K 线用新浪和 Yahoo。
- ```python
- def us_stock_kline_sina(ticker: str, num: int = 120) -> list[dict]:
- """
- 新浪美股日K — 可回溯到1984年
- ticker: 如 "AAPL"
- 返回: [{date, open, high, low, close, volume}, ...]
- """
- url = "https://stock.finance.sina.com.cn/usstock/api/jsonp.php/var/US_MinKService.getDailyK"
- params = {"symbol": ticker.upper(), "num": num}
- r = requests.get(url, params=params, headers={"Referer": "https://finance.sina.com.cn/"}, timeout=15)
- text = r.text
- # 解析 JSONP: var=([{...},...])
- import json
- m = re.search(r'\((\[.+\])\)', text)
- if not m:
- return []
- items = json.loads(m.group(1))
- result = []
- for item in items:
- result.append({
- "date": item.get("d"),
- "open": float(item.get("o", 0)),
- "high": float(item.get("h", 0)),
- "low": float(item.get("l", 0)),
- "close": float(item.get("c", 0)),
- "volume": int(item.get("v", 0)),
- })
- return result
- _YAHOO_INTRADAY = {"1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "4h"}
- def _yahoo_exchange_tz(meta: dict, intraday: bool):
- """K 线日期按交易所当地时间算,与使用者电脑的时区无关。"""
- from datetime import timedelta, timezone
- try:
- from zoneinfo import ZoneInfo # Python 3.9+;Windows 需另装 tzdata
- return ZoneInfo(meta["exchangeTimezoneName"]), 0
- except Exception:
- # 退回固定偏移:gmtoffset 是「当前」偏移,跨夏令时会差 1 小时。
- # 日/周/月线的时间戳落在当地 00:00–16:00 之间,再加 3 小时可吸收这 1 小时误差。
- tz = timezone(timedelta(seconds=meta.get("gmtoffset") or 0))
- return tz, (0 if intraday else 3 * 3600)
- def _yahoo_range_start(range_: str):
- """range_ → 起始日(UTC 日期),供周/月/季线换算成起止日期用"""
- import calendar
- from datetime import datetime, timedelta, timezone
- today = datetime.now(timezone.utc).date()
- if range_ == "ytd":
- return today.replace(month=1, day=1)
- m = re.fullmatch(r"(\d+)(d|mo|y)", str(range_))
- if not m:
- raise ValueError(f"range_ 取 1d/5d/1mo/3mo/6mo/1y/2y/5y/10y/ytd/max,收到 {range_!r}")
- n, unit = int(m.group(1)), m.group(2)
- if unit == "d":
- return today - timedelta(days=n)
- k = today.year * 12 + today.month - 1 - n * (12 if unit == "y" else 1)
- y, m = k // 12, k % 12 + 1
- return today.replace(year=y, month=m, day=min(today.day, calendar.monthrange(y, m)[1]))
- def stock_kline_yahoo(symbol: str, interval: str = "1d", range_: str = "6mo",
- start: str = None, end: str = None) -> list[dict]:
- """
- Yahoo Finance chart API — 美股/港股及其他市场通用,零crumb
- symbol: "AAPL" (美股) / "0700.HK" (港股) / 其他市场后缀见「市场代码规则」
- interval: "1d", "1wk", "1mo", "3mo", "1m", "2m", "5m", "15m", "30m", "90m", "1h", "4h"
- range_: "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"
- start / end: "YYYY-MM-DD"(按交易所当地日期),给了任一个就按起止日期取(忽略 range_);
- 只给 end = 从最早一根取到 end。日线、分钟线含 start、end 当天
- 返回: [{date, open, high, low, close, volume, adj_close?}, ...];区间内没有交易返回 []
- 周/月/季线由日线按交易所当地日历合并(日期标签是周期第一天:周一 / 每月 1 日 / 每季第一天,
- 与 Yahoo 原生标签一致)。每一根都是完整周期:start 所在周期从第一天算起,end 所在周期算到最后一天,
- 还没走完的当期只到最新交易日。range_ 同理:会补齐第一个周期(如 2y 月线 = 25 根)。
- 不直接用 Yahoo 原生周/月/季线,是因为它在节假日开头的那一周会拿上一周的收盘价当开盘价(实测东京、
- 香港、伦敦),按 start/end 截取时周线会多算或少算一天、季线分组跟着起始日漂移,末尾还会多一根只含最新一天的 bar。
- ⚠️ Yahoo 的 range=max 会无视 interval,按标的年限退成月线或季线
- (实测 AAPL 返回 169 根季线、0700.HK 270 根月线),所以 "max" 在这里改用起止时间请求,
- 日线可拿到上市以来全部(AAPL 1980 起 11,549 根)。分钟线 Yahoo 只给最近 60 天(1h / 4h 为 730 天;
- 1m 为 30 天且一次最多取约 7 天;2m 实测只有最近约 30 个交易日,更早的返回 []),不支持 "max";
- 在这个窗口内可以用 start/end。start 落在窗口第一天时,只返回窗口内的那一段。
- """
- import time
- from datetime import datetime, timedelta, timezone
- intraday = interval in _YAHOO_INTRADAY
- def _day(s, name):
- try:
- return datetime.strptime(s, "%Y-%m-%d").replace(tzinfo=timezone.utc)
- except (TypeError, ValueError):
- raise ValueError(f"{name} 要写成 YYYY-MM-DD,收到 {s!r}") from None
- d0 = _day(start, "start") if start else None
- d1 = _day(end, "end") if end else None
- if d0 and d1 and d0 > d1:
- raise ValueError(f"start {start} 晚于 end {end}")
- # 当地日期最多比 UTC 日期早一天(新西兰开盘时 UTC 还是前一天),超过一天才算未来
- if d0 and d0.timestamp() - 86400 > time.time():
- raise ValueError(f"start {start} 在未来")
- if interval in ("1wk", "1mo", "3mo"):
- def _first(d): # d 所在周期的第一天
- if interval == "1wk":
- return d - timedelta(days=d.weekday())
- return d.replace(month=(d.month - 1) // (3 if interval == "3mo" else 1)
- * (3 if interval == "3mo" else 1) + 1, day=1)
- def _next(d): # 下一个周期的第一天
- if interval == "1wk":
- return d + timedelta(days=7)
- k = d.year * 12 + d.month - 1 + (3 if interval == "3mo" else 1)
- return d.replace(year=k // 12, month=k % 12 + 1, day=1)
- if not (d0 or d1) and range_ != "max":
- d0 = datetime.combine(_yahoo_range_start(range_), datetime.min.time(), timezone.utc)
- s0 = _first(d0.date()).isoformat() if d0 else None
- s1 = (_next(_first(d1.date())) - timedelta(days=1)).isoformat() if d1 else None
- daily = stock_kline_yahoo(symbol, "1d", range_="max", start=s0, end=s1)
- bars = {}
- for x in daily:
- k = _first(datetime.strptime(x["date"], "%Y-%m-%d").date()).isoformat()
- b = bars.get(k)
- if b is None:
- bars[k] = dict(x, date=k)
- continue
- b["high"] = max(v for v in (b["high"], x["high"]) if v is not None) \
- if (b["high"] is not None or x["high"] is not None) else None
- b["low"] = min(v for v in (b["low"], x["low"]) if v is not None) \
- if (b["low"] is not None or x["low"] is not None) else None
- b["close"] = x["close"]
- b["volume"] += x["volume"]
- if "adj_close" in x:
- b["adj_close"] = x["adj_close"]
- return list(bars.values())
- lo = d0.strftime("%Y-%m-%d") if d0 else None
- hi = d1.strftime("%Y-%m-%d") if d1 else None
- params = {"interval": interval, "events": "div,split"}
- if d0 or d1:
- # 起点往前放宽:亚太的时间戳落在 UTC 前一天(东京 00:00Z、悉尼 23:00Z、新西兰最早 21:00Z),
- # 分钟线只放宽 14 小时,免得把 60 天窗口的第一天挤出去。终点:日线放宽 2 天;分钟线放宽 30 小时——
- # 期货(CL=F 等)按纽约时间交易到当地午夜,即 UTC 次日 04:00–05:00;不放宽 2 天是给 1m 的 8 天上限留余量。
- # 精确范围由下面按交易所当地日期再筛
- pad = timedelta(hours=14) if intraday else timedelta(days=1)
- params["period1"] = int((d0 - pad).timestamp()) if d0 else -2208988800 # 1900-01-01
- if intraday: # 放宽的部分不能超出 Yahoo 的分钟线窗口,否则整个请求被拒
- days = {"1m": 30, "60m": 730, "1h": 730, "4h": 730}.get(interval, 60)
- edge = int(time.time()) - days * 86400 + 600
- for d, name, v in ((d0, "start", start), (d1, "end", end)):
- if d and d.timestamp() + 86400 <= edge:
- raise ValueError(f"{interval} 线 Yahoo 只给最近 {days} 天,{name} {v} 超出范围")
- params["period1"] = max(params["period1"], edge)
- tail = timedelta(hours=30) if intraday else timedelta(days=2)
- params["period2"] = min(int((d1 + tail).timestamp()) if d1 else 2**31, int(time.time()))
- if params["period1"] >= params["period2"]:
- return [] # start 是今天或明天(按 UTC),还没有成交
- if interval == "1m" and params["period2"] - params["period1"] > 8 * 86400:
- raise ValueError("1m 线 Yahoo 一次最多取约 7 天,请同时给 start 和 end,跨度不超过 7 天")
- elif range_ == "max":
- if intraday:
- raise ValueError("分钟/小时线没有全部历史(Yahoo 分钟线只给最近 60 天,1m 30 天,1h / 4h 730 天),请用 range_ 或 start/end")
- params["period1"], params["period2"] = -2208988800, int(time.time())
- else:
- params["range"] = range_
- url = f"https://query2.finance.yahoo.com/v8/finance/chart/{symbol}"
- r = requests.get(url, params=params, timeout=20, headers={
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"})
- if r.status_code == 404:
- raise ValueError(f"Yahoo 找不到 {symbol!r}(代码不对或已退市)")
- if r.status_code in (400, 422): # 参数不被接受(如分钟线超出 60 天窗口)
- try:
- desc = ((r.json().get("chart") or {}).get("error") or {}).get("description")
- except ValueError:
- desc = None
- if desc and desc.startswith("Data doesn't exist"):
- return [] # 区间早于上市或晚于最新交易日,和节假日一样视为「没有交易」
- raise ValueError(f"Yahoo 拒绝该请求:{desc or r.text[:200]}")
- r.raise_for_status()
- chart = ((r.json().get("chart") or {}).get("result") or [None])[0] or {}
- meta = chart.get("meta") or {}
- timestamps = chart.get("timestamp") or []
- indicators = chart.get("indicators") or {}
- quote = (indicators.get("quote") or [{}])[0]
- adj = ((indicators.get("adjclose") or [{}])[0]).get("adjclose")
- tz, nudge = _yahoo_exchange_tz(meta, intraday)
- live_ts = meta.get("regularMarketTime")
- fmt = "%Y-%m-%d %H:%M" if intraday else "%Y-%m-%d"
- def _local(ts):
- # 最新一根的时间戳是真实成交时间,用当前偏移换算本来就准,不加修正量
- return datetime.fromtimestamp(ts + (0 if ts == live_ts else nudge), tz)
- def _v(key, i):
- x = (quote.get(key) or [None] * len(timestamps))[i]
- # Yahoo 内部按单精度存价格(7786.36 会变成 7786.3599…),保留 7 位有效数字去掉噪声;
- # 不能一律只留 2 位小数——港股仙股、汇率有 3 位以上小数
- return float(f"{x:.7g}") if x is not None else None
- result = []
- for i, ts in enumerate(timestamps):
- close = _v("close", i)
- if close is None: # 停牌/缺失的 bar 直接跳过,不用 0 冒充价格
- continue
- row = {
- "date": _local(ts).strftime(fmt),
- "open": _v("open", i), "high": _v("high", i), "low": _v("low", i),
- "close": close,
- "volume": int((quote.get("volume") or [0] * len(timestamps))[i] or 0),
- }
- if adj and adj[i] is not None:
- row["adj_close"] = float(f"{adj[i]:.7g}") # 含分红再投资的复权收盘
- if (hi and row["date"][:10] > hi) or (lo and row["date"][:10] < lo):
- continue
- if result and result[-1]["date"] == row["date"]:
- result[-1] = row # 盘中最后一根偶尔与上一根同日,保留较新的
- else:
- result.append(row)
- return result
- ```
- ### 2.2 港股 K 线 — Yahoo(唯一可用源)
- 港股 K 线只有 Yahoo 一个可用源(新浪港股K线已失效,东财 push2his 不返回港股K线数据)。
- ```python
- # 港股 Yahoo K线: 直接调 stock_kline_yahoo("0700.HK");全部历史 stock_kline_yahoo("0700.HK", range_="max")
- ```
- ### 2.3 其他市场 K 线 — Yahoo(同一函数,换代码后缀)
- `stock_kline_yahoo()` 不限美港:日本、台湾、韩国、印度、欧洲、新加坡、澳洲、加拿大、巴西的个股和主要指数
- 都能取,代码规则见「市场代码规则 → Yahoo Finance 代码格式」。`key_statistics()` 等 Yahoo quoteSummary 函数同样认这些代码。
- > ⚠️ **合规**:Yahoo 条款禁止未经许可的自动抓取(原文见「数据源合规分级」)。本节只是说明现有函数能认哪些代码,
- > 仅供个人学习研究,风险自负,不得商用或再分发。台股要可商用的数据,用 Layer 14 证交所 / 柜买中心 OpenAPI(只有最新一天)。
- **实测(2026-10-11,`range_="max"` 日线)**:丰田 7203.T 1999 起 6,851 根 · 台积电 2330.TW 2000 起 · 三星 005930.KS 2000 起 ·
- Reliance RELIANCE.NS 1996 起 · SAP.DE 1998 起 · BHP.AX 1988 起 · 日经 ^N225 1965 起 15,183 根 · 标普 ^GSPC 1927 起 24,811 根。
- ---
- ## Layer 3: 技术指标层
- 基于 K 线 OHLCV 数据的纯 Python 技术指标计算,零额外依赖。
- **使用方式:** 先调 K 线函数获取数据,再传入技术指标函数:
- ```python
- klines = us_stock_kline_sina("AAPL", 120)
- macd = calc_macd(klines)
- rsi = calc_rsi(klines)
- ```
- ### 3.1 移动平均线 MA / EMA
- ```python
- def _ema(values: list[float], period: int) -> list[float]:
- """EMA 指数移动平均(内部辅助)"""
- result = [values[0]]
- k = 2 / (period + 1)
- for v in values[1:]:
- result.append(v * k + result[-1] * (1 - k))
- return result
- def calc_ma(klines: list[dict], periods: list[int] = None) -> list[dict]:
- """
- 移动平均线 MA + EMA
- klines: K线数据 [{date, open, high, low, close, volume}, ...]
- periods: 周期列表,默认 [5, 10, 20, 60]
- 返回: [{date, close, ma5, ma10, ma20, ma60, ema12, ema26}, ...]
- """
- if periods is None:
- periods = [5, 10, 20, 60]
- closes = [k["close"] for k in klines]
- # EMA 12/26(MACD 常用)
- ema12 = _ema(closes, 12)
- ema26 = _ema(closes, 26)
- result = []
- for i, k in enumerate(klines):
- row = {"date": k["date"], "close": k["close"]}
- for p in periods:
- if i >= p - 1:
- row[f"ma{p}"] = round(sum(closes[i - p + 1:i + 1]) / p, 4)
- else:
- row[f"ma{p}"] = None
- row["ema12"] = round(ema12[i], 4)
- row["ema26"] = round(ema26[i], 4)
- result.append(row)
- return result
- ```
- ### 3.2 MACD
- ```python
- def calc_macd(klines: list[dict], fast: int = 12, slow: int = 26,
- signal: int = 9) -> list[dict]:
- """
- MACD (Moving Average Convergence Divergence)
- klines: K线数据
- fast/slow/signal: 快线/慢线/信号线周期(默认 12/26/9)
- 返回: [{date, close, dif, dea, macd_hist}, ...]
- dif = EMA(fast) - EMA(slow) 金叉/死叉看 dif 穿越 dea
- dea = EMA(signal) of dif 信号线
- macd_hist = (dif - dea) * 2 柱状图(红涨绿跌)
- """
- closes = [k["close"] for k in klines]
- ema_fast = _ema(closes, fast)
- ema_slow = _ema(closes, slow)
- dif = [round(f - s, 4) for f, s in zip(ema_fast, ema_slow)]
- dea = _ema(dif, signal)
- result = []
- for i, k in enumerate(klines):
- result.append({
- "date": k["date"],
- "close": k["close"],
- "dif": round(dif[i], 4),
- "dea": round(dea[i], 4),
- "macd_hist": round((dif[i] - dea[i]) * 2, 4),
- })
- return result
- ```
- ### 3.3 RSI
- ```python
- def calc_rsi(klines: list[dict],
- periods: list[int] = None) -> list[dict]:
- """
- RSI (Relative Strength Index)
- klines: K线数据
- periods: 周期列表(默认 [6, 12, 24])
- 返回: [{date, close, rsi6, rsi12, rsi24}, ...]
- RSI > 70 超买区(可能回调)
- RSI < 30 超卖区(可能反弹)
- """
- if periods is None:
- periods = [6, 12, 24]
- closes = [k["close"] for k in klines]
- # 涨跌额序列
- changes = [0.0] + [closes[i] - closes[i - 1] for i in range(1, len(closes))]
- gains = [max(c, 0) for c in changes]
- losses = [max(-c, 0) for c in changes]
- result = []
- for i, k in enumerate(klines):
- row = {"date": k["date"], "close": k["close"]}
- for p in periods:
- if i < p:
- row[f"rsi{p}"] = None
- continue
- avg_gain = sum(gains[i - p + 1:i + 1]) / p
- avg_loss = sum(losses[i - p + 1:i + 1]) / p
- if avg_loss == 0:
- row[f"rsi{p}"] = 100.0
- else:
- rs = avg_gain / avg_loss
- row[f"rsi{p}"] = round(100 - 100 / (1 + rs), 2)
- result.append(row)
- return result
- ```
- ### 3.4 KDJ
- ```python
- def calc_kdj(klines: list[dict], n: int = 9,
- m1: int = 3, m2: int = 3) -> list[dict]:
- """
- KDJ 随机指标
- klines: K线数据
- n: RSV 周期(默认9)
- m1/m2: K/D 平滑系数(默认3/3)
- 返回: [{date, close, k, d, j}, ...]
- K/D > 80 超买,K/D < 20 超卖
- J > 100 或 J < 0 为极端信号
- 金叉: K 上穿 D;死叉: K 下穿 D
- """
- k_val, d_val = 50.0, 50.0
- result = []
- for i, kline in enumerate(klines):
- if i < n - 1:
- result.append({"date": kline["date"], "close": kline["close"],
- "k": None, "d": None, "j": None})
- continue
- window = klines[i - n + 1:i + 1]
- high_n = max(w["high"] for w in window)
- low_n = min(w["low"] for w in window)
- rsv = (kline["close"] - low_n) / (high_n - low_n) * 100 if high_n != low_n else 50.0
- k_val = (1 / m1) * rsv + (1 - 1 / m1) * k_val
- d_val = (1 / m2) * k_val + (1 - 1 / m2) * d_val
- j_val = 3 * k_val - 2 * d_val
- result.append({
- "date": kline["date"],
- "close": kline["close"],
- "k": round(k_val, 2),
- "d": round(d_val, 2),
- "j": round(j_val, 2),
- })
- return result
- ```
- ### 3.5 布林带
- ```python
- def calc_boll(klines: list[dict], period: int = 20,
- num_std: float = 2.0) -> list[dict]:
- """
- 布林带 (Bollinger Bands)
- klines: K线数据
- period: 中轨 MA 周期(默认20)
- num_std: 标准差倍数(默认2)
- 返回: [{date, close, upper, middle, lower, bandwidth}, ...]
- 价格触及 upper → 可能超买
- 价格触及 lower → 可能超卖
- bandwidth 收窄 → 即将变盘
- """
- closes = [k["close"] for k in klines]
- result = []
- for i, k in enumerate(klines):
- if i < period - 1:
- result.append({"date": k["date"], "close": k["close"],
- "upper": None, "middle": None, "lower": None,
- "bandwidth": None})
- continue
- window = closes[i - period + 1:i + 1]
- ma = sum(window) / period
- std = (sum((x - ma) ** 2 for x in window) / period) ** 0.5
- upper = ma + num_std * std
- lower = ma - num_std * std
- result.append({
- "date": k["date"],
- "close": k["close"],
- "upper": round(upper, 4),
- "middle": round(ma, 4),
- "lower": round(lower, 4),
- "bandwidth": round((upper - lower) / ma * 100, 2) if ma else None,
- })
- return result
- ```
- ---
- ## Layer 4: 基本面层
- ### 4.1 财报三表 — 东财 datacenter
- 东财 datacenter 提供美股/港股的资产负债表、利润表、现金流量表,中文字段名,按科目行展开。
- ```python
- def financial_statements_eastmoney(secucode: str, statement: str = "balance",
- page_size: int = 200) -> list[dict]:
- """
- 东财 datacenter 财报三表
- secucode: "AAPL.O" (NASDAQ) / "BABA.N" (NYSE) / "00700.HK" (港股)
- statement: "balance" / "income" / "cashflow"
- 返回: [{ITEM_NAME, AMOUNT, YOY_RATIO, REPORT, REPORT_DATE, ...}, ...]
- 注意: 数据按科目行展开,每行一个科目(如"流动资产合计"、"营业收入"等),
- 同一期报告有多行。用 REPORT_DATE 分组可还原整张报表。
- """
- # 报表名映射(注意命名不统一:balance/income 用 F10,cashflow 用 SK)
- report_map = {
- "balance": {"us": "RPT_USF10_FN_BALANCE", "hk": "RPT_HKF10_FN_BALANCE"},
- "income": {"us": "RPT_USF10_FN_INCOME", "hk": "RPT_HKF10_FN_INCOME"},
- "cashflow": {"us": "RPT_USSK_FN_CASHFLOW", "hk": "RPT_HKSK_FN_CASHFLOW"},
- }
- market = "hk" if secucode.endswith(".HK") else "us"
- report_name = report_map[statement][market]
- return eastmoney_datacenter(
- report_name=report_name,
- filter_str=f'(SECUCODE="{secucode}")',
- page_size=page_size,
- sort_columns="REPORT_DATE",
- sort_types="-1",
- )
- # 每行字段:
- # SECUCODE, SECURITY_CODE, SECURITY_NAME_ABBR, REPORT_DATE,
- # STD_ITEM_CODE, ITEM_NAME (科目名), AMOUNT (金额),
- # YOY_RATIO (同比%), REPORT (如 "2026/Q2"), REPORT_TYPE,
- # ACCOUNT_STANDARD (如 "美国会计准则"/"国际会计准则"),
- # CURRENCY (如 "美元"/"人民币")
- ```
- ### 4.2 关键财务指标(中文) — 东财 GMAININDICATOR
- 东财 datacenter 的 GMAININDICATOR 报表,提供中文关键财务指标概览。美股 49 字段、港股 75 字段,包含 ROE/ROA/EPS/毛利率/资产负债率/流动比率等,按季度报告。
- ```python
- def key_indicators_eastmoney(secucode: str, page_size: int = 4) -> list[dict]:
- """
- 东财 GMAININDICATOR 关键财务指标(中文)
- secucode: "AAPL.O" (NASDAQ) / "BABA.N" (NYSE) / "00700.HK" (港股)
- page_size: 返回最近几期报告(默认4期=一年)
- 返回: [{REPORT_DATE, OPERATE_INCOME, BASIC_EPS, ROE_AVG, ROA, ...}, ...]
- 美股核心字段(49): OPERATE_INCOME(营收), GROSS_PROFIT(毛利), GROSS_PROFIT_RATIO(毛利率%),
- PARENT_HOLDER_NETPROFIT(归母净利), NET_PROFIT_RATIO(净利率%), BASIC_EPS, DILUTED_EPS,
- ROE_AVG(平均ROE%), ROA(%), CURRENT_RATIO(流动比率), DEBT_ASSET_RATIO(资产负债率%),
- OPERATE_INCOME_YOY(营收同比%), BASIC_EPS_YOY(EPS同比%)
- 港股额外字段(75): BPS(每股净资产), ROIC(投入资本回报率), EQUITY_RATIO(产权比率),
- HOLDER_PROFIT(股东应占溢利), OCF_SALES(经营现金流/营收%), DPS_HKD(每股股息),
- DIVI_RATIO(股息率%), PER_NETCASH_OPERATE(每股经营现金流)
- """
- market = "hk" if secucode.endswith(".HK") else "us"
- report_name = f"RPT_{'HK' if market == 'hk' else 'US'}F10_FN_GMAININDICATOR"
- return eastmoney_datacenter(
- report_name=report_name,
- filter_str=f'(SECUCODE="{secucode}")',
- page_size=page_size,
- sort_columns="REPORT_DATE",
- sort_types="-1",
- )
- ```
- ### 4.3 关键财务指标(英文) — Yahoo quoteSummary
- Yahoo quoteSummary 的 `financialData` + `defaultKeyStatistics` 模块提供最核心的估值指标。
- ```python
- def key_statistics(symbol: str) -> dict:
- """
- Yahoo 关键财务指标
- symbol: "AAPL" (美股) 或 "0700.HK" (港股)
- 返回: PE/PB/EV/EBITDA/利润率/目标价/ROE/Beta 等
- """
- data = yahoo_quote_summary(symbol, ["financialData", "defaultKeyStatistics", "summaryDetail"])
- fd = data.get("financialData", {})
- ks = data.get("defaultKeyStatistics", {})
- sd = data.get("summaryDetail", {})
- def _val(d, key):
- v = d.get(key, {})
- return v.get("raw") if isinstance(v, dict) else v
- return {
- # 价格相关
- "current_price": _val(fd, "currentPrice"),
- "target_high": _val(fd, "targetHighPrice"),
- "target_low": _val(fd, "targetLowPrice"),
- "target_mean": _val(fd, "targetMeanPrice"),
- "recommendation": fd.get("recommendationKey"), # buy/hold/sell
- # 估值指标
- "trailing_pe": _val(sd, "trailingPE"),
- "forward_pe": _val(ks, "forwardPE"),
- "peg_ratio": _val(ks, "pegRatio"),
- "price_to_book": _val(ks, "priceToBook"),
- "enterprise_value": _val(ks, "enterpriseValue"),
- "ev_to_ebitda": _val(ks, "enterpriseToEbitda"),
- "ev_to_revenue": _val(ks, "enterpriseToRevenue"),
- # 盈利能力
- "profit_margin": _val(ks, "profitMargins"),
- "operating_margin": _val(fd, "operatingMargins"),
- "gross_margin": _val(fd, "grossMargins"),
- "return_on_equity": _val(fd, "returnOnEquity"),
- "return_on_assets": _val(fd, "returnOnAssets"),
- # 成长性
- "earnings_growth": _val(fd, "earningsGrowth"),
- "revenue_growth": _val(fd, "revenueGrowth"),
- # 风险
- "beta": _val(ks, "beta"),
- "short_ratio": _val(ks, "shortRatio"),
- # 股息
- "dividend_yield": _val(sd, "dividendYield"),
- "payout_ratio": _val(ks, "payoutRatio"),
- # 规模
- "market_cap": _val(sd, "marketCap"),
- "total_revenue": _val(fd, "totalRevenue"),
- "total_cash": _val(fd, "totalCash"),
- "total_debt": _val(fd, "totalDebt"),
- }
- ```
- ### 4.4 分析师预期与评级 — Yahoo quoteSummary
- ```python
- def analyst_estimates(symbol: str) -> dict:
- """
- Yahoo 分析师预期 — EPS预测/评级趋势/升降级历史
- symbol: "AAPL" 或 "0700.HK"
- """
- data = yahoo_quote_summary(symbol, [
- "earningsTrend", "recommendationTrend", "upgradeDowngradeHistory",
- "earnings", "earningsHistory",
- ])
- # EPS 趋势
- et = data.get("earningsTrend", {}).get("trend", [])
- eps_trend = []
- for t in et:
- eps_trend.append({
- "period": t.get("period"),
- "end_date": t.get("endDate"),
- "eps_estimate": t.get("earningsEstimate", {}).get("avg", {}).get("raw"),
- "eps_high": t.get("earningsEstimate", {}).get("high", {}).get("raw"),
- "eps_low": t.get("earningsEstimate", {}).get("low", {}).get("raw"),
- "revenue_estimate": t.get("revenueEstimate", {}).get("avg", {}).get("raw"),
- "num_analysts": t.get("earningsEstimate", {}).get("numberOfAnalysts", {}).get("raw"),
- })
- # 评级趋势 (最近4个月)
- rt = data.get("recommendationTrend", {}).get("trend", [])
- rating_trend = []
- for r_ in rt:
- rating_trend.append({
- "period": r_.get("period"),
- "strong_buy": r_.get("strongBuy"),
- "buy": r_.get("buy"),
- "hold": r_.get("hold"),
- "sell": r_.get("sell"),
- "strong_sell": r_.get("strongSell"),
- })
- # 升降级历史 (最近20条)
- udh = data.get("upgradeDowngradeHistory", {}).get("history", [])[:20]
- upgrades = []
- for u in udh:
- upgrades.append({
- "date": u.get("epochGradeDate"),
- "firm": u.get("firm"),
- "to_grade": u.get("toGrade"),
- "from_grade": u.get("fromGrade"),
- "action": u.get("action"), # up/down/main/init
- })
- return {
- "eps_trend": eps_trend,
- "rating_trend": rating_trend,
- "upgrade_downgrade": upgrades,
- }
- ```
- ### 4.5 机构持仓 — Yahoo quoteSummary
- ```python
- def institutional_holders(symbol: str) -> dict:
- """
- Yahoo 机构持仓 — 前10大机构 + 内部人持股比例
- symbol: "AAPL" 或 "0700.HK"
- """
- data = yahoo_quote_summary(symbol, ["institutionOwnership", "majorHoldersBreakdown"])
- # 持股比例总览
- mhb = data.get("majorHoldersBreakdown", {})
- def _val(d, key):
- v = d.get(key, {})
- return v.get("raw") if isinstance(v, dict) else v
- overview = {
- "insiders_pct": _val(mhb, "insidersPercentHeld"),
- "institutions_pct": _val(mhb, "institutionsPercentHeld"),
- "institutions_float_pct": _val(mhb, "institutionsFloatPercentHeld"),
- "institutions_count": _val(mhb, "institutionsCount"),
- }
- # 前10大机构
- io = data.get("institutionOwnership", {}).get("ownershipList", [])
- top_holders = []
- for h in io[:10]:
- top_holders.append({
- "name": h.get("organization"),
- "shares": _val(h, "position"),
- "value": _val(h, "value"),
- "pct_held": _val(h, "pctHeld"),
- "report_date": h.get("reportDate", {}).get("fmt") if isinstance(h.get("reportDate"), dict) else None,
- })
- return {"overview": overview, "top_holders": top_holders}
- ```
- ### 4.6 年度/季度财报明细 — Yahoo quoteSummary
- 东财 datacenter 按科目行展开,Yahoo 直接返回完整报表结构,两个互补。
- ```python
- def financial_statements_yahoo(symbol: str,
- quarterly: bool = False) -> dict:
- """
- Yahoo 财报三表 — 结构化完整报表
- symbol: "AAPL" 或 "0700.HK"
- quarterly: False=年度, True=季度
- 返回: {"income": [...], "balance": [...], "cashflow": [...]}
- """
- suffix = "Quarterly" if quarterly else ""
- data = yahoo_quote_summary(symbol, [
- f"incomeStatementHistory{suffix}",
- f"balanceSheetHistory{suffix}",
- f"cashflowStatementHistory{suffix}",
- ])
- def _extract(statements):
- result = []
- for stmt in statements:
- row = {}
- for k, v in stmt.items():
- if isinstance(v, dict) and "raw" in v:
- row[k] = v["raw"]
- elif isinstance(v, dict) and "fmt" in v:
- row[k] = v["fmt"]
- else:
- row[k] = v
- result.append(row)
- return result
- income_key = f"incomeStatementHistory{suffix}"
- balance_key = f"balanceSheetHistory{suffix}"
- cashflow_key = f"cashflowStatementHistory{suffix}"
- return {
- "income": _extract(data.get(income_key, {}).get("incomeStatementHistory", [])),
- "balance": _extract(data.get(balance_key, {}).get("balanceSheetStatements", [])),
- "cashflow": _extract(data.get(cashflow_key, {}).get("cashflowStatements", [])),
- }
- ```
- ---
- ## Layer 5: 资金面层
- ### 5.1 日级资金流 — 东财 push2his
- ```python
- def fund_flow_daily(ticker_or_code: str, secid_prefix: int = 105,
- limit: int = 100) -> list[dict]:
- """
- 东财 push2his 日级资金流 — 主力/大单/中单/小单净流入
- 美股: fund_flow_daily("AAPL", 105) # NASDAQ
- fund_flow_daily("BABA", 106) # NYSE
- 港股: fund_flow_daily("00700", 116)
- 返回: [{date, main_net, big_net, mid_net, small_net, main_pct, ...}, ...]
- """
- url = "https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get"
- params = {
- "secid": f"{secid_prefix}.{ticker_or_code}",
- "klt": 101,
- "fields1": "f1,f2,f3,f7",
- "fields2": "f51,f52,f53,f54,f55,f56,f57",
- "lmt": limit,
- }
- r = requests.get(url, params=params, timeout=15)
- d = r.json()
- data = d.get("data")
- if not data or not data.get("klines"):
- return []
- result = []
- for line in data["klines"]:
- parts = line.split(",")
- # f51=日期, f52=主力净流入, f53=小单净流入, f54=中单净流入, f55=大单净流入, f56=超大单净流入
- result.append({
- "date": parts[0],
- "main_net": float(parts[1]), # 主力净流入(元)
- "small_net": float(parts[2]), # 小单净流入
- "mid_net": float(parts[3]), # 中单净流入
- "big_net": float(parts[4]), # 大单净流入
- "super_big_net": float(parts[5]), # 超大单净流入
- "main_pct": float(parts[6]) if len(parts) > 6 and parts[6] else 0, # 主力净占比%
- })
- return result
- ```
- ---
- ## Layer 6: 期权层
- ### 6.1 期权链 + 希腊字母 + 0DTE 流 — CBOE 官方(主力 ⭐ V2.0 新增)
- 数据源 `cdn.cboe.com`,零鉴权。单只标的全链一次返回(实测 NVDA 3,908 / TSLA 6,200 / AAPL 3,576 合约),
- 字段含 `bid/ask/volume/open_interest/iv/delta/gamma/vega/theta/rho`。
- > ⚠️ **合规(C 级)**:Cboe 的 Use of Content 政策要求使用前取得书面批准与 license。
- > 以下代码**仅供个人研究**;商业用途或再分发前须先向 Cboe 申请授权。
- ```python
- import re
- from datetime import datetime, timezone, timedelta
- # 依赖「官方源统一出口」的 official_get / assert_us_ticker
- CBOE_BASE = "https://cdn.cboe.com/api/global/delayed_quotes"
- # OCC 合约代码: 标的 + YYMMDD + C/P + 8位行权价(千分之一美元)
- # root 允许含数字:拆股/分拆等公司行为会产生调整后合约(如 NVDA1、BRKB1)。
- # 后面全是定宽组(6+1+8=15 字符),正则回溯能正确对齐,标准合约解析结果不变。
- _OSI = re.compile(r"^(?P<root>[A-Z][A-Z0-9]*)(?P<y>\d{2})(?P<m>\d{2})(?P<d>\d{2})"
- r"(?P<cp>[CP])(?P<strike>\d{8})$")
- def parse_osi(symbol: str) -> dict:
- """解析 OCC 合约代码 → {expiry, type, strike};无法解析返回 {}"""
- m = _OSI.match(symbol)
- if not m:
- return {}
- g = m.groupdict()
- return {"expiry": f"20{g['y']}-{g['m']}-{g['d']}",
- "type": "call" if g["cp"] == "C" else "put",
- "strike": int(g["strike"]) / 1000.0}
- def options_chain_cboe(ticker: str) -> dict:
- """
- CBOE 官方延时期权全链(仅美股)。
- 返回 {"ticker","timestamp","spot","contracts":[{symbol,expiry,type,strike,bid,ask,
- volume,open_interest,iv,delta,gamma,vega,theta,rho,last_trade_price}]}
- """
- ticker = assert_us_ticker(ticker)
- raw = official_get(f"{CBOE_BASE}/options/{ticker}.json", as_json=True)
- data = raw.get("data") or {}
- contracts = []
- for o in data.get("options") or []:
- meta = parse_osi(o.get("option", ""))
- if not meta:
- continue
- contracts.append({
- "symbol": o["option"], **meta,
- "bid": o.get("bid"), "ask": o.get("ask"),
- "volume": o.get("volume") or 0,
- "open_interest": o.get("open_interest") or 0,
- "iv": o.get("iv"), "delta": o.get("delta"), "gamma": o.get("gamma"),
- "vega": o.get("vega"), "theta": o.get("theta"), "rho": o.get("rho"),
- "last_trade_price": o.get("last_trade_price"),
- })
- if not contracts:
- raise DataNotAvailable(f"{ticker} 未返回任何期权合约 —— 该标的可能无期权,"
- f"或不在 CBOE 覆盖范围(CBOE 仅覆盖美股)")
- return {"ticker": ticker, "timestamp": raw.get("timestamp"),
- "spot": data.get("current_price"), "contracts": contracts}
- try:
- from zoneinfo import ZoneInfo
- _ET_TZ = ZoneInfo("America/New_York")
- except Exception: # Windows 上 zoneinfo 可能缺 tzdata
- _ET_TZ = None
- def _et_today() -> str:
- """
- 美东今日 YYYY-MM-DD,用于 0DTE 判定。
- ⚠️ 必须区分 EDT(UTC-4) 与 EST(UTC-5):硬编码 UTC-4 会让冬令时
- UTC 04:00–05:00 这一小时算成次日,导致 0DTE 选错到期日。
- """
- now = datetime.now(timezone.utc)
- if _ET_TZ is not None:
- return now.astimezone(_ET_TZ).strftime("%Y-%m-%d")
- # 无 tzdata 时的回退:按美国 DST 规则(3月第2个周日 ~ 11月第1个周日)自算
- y = now.year
- # 美国 DST 在**当地时间 2:00** 切换,换算成 UTC:
- # 开始 = 3月第2个周日 02:00 EST = 07:00 UTC
- # 结束 = 11月第1个周日 02:00 EDT = 06:00 UTC
- # 用 00:00 UTC 当切换点会在切换日凌晨那几小时取错偏移。
- mar8 = datetime(y, 3, 8, tzinfo=timezone.utc)
- dst_start = (mar8 + timedelta(days=(6 - mar8.weekday()) % 7)
- ).replace(hour=7)
- nov1 = datetime(y, 11, 1, tzinfo=timezone.utc)
- dst_end = (nov1 + timedelta(days=(6 - nov1.weekday()) % 7)
- ).replace(hour=6)
- offset = 4 if dst_start <= now < dst_end else 5
- return (now - timedelta(hours=offset)).strftime("%Y-%m-%d")
- def filter_expiry(chain: dict, expiry: str = None, dte_max: int = None) -> list[dict]:
- """按到期日筛选。expiry='0DTE' 取当日到期;dte_max 取 N 天内到期"""
- cs = chain["contracts"]
- if expiry == "0DTE":
- return [c for c in cs if c["expiry"] == _et_today()]
- if expiry:
- return [c for c in cs if c["expiry"] == expiry]
- if dte_max is not None:
- today = datetime.strptime(_et_today(), "%Y-%m-%d")
- return [c for c in cs
- if 0 <= (datetime.strptime(c["expiry"], "%Y-%m-%d") - today).days <= dte_max]
- return cs
- def unusual_activity(contracts: list[dict], min_volume: int = 500,
- vol_oi_min: float = 1.0) -> list[dict]:
- """
- 异动合约识别:成交量 >= min_volume 且 volume/open_interest >= vol_oi_min。
- vol/OI > 1 = 当日成交超过存量持仓 = 新建仓,是 options flow 的核心信号。
- """
- out = []
- for c in contracts:
- vol, oi = c["volume"], c["open_interest"]
- if vol < min_volume:
- continue
- ratio = vol / oi if oi > 0 else float("inf")
- if ratio >= vol_oi_min:
- out.append({**c, "vol_oi_ratio": round(ratio, 2) if oi > 0 else None})
- return sorted(out, key=lambda x: -x["volume"])
- def chain_summary(contracts: list[dict]) -> dict:
- """链级聚合:put/call 量比与持仓比、成交量加权 IV、净 delta 敞口"""
- calls = [c for c in contracts if c["type"] == "call"]
- puts = [c for c in contracts if c["type"] == "put"]
- cv, pv = sum(c["volume"] for c in calls), sum(c["volume"] for c in puts)
- coi, poi = sum(c["open_interest"] for c in calls), sum(c["open_interest"] for c in puts)
- traded = [c for c in contracts if c["volume"] > 0 and c.get("iv")]
- tot_v = sum(c["volume"] for c in traded)
- vwiv = sum(c["iv"] * c["volume"] for c in traded) / tot_v if tot_v else None
- net_delta = sum((c.get("delta") or 0) * c["volume"] * 100 for c in contracts)
- return {"call_volume": cv, "put_volume": pv,
- "put_call_volume_ratio": round(pv / cv, 3) if cv else None,
- "call_oi": coi, "put_oi": poi,
- "put_call_oi_ratio": round(poi / coi, 3) if coi else None,
- "volume_weighted_iv": round(vwiv, 4) if vwiv else None,
- "net_delta_exposure_shares": round(net_delta),
- "contracts_total": len(contracts),
- "contracts_traded": len([c for c in contracts if c["volume"] > 0])}
- def cboe_quote(ticker: str) -> dict:
- """CBOE 个股快照(含现价,可与期权链配合定 ATM)"""
- return official_get(f"{CBOE_BASE}/quotes/{assert_us_ticker(ticker)}.json",
- as_json=True)["data"]
- ```
- **用法**
- ```python
- chain = options_chain_cboe("NVDA")
- zero = filter_expiry(chain, expiry="0DTE") # 当日到期合约
- near = filter_expiry(chain, dte_max=7) # 7 日内到期
- flow = unusual_activity(zero, min_volume=1000) # 0DTE 异动
- summ = chain_summary(zero) # P/C 比、加权 IV、净 delta
- ```
- **实测样本(2026-07-24)**
- | 标的 | 全链 | 0DTE 合约 | P/C 量比 | 量加权 IV | 净 delta 敞口 |
- |---|---|---|---|---|---|
- | NVDA | 3,908 | 168 | 0.542 | 43.1% | +16,496,611 股 |
- | TSLA | 6,200 | 326 | 1.041 | 83.2% | −37,364,065 股 |
- > TSLA 当日 −14.52%,期权层三个指标(put 占优 / IV 83% / 净 delta 为负)独立指向同一方向,可交叉验证。
- ⚠️ **限制**:CBOE 端点仅覆盖**美股**(港股期权需港交所专有接口);数据为**延时**,
- 不适用于实盘下单,适用于研究与流向分析。
- ---
- ### 6.2 期权链 — Yahoo Finance(后备 · 无希腊字母)
- ```python
- def options_chain(symbol: str, expiration: int = None) -> dict:
- """
- Yahoo 期权链 — calls + puts 完整数据(仅美股)
- symbol: "AAPL", "TSLA" 等美股 ticker
- ⚠️ 港股(如0700.HK)期权不在Yahoo覆盖范围,调用会返回空列表
- expiration: Unix timestamp (不传则返回最近到期日 + 所有到期日列表)
- 返回: {"expiration_dates": [...], "calls": [...], "puts": [...]}
- """
- s = get_yahoo_session()
- params = {"crumb": s._crumb}
- if expiration:
- params["date"] = expiration
- r = s.get(f"https://query2.finance.yahoo.com/v7/finance/options/{symbol}",
- params=params, timeout=15)
- r.raise_for_status()
- oc = r.json().get("optionChain", {}).get("result", [{}])[0]
- exp_dates = oc.get("expirationDates", [])
- options = oc.get("options", [{}])[0] if oc.get("options") else {}
- def _parse_options(opts):
- result = []
- for o in opts:
- def _val(key):
- v = o.get(key, {})
- return v.get("raw") if isinstance(v, dict) else v
- result.append({
- "strike": _val("strike"),
- "last_price": _val("lastPrice"),
- "bid": _val("bid"),
- "ask": _val("ask"),
- "volume": _val("volume"),
- "open_interest": _val("openInterest"),
- "implied_volatility": _val("impliedVolatility"),
- "in_the_money": o.get("inTheMoney"),
- "expiration": o.get("expiration", {}).get("fmt") if isinstance(o.get("expiration"), dict) else None,
- "contract_symbol": o.get("contractSymbol"),
- })
- return result
- return {
- "expiration_dates": exp_dates, # Unix timestamps, 可依次传入获取各期
- "calls": _parse_options(options.get("calls", [])),
- "puts": _parse_options(options.get("puts", [])),
- "underlying_price": oc.get("quote", {}).get("regularMarketPrice"),
- }
- ```
- ### 6.3 波动率指数历史 + VIX 期限结构 — CBOE 官方(V2.2 新增)
- CBOE 公开的指数日线文件,零鉴权。VIX 从 1990 年起,另有 VIX1D / VIX9D / VIX3M / VIX6M / VIX1Y
- (不同期限的隐含波动率)、VVIX(VIX 的波动率)、SKEW(尾部风险)、OVX(原油)、GVZ(黄金)等。
- 不用期货,只用这几个期限指数就能看出波动率曲线是正常向上(contango)还是倒挂(backwardation)。
- > ⚠️ **合规(C 级)**:与 6.1 同属 Cboe 内容,使用前须取得 Cboe 授权。**仅供个人研究**,商用或再分发前须先向 Cboe 申请。
- ```python
- import csv, io, re
- from datetime import datetime
- # 依赖「官方源统一出口」的 official_get;日期检查用 Layer 13 的 _check_range
- _YMD = re.compile(r"\d{4}-\d{2}-\d{2}")
- # 期限类指数 → 对应天数
- _VOL_DAYS = {"VIX1D": 1, "VIX9D": 9, "VIX": 30, "VIX3M": 93, "VIX6M": 183, "VIX1Y": 365}
- def vol_index_history(index: str = "VIX", start: str = None, end: str = None) -> list:
- """
- CBOE 波动率指数日线历史。
- index: VIX / VIX1D / VIX9D / VIX3M / VIX6M / VIX1Y / VVIX / SKEW / OVX / GVZ / VXN / RVX …
- start/end: YYYY-MM-DD(含)
- 返回 [{date, open, high, low, close}],旧的在前;
- VVIX / SKEW / OVX / GVZ 的文件只有收盘值,open/high/low 为 None
- 代码不存在 → DataNotAvailable
- """
- idx = index.strip().upper() if isinstance(index, str) else ""
- if not re.fullmatch(r"[A-Z0-9]{2,8}", idx):
- raise ValueError(f"无效的指数代码: {index!r}")
- start, end = _check_range(start, end, _YMD)
- raw = official_get(f"https://cdn.cboe.com/api/global/us_indices/daily_prices/{idx}_History.csv")
- reader = csv.reader(io.StringIO(raw))
- head = [h.strip().upper() for h in next(reader, [])]
- if not head or head[0] != "DATE":
- raise RuntimeError(f"CBOE {idx} 历史文件格式变了:{head[:5]}")
- ci = head.index("CLOSE") if "CLOSE" in head else (head.index(idx) if idx in head else len(head) - 1)
- oi, hi, li = (head.index(k) if k in head else None for k in ("OPEN", "HIGH", "LOW"))
- def f(p, i):
- if i is None or i >= len(p) or p[i].strip() == "":
- return None
- try:
- return float(p[i])
- except ValueError:
- return None
- out = []
- for p in reader:
- if not p or not p[0].strip():
- continue
- try:
- d = datetime.strptime(p[0].strip(), "%m/%d/%Y").strftime("%Y-%m-%d")
- except ValueError:
- continue
- if (start and d < start) or (end and d > end):
- continue
- c = f(p, ci)
- if c is None:
- continue
- out.append({"date": d, "open": f(p, oi), "high": f(p, hi), "low": f(p, li), "close": c})
- if not out:
- raise DataNotAvailable(f"CBOE {idx} 在所选区间没有数据")
- return out
- def vix_term_structure(indices=("VIX9D", "VIX", "VIX3M", "VIX6M", "VIX1Y")) -> dict:
- """
- VIX 期限结构(各期限指数的最新收盘)。
- shape: contango = 期限越长越高(常态);backwardation = 短端高于长端(恐慌时);mixed = 其他
- 返回 {"date","dates_aligned","points":[{index,days,date,close}],"shape","front_back_spread"}
- dates_aligned=False 表示各指数最新日期不一致(CBOE 各文件更新时间不同),比较时留意
- """
- if isinstance(indices, str):
- indices = [indices]
- names = []
- for ix in indices:
- ix = str(ix).strip().upper()
- if ix not in _VOL_DAYS:
- raise ValueError(f"{ix} 不是期限类指数,可选 {list(_VOL_DAYS)}")
- if ix not in names:
- names.append(ix)
- if len(names) < 2:
- raise ValueError("indices 至少给两个不同的期限")
- pts = []
- for ix in names: # 先检查完参数再下载
- last = vol_index_history(ix)[-1]
- pts.append({"index": ix, "days": _VOL_DAYS[ix], "date": last["date"], "close": last["close"]})
- pts.sort(key=lambda x: x["days"])
- closes = [p["close"] for p in pts]
- if all(a < b for a, b in zip(closes, closes[1:])):
- shape = "contango"
- elif all(a > b for a, b in zip(closes, closes[1:])):
- shape = "backwardation"
- else:
- shape = "mixed"
- dates = {p["date"] for p in pts}
- return {"date": max(dates), "dates_aligned": len(dates) == 1, "points": pts, "shape": shape,
- "front_back_spread": round(closes[-1] - closes[0], 2)}
- ```
- **实测(2026-10-12)**:VIX 1990-01-02 起 9,291 根,2020 年 3 月最高收盘 82.69;2026-10-09 收盘 VIX9D 11.26 / VIX 14.84 / VIX3M 17.77 / VIX6M 19.86 / VIX1Y 21.73,期限结构 contango,长短端差 10.47;VVIX 84.88、SKEW 154.34、OVX 48.9、GVZ 22.79(这四个文件只有收盘价)。起始年份:VIX1Y 2007、VIX6M 2008、VIX3M 2009、VIX9D 2011、VIX1D 2022。
- ---
- ## Layer 7: SEC Filing 层(仅美股)
- ### 7.1 SEC Filing 列表 — EDGAR submissions
- ```python
- SEC_HEADERS = {"User-Agent": "SimonLin global-stock-data/1.0 (contact@example.com)"}
- def sec_filings(cik: str, form_type: str = None) -> dict:
- """
- SEC EDGAR Filing 列表
- cik: CIK号(10位补零),如 "0000320193" (Apple)
- 可通过 ticker_to_cik() 从 ticker 转换
- form_type: 筛选类型,如 "10-K", "10-Q", "8-K"(不传返回全部)
- 返回: {"company_name": ..., "filings": [{form, date, accession_number, primary_document}, ...]}
- """
- url = f"https://data.sec.gov/submissions/CIK{cik}.json"
- r = requests.get(url, headers=SEC_HEADERS, timeout=15)
- r.raise_for_status()
- data = r.json()
- recent = data.get("filings", {}).get("recent", {})
- forms = recent.get("form", [])
- dates = recent.get("filingDate", [])
- accessions = recent.get("accessionNumber", [])
- primary_docs = recent.get("primaryDocument", [])
- descriptions = recent.get("primaryDocDescription", [])
- filings = []
- for i in range(len(forms)):
- if form_type and forms[i] != form_type:
- continue
- filings.append({
- "form": forms[i],
- "date": dates[i],
- "accession_number": accessions[i],
- "primary_document": primary_docs[i] if i < len(primary_docs) else "",
- "description": descriptions[i] if i < len(descriptions) else "",
- "url": f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accessions[i].replace('-', '')}/{primary_docs[i]}" if i < len(primary_docs) and primary_docs[i] else "",
- })
- return {
- "company_name": data.get("name"),
- "cik": cik,
- "ticker": data.get("tickers", [""])[0] if data.get("tickers") else "",
- "filings": filings[:50], # 最近50条
- }
- ```
- ### 7.2 SEC XBRL 结构化财务数据 — EDGAR companyfacts
- 覆盖 503 个 GAAP 指标,可精确提取多年营收/净利/EPS/资产/负债等。
- ```python
- def sec_xbrl_facts(cik: str, metrics: list[str] = None) -> dict:
- """
- SEC EDGAR XBRL 结构化财务数据
- cik: CIK号(10位补零)
- metrics: 要提取的指标名,如 ["RevenueFromContractWithCustomerExcludingAssessedTax",
- "NetIncomeLoss", "EarningsPerShareDiluted"]
- 不传则返回所有可用指标名列表
Lines 2,001–4,323 are not shown. The link to the file on GitHub has every line.
README.md · README · 362 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <p align="center"><a href="README_zh.md">简体中文</a> | <b>English</b></p>
- <h1 align="center">global-stock-data</h1>
- <p align="center">
- <b>US Market Data for AI Coding Assistants</b><br>
- Options Greeks · 0DTE Flow · VIX Term Structure · SEC Filings & Insider Trades · Short Data · Fundamentals · Screener · Global Rates & FX · Taiwan · Energy · US Macro
- </p>
- <p align="center">
- <a href="LICENSE"><img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" alt="License: Apache 2.0"></a>
- <a href="https://www.python.org/"><img src="https://img.shields.io/badge/Python-3.9+-3776AB?logo=python&logoColor=white" alt="Python 3.9+"></a>
- <a href="https://github.com/simonlin1212/global-stock-data/stargazers"><img src="https://img.shields.io/github/stars/simonlin1212/global-stock-data?style=social" alt="GitHub stars"></a>
- <a href="#architecture"><img src="https://img.shields.io/badge/layers-17-2ea44f.svg" alt="Layers"></a>
- <a href="#endpoints"><img src="https://img.shields.io/badge/endpoints-50%2B-2ea44f.svg" alt="Endpoints"></a>
- <a href="#data-sources"><img src="https://img.shields.io/badge/sources-18-2ea44f.svg" alt="Sources"></a>
- <a href="#data-sources"><img src="https://img.shields.io/badge/auth-zero-success.svg" alt="Zero-Auth"></a>
- </p>
- ---
- <p align="center">
- <a href="#architecture">Architecture</a> ·
- <a href="#compliance-tiers">Compliance</a> ·
- <a href="#quick-start">Quick Start</a> ·
- <a href="#endpoints">Endpoints</a> ·
- <a href="#data-sources">Data Sources</a> ·
- <a href="#faq">FAQ</a>
- </p>
- > **Full-stack market data for US equities** — 17 layers · 50+ endpoints · 18 sources · zero-auth · only `requests`.
- >
- > **Official-source-first (V2.0):** CBOE options with full Greeks + **0DTE** flow, FINRA market-wide short volume, SEC EDGAR filing stream + a free market-wide screener, Treasury / CFTC / earnings calendar. **Every source is labeled with its compliance tier, terms quoted verbatim** — "official" does not mean "free to use".
- >
- > **New in V2.1:** a global rates & FX layer — policy rates for 38 central banks (BIS), ECB FX / key rates / euro-area yield curve, NY Fed SOFR / EFFR, Fed H.10 FX / H.6 money stock, and US Treasury auctions + federal debt, all tier S. Yahoo K-line now returns true full-history daily bars in exchange-local dates, builds weekly / monthly / quarterly bars from daily data, and works for Japan / Taiwan / Korea / India / Europe and more.
- >
- > **New in V2.2:** CBOE volatility indices (VIX since 1990) and the VIX term structure, FINRA short interest (twice a month, with days to cover), SEC Form 4 insider trades line by line and 13F institutional holdings, the Taiwan Stock Exchange / TPEx official open APIs (latest Taiwan quotes, P/E, monthly revenue; commercial use OK), and US EIA weekly crude oil / natural gas inventories plus spot prices (spot prices are tier B, see Compliance tiers).
- >
- > **New in V2.3:** a US macro layer — the US Bureau of Labor Statistics' registration-free public API: 23 common indicators in one request, including CPI / core CPI, nonfarm payrolls, the unemployment rate, average hourly earnings, PPI, JOLTS job openings, import prices, the Employment Cost Index and labor productivity, with month-over-month and year-over-year changes computed locally, the official release schedule and each indicator's revision rules; plus the Department of Labor's weekly initial / continued jobless claims (since 1967). All tier S; cite the source and the retrieval date.
- A single self-contained Skill file that turns raw US stock data — scattered across many sources — into a toolkit an AI coding assistant can call directly. You no longer memorize Eastmoney secid prefixes, Yahoo crumb auth flows, or SEC EDGAR CIK mappings. That's all handled.
- > *This project distributes **code, not market data**. Data is fetched by the user under each source's own terms. For commercial use, rely only on tier-S sources.*
- > Compatible with [Claude Code](https://github.com/anthropics/claude-code) · [Codex](https://github.com/openai/codex) · [OpenClaw](https://github.com/openclaw/openclaw). The Skill file is structured Markdown + embedded Python — any AI coding assistant with context injection can use it.
- ---
- ## Architecture
- ```
- US Full-Stack Data · 17-layer architecture · V2.3
- │
- ├── Market Data Sina + Tencent + Eastmoney push2 Real-time quotes, 25-78 fields
- ├── K-line Sina(back to 1984) + Yahoo chart Daily / weekly / monthly / minute; JP/TW/KR/IN/EU via suffix
- ├── Technical Ind. MA/EMA + MACD + RSI + KDJ + Bollinger Pure Python, zero extra deps
- ├── Fundamentals Eastmoney + Yahoo + SEC XBRL Statements + key metrics + holdings
- ├── Fund Flow Eastmoney push2his Daily main/large/medium/small flow
- ├── Options Yahoo crumb Options chain (US only)
- ├── SEC Filing EDGAR submissions + XBRL 10-K/10-Q/8-K + 503 GAAP metrics (US)
- └── Tools Eastmoney + Yahoo + SEC CIK Search + market list + news + ticker↔CIK
- ━━━ New in V2.0 (official-source-first) ━━━
- ├── Options·CBOE cdn.cboe.com official feed ⭐ full chain + IV + delta/gamma/vega/theta/rho + 0DTE + flow
- ├── Short Volume FINRA Reg SHO ⭐ market-wide daily short volume (12,112 symbols) + series
- ├── Filing Stream EDGAR daily index + FTS ⭐ Form 4 / 8-K / 13F same-day + full-text since 2001
- ├── Market Screener EDGAR frames ⭐ any XBRL tag across the whole market (1,842~5,309 co.) — free
- └── Macro / Calendar Treasury + CFTC + Nasdaq ⭐ yield curve (1M~30Y) + COT + earnings calendar
- ━━━ New in V2.1 ━━━
- └── Global Rates/FX BIS + ECB + NY Fed + Fed + Treasury ⭐ 38 central-bank policy rates + EUR/USD FX + SOFR/EFFR + euro curve + auctions
- ━━━ New in V2.2 ━━━
- ├── Volatility CBOE index files ⭐ VIX since 1990 + VIX9D/3M/6M/1Y term structure + VVIX/SKEW/OVX/GVZ
- ├── Short Interest FINRA, twice a month ⭐ all US open short positions (22,595 symbols) + days to cover + rankings
- ├── Insiders / 13F SEC Form 4 + 13F ⭐ insider trades (price/shares/10b5-1 box on the filing) + quarterly institutional holdings
- ├── Taiwan TWSE + TPEx OpenAPI ⭐ latest quotes + P/E + monthly revenue + margin for all listed/OTC stocks (commercial OK)
- └── Energy US EIA ⭐ weekly crude/gas inventories + WTI (since 1986)/Brent/Henry Hub daily spot prices (tier B)
- ━━━ New in V2.3 ━━━
- └── US Macro US Dept. of Labor BLS + ETA ⭐ CPI/core CPI/payrolls/unemployment/earnings/PPI/JOLTS and more (23 indicators) + release schedule + weekly jobless claims
- ```
- > Layer count: the original 8 layers + 5 in V2.0 (the CBOE options chain counts as its own layer) + 1 in V2.1 + 2 in V2.2 (Taiwan, energy) + 1 in V2.3 (US macro). The V2.2 volatility indices, short interest and Form 4 / 13F parsers are new sections inside existing layers and are not counted as layers.
- ---
- ## Compliance tiers
- Source terms differ a lot. **"Official" does not mean "free to use".** These tiers come from reading each source's actual terms of service (2026-07-24; Yahoo / Nasdaq re-checked and 4 new official sources read on 2026-10-11; TWSE / TPEx and EIA read on 2026-10-12; the US Bureau of Labor Statistics and Department of Labor read on 2026-11-02). Quotes are verbatim.
- <table>
- <thead>
- <tr><th nowrap>Tier</th><th nowrap>Commercial</th><th nowrap>Redistribute</th><th>Sources</th><th>Basis (quoted)</th></tr>
- </thead>
- <tbody>
- <tr><td nowrap><strong>S</strong></td><td nowrap>✅</td><td nowrap>✅</td><td>SEC EDGAR / Treasury / CFTC / Federal Reserve Board / NY Fed / BIS / ECB / EIA (inventories) / TWSE / TPEx / US Dept. of Labor (BLS / ETA)</td><td>EDGAR: <em>"Anyone can access and download this information <strong>for free</strong>"</em>, <em>"We <strong>allow scripted access</strong>"</em> — hard limit <strong>10 req/s</strong>, User-Agent required. Fed Board: <em>"public domain"</em>. NY Fed: <em>"personal or business purposes"</em>, <em>"through an automated process"</em>. BIS: <em>"unrestricted"</em>. ECB: <em>"reused free of charge"</em>. EIA's own data: <em>"public domain"</em>. TWSE / TPEx: all 13 datasets we use are registered on Taiwan's government open data platform under the Open Government Data License, which allows use for any purpose, non-exclusive, irrevocable and royalty-free; both OpenAPI pages say they welcome integration, and the intellectual-property section of both sites' terms exempts data licensed to the open data platform, while asking that reproductions stay complete, with nothing arbitrarily added or removed (TPEx's OpenAPI page does not link the license and the platform lists web download URLs, so rating it S is this tool's judgment). BLS: <em>"public domain"</em>; its API terms ask users to cite the retrieval date and state <em>"BLS.gov cannot vouch for the data or analyses derived from these data after the data have been retrieved from BLS.gov."</em> The key-free tier allows 25 requests a day, and trying to get around the limits can get you blocked. Department of Labor: <em>"public domain"</em>, without implying any affiliation with or endorsement by the DOL. <strong>BIS / ECB / Fed Board / TWSE / TPEx / BLS require attribution (BLS also the retrieval date), ECB data must not be modified, and NY Fed reference rates need its notice when shown to others</strong></td></tr>
- <tr><td nowrap><strong>B</strong></td><td nowrap>⚠️ verify first</td><td nowrap>❌</td><td>FINRA / EIA spot prices</td><td>FINRA files (daily short volume, short interest) are published for download, but terms prohibit <em>"data mining, scraping or harvesting tools (including robots)"</em> and state <em>"<strong>non-commercial use</strong>"</em>. EIA's WTI / Brent / Henry Hub spot prices are sourced from <em>"Refinitiv, an LSEG business"</em>; reproducing third-party material beyond fair use needs the copyright owner's written permission (tier B is this tool's judgment)</td></tr>
- <tr><td nowrap><strong>C</strong></td><td nowrap>❌ needs permission</td><td nowrap>❌</td><td>CBOE / Eastmoney / Sina / Tencent</td><td>CBOE (options chains and volatility indices) requires <em>"<strong>approval in advance</strong>"</em> + <em>"<strong>execution of a license agreement</strong>"</em>; Eastmoney / Sina / Tencent are website front-end endpoints, personal research only</td></tr>
- <tr><td nowrap><strong>D</strong></td><td nowrap>❌</td><td nowrap>❌</td><td>Yahoo / Nasdaq</td><td>Terms prohibit automated access without permission. Yahoo: <em>"using any automated means… for any purpose without our express, prior permission"</em>. Nasdaq: <em>"any process, whether automated or manual, to capture data… for any reason"</em>. <strong>Personal study and research only, at your own risk; no commercial use or redistribution</strong></td></tr>
- <tr><td nowrap><strong>⛔ Excluded</strong></td><td nowrap>—</td><td nowrap>—</td><td>HKEX (CCASS)</td><td>Terms prohibit <em>"any '<strong>robot</strong>', '<strong>bot</strong>', '<strong>spider</strong>', '<strong>scraper</strong>'..."</em> and apply <em>"<strong>whether or not for gain</strong>"</em> → <strong>this tool ships no scraper for it</strong></td></tr>
- </tbody>
- </table>
- A working HKEX shareholding layer was built, then removed. Shipping code that violates a source's terms would defeat the point of grading sources in the first place. **This project distributes code, not data.** For commercial use, rely only on tier S.
- **So why keep tier-D Yahoo and Nasdaq?** Honestly, their terms are the same kind as HKEX's. The difference is that they have no substitute: Yahoo is the only source for HK K-lines and for markets beyond the US and HK, and Nasdaq is the only key-free earnings calendar, while the HKEX shareholding layer was a nice-to-have. So the code stays and the terms are quoted in full (see "数据源合规分级" in SKILL.md). Whether to use them is your call under those terms.
- ---
- ## Quick start
- **3 steps, 2 minutes.**
- ```bash
- # 1. Create the skill directory
- mkdir -p ~/.claude/skills/global-stock-data
- # 2. Download SKILL.md
- curl -o ~/.claude/skills/global-stock-data/SKILL.md \
- https://raw.githubusercontent.com/simonlin1212/global-stock-data/main/SKILL.md
- # 3. Install the dependency
- pip install requests
- # Windows only: also install tzdata so Yahoo K-line dates use the exchange's time zone
- pip install tzdata
- ```
- ⚠️ **Before using the SEC or US macro (BLS) layers, set `SEC_CONTACT` in SKILL.md to your real name and email.** SEC requires a declared User-Agent; requests without one are rejected as an *Undeclared Automated Tool*, and the BLS website returns 403. The code raises a clear error if you forget.
- Launch Claude Code and say "check AAPL's financials" — the skill activates on its own. **Codex / OpenClaw users:** paste SKILL.md into your system prompt or project context file; the embedded Python runs as-is.
- ---
- ## Endpoints
- **Price** — Sina / Tencent / Eastmoney quotes (25-78 fields) · Sina & Yahoo K-line (US back to 1984, daily→minute; Japan / Taiwan / Korea / India / Europe and more via ticker suffix) · MA/EMA/MACD/RSI/KDJ/Bollinger computed locally.
- **Value** — Eastmoney three statements + GMAININDICATOR (US 49 / HK 75 fields) · Yahoo quoteSummary (23 modules: financials, analysts, institutional holdings) · SEC EDGAR XBRL (503 GAAP metrics).
- **Flow & positioning ⭐** — CBOE options with full Greeks + IV + **0DTE** + unusual-flow detection · FINRA market-wide daily short volume (12,112 symbols) · Eastmoney daily fund flow · **V2.2:** CBOE VIX history since 1990 + term structure (contango or backwardation) + VVIX / SKEW · FINRA short interest (twice a month, 22,595 symbols, with days to cover and rankings).
- **Filings & events ⭐** — EDGAR daily index (same-day **Form 4 insider / 8-K / 13F**, one day: 547 / 370 / 261) · full-text search since 2001 · 10-K/10-Q/8-K list · **V2.2:** Form 4 insider trades line by line (price, shares, holdings after, whether the filing ticks the 10b5-1 box) · 13F quarterly institutional holdings (sorted by value, with weights).
- **Screener & macro ⭐** — EDGAR frames (any XBRL tag across the whole market, free — net income CY2025Q1 = 5,309 companies) · Treasury yield curve (1M~30Y) · CFTC COT · Nasdaq earnings calendar.
- **Global rates & FX ⭐ (V2.1)** — policy rates for 38 central banks in one call (BIS) · ECB FX / three key rates / euro-area yield curve · NY Fed SOFR / EFFR · Fed H.10 USD vs 23 currencies / H.6 M1·M2 · Treasury auction results and schedule / federal debt / average interest rates.
- **Taiwan ⭐ (V2.2)** — TWSE + TPEx official open APIs: the latest trading day's quotes, P/E / dividend yield / P/B, monthly revenue, company profiles, margin trading, ex-dividend notices and dividends for every listed and OTC stock (latest day only; for Taiwan K-line history use Yahoo `.TW` / `.TWO`).
- **Energy ⭐ (V2.2)** — EIA weekly crude (commercial + SPR), gasoline, distillate and natural gas inventories · WTI (since 1986) / Brent / Henry Hub daily spot prices (tier B: third-party data republished by EIA).
- **US macro ⭐ (V2.3)** — US Bureau of Labor Statistics: CPI / core CPI (seasonally adjusted and not), shelter, CPI-W, chained CPI, unemployment rate, U-6, participation rate, nonfarm payrolls, average hourly earnings, PPI and core PPI, JOLTS openings and quits rate, import prices, the Employment Cost Index, labor productivity, or any BLS series ID · the latest period's MoM / YoY change and next release date · the official BLS release schedule · Department of Labor weekly initial / continued jobless claims (since 1967). The key-free tier allows 25 requests a day; identical requests are reused for an hour.
- **Tools** — stock search (CN+EN) · full-market list (US 5925+ / HK 18000+) · news by ticker · ticker↔CIK.
- <details>
- <summary>Full endpoint tables</summary>
- <br>
- ### Options ⭐ (US only)
- | Endpoint | Data |
- |----------|------|
- | **CBOE official** | Full chain + **IV + delta/gamma/vega/theta/rho**, plus **0DTE filtering** and **unusual-flow** detection (vol/OI > 1 = new positioning) |
- | Yahoo (fallback) | Options chain, all expiries — **no Greeks** |
- ### Volatility indices ⭐ (V2.2, US only)
- | Endpoint | Data |
- |----------|------|
- | CBOE `vol_index_history()` | Daily VIX (since 1990) / VIX1D / VIX9D / VIX3M / VIX6M / VIX1Y / VVIX / SKEW / OVX / GVZ and more |
- | CBOE `vix_term_structure()` | Latest VIX at each tenor, whether the curve is in contango or backwardation, plus the long-short spread |
- ### Short volume ⭐ (US only)
- | Endpoint | Data |
- |----------|------|
- | FINRA Reg SHO | Market-wide **daily short volume** (12,112 symbols), per-symbol series, ratio ranking |
- | FINRA short interest `short_interest()` / `short_interest_all()` / `short_interest_ranking()` (V2.2) | **Open short positions** twice a month (22,595 symbols), days to cover, change vs prior period; rank by days to cover / shares short / change |
- ### Filing stream ⭐ (US only)
- | Endpoint | Data |
- |----------|------|
- | EDGAR daily index | Same-day **Form 4 / 8-K / 13F / 144** — one day: 547 / 370 / 261 / 118 |
- | EDGAR full-text | Search every filing body back to 2001 |
- | EDGAR submissions / XBRL | Filing list + structured financials (503 GAAP metrics) |
- | Form 4 parser `insider_trades()` (V2.2) | Insider trades line by line: trade date, transaction type, shares, price, value, holdings after, whether the filing ticks the 10b5-1 box; plus an open-market buy / sell summary |
- | 13F parser `holdings_13f()` (V2.2) | Quarterly institutional holdings, sorted by value with weights, reconciled against the cover-page total; pre-2023 filings in thousands are converted to dollars |
- ### Market screener ⭐ (US only)
- | Endpoint | Data |
- |----------|------|
- | EDGAR frames | One XBRL tag across the whole market in one call — a free screener |
- ### Macro / calendar ⭐
- | Endpoint | Data |
- |----------|------|
- | Treasury / CFTC / Nasdaq | Yield curve (1M~30Y) · COT · earnings calendar (pre/post-market + EPS est.) |
- ### Global rates / FX / central banks ⭐ (V2.1)
- | Endpoint | Data |
- |----------|------|
- | BIS `policy_rates()` | Policy rates for 48 economies (38 still updated), all in one call |
- | ECB `ecb_fx()` / `ecb_key_rates()` / `ecb_yield_curve()` / `ecb_series()` | EUR reference rates · deposit facility and the other two key rates · euro-area government curve (AAA or all issuers) · any ECB series |
- | NY Fed `nyfed_rates()` | SOFR / EFFR / OBFR / TGCR / BGCR with percentiles and volume; SOFR averages and index |
- | Fed Board `fed_data()` | H.10 USD vs 23 currencies · H.6 M1/M2 and components |
- | Treasury `fiscal_data()` | Auction results (high yield, bid-to-cover) and upcoming schedule · daily federal debt · average interest rates · Treasury reporting FX rates |
- ### Taiwan ⭐ (V2.2)
- | Endpoint | Data |
- |----------|------|
- | `tw_stock()` | One Taiwan stock's latest quote + P/E / P/B / dividend yield; listed or OTC detected automatically |
- | `tw_market()` | Listed (TWSE) or OTC (TPEx), whole market or one stock: quotes · valuation · monthly revenue · company profile · margin trading · ex-dividend notices · dividend resolutions (dividends: TWSE only) |
- ### Energy ⭐ (V2.2)
- | Endpoint | Data |
- |----------|------|
- | EIA `energy_prices()` | WTI (since 1986) / Brent (since 1987) crude spot, USD per barrel; Henry Hub natural gas (since 1997). Tier B: prices come from Refinitiv, verify before commercial use or redistribution |
- | EIA `energy_inventories()` | Weekly crude (commercial + SPR), gasoline, distillate and other stocks; Lower 48 and regional natural gas storage vs the 5-year average |
- ### US macro ⭐ (V2.3)
- | Endpoint | Data |
- |----------|------|
- | BLS `us_macro()` | 23 common indicators in one request: CPI / core CPI (SA and NSA), shelter, CPI-W, chained CPI, unemployment rate, U-6, participation rate, employment-population ratio, nonfarm payrolls, average hourly earnings, average weekly hours, PPI and core PPI, JOLTS openings and quits rate, import prices, ECI 12-month change, labor productivity |
- | BLS `us_macro_latest()` | Latest, previous and year-ago values per indicator, MoM / YoY computed locally, plus the next release date |
- | BLS `bls_series()` | Any BLS series ID; requests over 25 series or 10 years are split automatically |
- | BLS `bls_release_calendar()` | Official release schedule: date and Eastern time of every CPI / Employment Situation / PPI / JOLTS release and more |
- | Dept. of Labor `us_jobless_claims()` | Weekly initial and continued claims (SA / NSA / 4-week average) and the insured unemployment rate, since 1967 |
- ### Price / value / flow / tools
- | Endpoint | Data |
- |----------|------|
- | Sina / Tencent / Eastmoney push2 | US/HK real-time quotes, 25-78 fields |
- | Sina / Yahoo chart | K-line, daily→minute, US back to 1984; Yahoo gives full daily history (S&P 500 since 1927) and markets beyond US/HK |
- | Eastmoney datacenter / GMAININDICATOR | Statements + key metrics (bilingual) |
- | Yahoo quoteSummary | 23 modules: financials / analysts / institutional holdings |
- | Eastmoney push2his | Daily main/large/medium/small fund flow |
- | Eastmoney search / push2 list / Yahoo search / SEC CIK | Search / full-market list / news / ticker↔CIK |
- Every source is free, no API key. Yahoo crumb is auto-managed; SEC EDGAR and BLS only need a declared User-Agent (the key-free BLS tier allows 25 requests a day).
- </details>
- ---
- ## Usage examples
- Just tell your AI assistant:
- | Scenario | Prompt |
- |----------|--------|
- | 0DTE options flow ⭐ | "Show NVDA's 0DTE options flow — unusual activity" |
- | Short volume ⭐ | "TSLA's short volume ratio trend this week" |
- | Short interest ⭐ | "GME's short interest and days to cover over the last few periods" |
- | VIX term structure ⭐ | "Is the VIX term structure inverted right now?" |
- | Insider filings ⭐ | "Any Form 4 insider filings today for my watchlist" |
- | Insider trades ⭐ | "How many shares did NVDA insiders sell in the past six months?" |
- | 13F holdings ⭐ | "Berkshire's top 10 holdings in its latest 13F" |
- | Full-text filings ⭐ | "Which companies first mentioned 'HBM4' in an 8-K" |
- | Market screener ⭐ | "Rank all filers by R&D expense for CY2025Q1" |
- | Macro ⭐ | "What's the 10Y-2Y Treasury spread right now" |
- | Central banks ⭐ | "Current policy rates of the major central banks" · "SOFR and EFFR over the past week" |
- | FX / Treasuries ⭐ | "EUR/JPY this month" · "Next week's Treasury auction schedule" |
- | Taiwan ⭐ | "TSMC's latest close and P/E" · "This month's revenue for OTC-listed stocks" |
- | Oil / gas ⭐ | "This week's EIA crude inventories" · "WTI over the past year" |
- | US macro ⭐ | "Latest CPI and core CPI year over year, and when's the next release?" · "Initial jobless claims over the last few weeks" |
- | Other markets | "Toyota 7203.T daily K-line for the past year" · "TSMC 2330.TW full history" |
- | US / HK quote | "AAPL's price and PE" · "How's Tencent 00700 today" |
- | K-line | "Pull TSLA's daily K-line for the past 6 months" |
- | Statements / valuation | "Apple's latest income statement" · "BABA's PE/PB/ROE + target" |
- | Institutional holdings | "Which institutions hold NVDA, and what %" |
- | Technical analysis | "AAPL's MACD and RSI — any golden cross?" |
- | Batch compare | "Compare valuations of AAPL MSFT GOOGL" |
- ---
- ## Data sources
- | Source | Tier | Auth | Coverage |
- |--------|------|------|----------|
- | **SEC EDGAR** | **S** | real UA | US filings / XBRL / **filing stream** / **full-text search** / **market screener** / **Form 4 insider trades** / **13F holdings** |
- | **US Treasury** | **S** | none | **Yield curve (1M~30Y)** · FiscalData **auctions / federal debt / average rates** |
- | **CFTC** | **S** | none | **COT reports** |
- | **Federal Reserve Board** | **S** | none | **H.10 FX / H.6 money stock** (attribution) |
- | **NY Fed** | **S** | none | **SOFR / EFFR / OBFR / TGCR / BGCR** (notice required when shown to others) |
- | **BIS** | **S** | none | **Central-bank policy rates** (attribution) |
- | **ECB** | **S** | none | **EUR FX / ECB key rates / euro-area yield curve** (attribution, no modification) |
- | **US EIA** | **S** / B | none | **Weekly crude oil / natural gas inventories** (S, attribution recommended) · WTI / Brent / Henry Hub spot prices (B: Refinitiv data republished by EIA, verify before commercial use) |
- | **US Department of Labor** (BLS + ETA) | **S** | real UA | **CPI / payrolls / unemployment / PPI / JOLTS / import prices / ECI / productivity** · **release schedule** · **weekly jobless claims** (cite source and retrieval date; key-free tier: 25 requests a day) |
- | **Taiwan Stock Exchange** | **S** | none | Listed stocks' **latest quotes / P/E / monthly revenue / margin / ex-dividend / dividends** (attribution) |
- | **TPEx** | **S** | none | OTC stocks' **latest quotes / P/E / monthly revenue / margin / ex-dividend** (attribution; S is this tool's judgment) |
- | **FINRA** | **B** | none | US **market-wide daily short volume** · **short interest** (verify before commercial use) |
- | **CBOE** | **C** | none | US **options + Greeks + IV + 0DTE** · **VIX and other volatility indices** (needs Cboe's prior approval) |
- | Eastmoney (push2 / push2his / datacenter / search) | C | none | US+HK quotes / fund flow / statements / search |
- | Sina | C | none | US+HK quotes, US K-line |
- | Tencent | C | none | US+HK quotes |
- | Yahoo Finance | D | cookie+crumb (auto) | US+HK+other markets, all categories (terms prohibit automated access) |
- | Nasdaq | D | none | US **earnings calendar** (terms prohibit automated access) |
- **Tiers:** **S** = government and central-bank data (including exchange data registered as Taiwan government open data), commercial + redistribution OK (some require attribution) · **B** = published data, verify before commercial use · **C** = needs prior approval or terms unverified, personal research only · **D** = terms prohibit automated access without permission; personal study and research only, at your own risk, no commercial use or redistribution. See [Compliance tiers](#compliance-tiers) for the quoted basis. All requests go through direct HTTP with a built-in thread-safe rate limiter (SEC capped at 8 req/s against the official 10).
- ---
- ## FAQ
- **Q: How does this relate to a-stock-data?**
- Sister project. [a-stock-data](https://github.com/simonlin1212/a-stock-data) covers China A-shares; global-stock-data covers US and HK. Install both — they don't conflict.
- **Q: Does Yahoo Finance need an API key?**
- No. The code fetches cookie + crumb automatically and refreshes on expiry.
- **Q: Any limits on SEC EDGAR?**
- Yes — a declared User-Agent and 10 req/s. Set `SEC_CONTACT` to your real email; the built-in throttle stays under the limit.
- **Q: HK options data?**
- No. HK options aren't in Yahoo's coverage and need HKEX's paid feed. The options layer is US only.
- **Q: Can I look up stocks outside the US and HK?**
- K-lines and Yahoo fundamentals, yes: Japan `.T`, Taiwan `.TW`, Korea `.KS`, India `.NS`, London `.L`, Germany `.DE` and more — see "Yahoo Finance 代码格式" in SKILL.md. Note that Yahoo is a tier-D source. Taiwan also has the official TWSE / TPEx APIs (tier S, latest trading day only): `tw_stock("2330")`. For China A-shares, use the sister project a-stock-data.
- **Q: How fresh are the global rates and FX?**
- ECB and NY Fed update every business day; Fed H.10 is published each Monday for the prior week; BIS lags by a few days to about three weeks depending on the country. Every row carries its date — check the central bank itself when you need today's exact value.
- **Q: How often is short interest updated?**
- FINRA publishes it twice a month, for settlement dates on the 15th and at month-end (moved earlier for holidays), about 8 business days after settlement. The daily dataset is a different one — daily short volume (9.1), which counts that day's short-sale trades, not open short positions.
- **Q: Are there limits on the US macro data? Does it get revised?**
- The registration-free BLS API allows 25 requests a day, up to 25 series and 10 years per request; `us_macro()` gets all 23 indicators in one request, and identical requests are reused for an hour. Payrolls, PPI, JOLTS and others are revised after release, and the API returns the latest revised values, not what was first published. When replaying history, line data up with the real release dates from `bls_release_calendar()`. Each indicator's revision rules are in section 16.5 of SKILL.md.
- **Q: Why no GDP?**
- GDP comes from the Bureau of Economic Analysis, whose API needs a registered key. This project does not use sources that require an account or a key.
- **Q: Running from a server in mainland China — can it reach Yahoo / SEC?**
- They're overseas and may be flaky on a direct connection. Use a proxy, or lean on the Eastmoney / Sina / Tencent sources.
- **Q: Can I use it without Claude Code?**
- Yes. SKILL.md is Markdown + embedded Python — Codex, OpenClaw, or any AI coding assistant can read it, and you can copy the Python into your own scripts.
- ---
- ## Changelog
- See [CHANGELOG.md](./CHANGELOG.md).
- ## Disclaimer
- This project provides data-access tools only. It is not investment advice. Investing involves risk.
- ## License
- [Apache License 2.0](./LICENSE) — **Author:** Simon Lin · X [@linsizhen](https://x.com/linsizhen) · Email: [simonlin0423@gmail.com](mailto:simonlin0423@gmail.com)
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.