SkillsGrove
SkillsGrove/생산성/simonlin1212/global-stock-data/global-stock-data

global-stock-data

설치

$npx skills add https://github.com/simonlin1212/global-stock-data --skill global-stock-data
$git clone --depth 1 https://github.com/simonlin1212/global-stock-data.git /tmp/global-stock-data && mkdir -p ~/.claude/skills && cp -r /tmp/global-stock-data/. ~/.claude/skills/global-stock-data
이 Agent Skill을 설치해 주세요: https://github.com/simonlin1212/global-stock-data/tree/b7f22029660769baa29a4403cc61c285f35f8905/ — 먼저 SKILL.md와 스크립트를 읽고, 안전하다고 확인한 뒤에만 제 skills 폴더에 설치해 주세요.

요약

원문 설명 · Apache-2.0美股港股全栈数据工具包(官方源优先)— 十七层架构·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/非农/失业金等宏观数据与发布日程等场景。
아래 SKILL.md는 simonlin1212/global-stock-data(커밋 b7f2202)에서 Apache-2.0 라이선스에 따라 게시한 것입니다. 본문은 변경하지 않았으며, 파일 상단의 메타데이터만 생략하고 이미지는 링크로 표시하며 매우 긴 파일은 일부만 표시합니다. Copyright owner or entity authorized by. 라이선스: LICENSE. 지침 파일만 표시되며 스크립트 등은 원본 저장소를 참고하세요.

📦 项目主页:https://github.com/simonlin1212/global-stock-data — 更新、反馈、支持作者

作者:Simon 林 · X @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

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 自动获取并缓存:

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 {}

东财数据中心统一查询

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)。

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)。

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 港股实时行情 — 腾讯 + 新浪

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):

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 在 issue #2 中提供的完整对照,本表据此逐条复测后修订。

1.3 东财 push2 实时行情 — 美股 + 港股

东财 push2 接口,通过 secid 统一查询美股/港股实时行情。优点:有中文名、换手率、涨跌幅,且 secid 可由 stock_search() 自动获取。

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。

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线数据)。

# 港股 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 线函数获取数据,再传入技术指标函数:

klines = us_stock_kline_sina("AAPL", 120)
macd = calc_macd(klines)
rsi = calc_rsi(klines)

3.1 移动平均线 MA / EMA

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

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

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

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 布林带

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 提供美股/港股的资产负债表、利润表、现金流量表,中文字段名,按科目行展开。

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/毛利率/资产负债率/流动比率等,按季度报告。

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 模块提供最核心的估值指标。

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

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

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 直接返回完整报表结构,两个互补。

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

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 申请授权。

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"]

用法

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(后备 · 无希腊字母)

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 申请。

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

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/资产/负债等。

def sec_xbrl_facts(cik: str, metrics: list[str] = None) -> dict:
    """
    SEC EDGAR XBRL 结构化财务数据
    cik: CIK号(10位补零)
    metrics: 要提取的指标名,如 ["RevenueFromContractWithCustomerExcludingAssessedTax",
             "NetIncomeLoss", "EarningsPerShareDiluted"]
             不传则返回所有可用指标名列表
    
    返回: {"company": ..., "metrics": {"Revenue": [{end, val, form, filed}, ...], ...}}
    """
    url = f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json"
    r = requests.get(url, headers=SEC_HEADERS, timeout=15)
    r.raise_for_status()
    
    facts = r.json()
    us_gaap = facts.get("facts", {}).get("us-gaap", {})
    
    # 如果不传 metrics,返回所有可用指标
    if not metrics:
        available = []
        for k, v in us_gaap.items():
            label = v.get("label", k)
            units = list(v.get("units", {}).keys())
            available.append({"name": k, "label": label, "units": units})
        return {
            "company": facts.get("entityName"),
            "total_metrics": len(available),
            "available_metrics": available,
        }
    
    # 提取指定指标
    result = {}
    for metric_name in metrics:
        metric = us_gaap.get(metric_name, {})
        if not metric:
            result[metric_name] = []
            continue
        
        # 自动选择单位(USD 或 USD/shares)
        units = metric.get("units", {})
        unit_key = "USD" if "USD" in units else list(units.keys())[0] if units else None
        if not unit_key:
            result[metric_name] = []
            continue
        
        entries = units[unit_key]
        # 只取 10-K 和 10-Q
        filtered = [e for e in entries if e.get("form") in ("10-K", "10-Q")]
        result[metric_name] = [{
            "end": e.get("end"),
            "val": e.get("val"),
            "form": e.get("form"),
            "filed": e.get("filed"),
            "fy": e.get("fy"),
            "fp": e.get("fp"),
        } for e in filtered[-20:]]  # 最近20条
    
    return {
        "company": facts.get("entityName"),
        "metrics": result,
    }

常用 XBRL 指标名速查:

指标 XBRL 名
营业收入 RevenueFromContractWithCustomerExcludingAssessedTax 或 Revenues
净利润 NetIncomeLoss
稀释 EPS EarningsPerShareDiluted
基本 EPS EarningsPerShareBasic
总资产 Assets
总负债 Liabilities
股东权益 StockholdersEquity
经营现金流 NetCashProvidedByOperatingActivities
研发费用 ResearchAndDevelopmentExpense
股份回购 PaymentsForRepurchaseOfCommonStock
股息支付 PaymentsOfDividends

Layer 8: 工具层

8.1 股票搜索 — 东财 search API

def stock_search(keyword: str, count: int = 10) -> list[dict]:
    """
    东财股票搜索 — 支持中英文,返回代码+市场+中文名
    keyword: "AAPL" / "苹果" / "Tencent" / "00700" / "特斯拉"
    返回: [{code, name, mkt_num, market_name, security_type}, ...]
    
    mkt_num 即 push2/push2his 的 secid 前缀:
    105=NASDAQ, 106=NYSE, 107=美股ETF, 116=港股
    """
    url = "https://searchapi.eastmoney.com/api/suggest/get"
    params = {
        "input": keyword,
        "type": 14,  # 14=全球市场
        "token": "D43BF722C8E33BDC906FB84D85E326E8",
        "count": count,
    }
    r = requests.get(url, params=params, timeout=10)
    d = r.json()
    
    suggestions = d.get("QuotationCodeTable", {}).get("Data", [])
    result = []
    for s in suggestions:
        mkt = s.get("MktNum", "")
        # 只保留美股和港股
        if str(mkt) not in ("105", "106", "107", "116"):
            continue
        
        market_map = {"105": "NASDAQ", "106": "NYSE", "107": "US_OTHER", "116": "HK"}
        result.append({
            "code": s.get("Code"),
            "name": s.get("Name"),
            "mkt_num": int(mkt),
            "market_name": market_map.get(str(mkt), str(mkt)),
            "security_type": s.get("SecurityTypeName"),
        })
    return result

8.2 股票新闻 — Yahoo Finance search

def stock_news(keyword: str, count: int = 10) -> list[dict]:
    """
    Yahoo Finance 新闻搜索
   

이 파일은 길어서 일부만 표시했습니다. GitHub에서 원본 전체 보기 →

라이선스 전문 보기(Apache-2.0)
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2026 Simon Lin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.