release: v0.6.0(统一对外接口重构)
按「数据类型」合并同类查询接口:一个数据类型 = 一个方法,跨市场自动选路。 - 28 个统一接口(get_universe/get_quotes/get_bars/get_indicators/get_ticks/ get_minutes/get_f10/get_file/get_boards/get_board_of/get_snapshot 等), 标的统一字符串写法(sz000001 / hk00700 / usAAPL / cffex:IFL0); 同名旧方法不再兼容 (market, code) 元组。 - 旧 51 个按通道/市场分裂的接口:33 个保留为 deprecated 别名(1.0 移除), 18 个同名升级为统一接口。公开方法共 63 个。 - 新增库层标的解析 pytdxdata.symbols;数据模型追加 symbol/name/fields 兜底字段。 - 修复:分页器连接泄漏、日期区间 K线返回 0 条(偏移方向探测)、池子全冷却死等。 - 文档/README/SKILL/llms.txt 全量同步;新增 docs/refactor-audit.md 审查报告。 - 测试 127 个用例全绿(含 tests/test_all_interfaces.py 全 63 方法回归)。
This commit is contained in:
1 parent
1bee6b0fc7
commit
3e0beb27a6
33 files changed
+2789
-1270
No files matched your search
@@ -16,7 +16,7 @@ from .models import (
|
||||
XdxrRecord,
|
||||
)
|
||||
|
||||
__version__ = "0.5.0"
|
||||
__version__ = "0.6.0"
|
||||
__all__ = [
|
||||
"TdxData",
|
||||
"Market",
|
||||
|
||||
+1318
-925
File diff suppressed because it is too large.
Load diff
Vendored
+8
-3
@@ -40,7 +40,12 @@ class CacheKey:
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def quote_key(cls, stocks: Sequence[tuple[int, str]]) -> "CacheKey":
|
||||
"""报价键:对股票集规范化排序,顺序无关可命中。"""
|
||||
def quote_key(cls, stocks: Sequence[tuple[int, str]],
|
||||
tag: str = "") -> "CacheKey":
|
||||
"""报价键:对股票集规范化排序,顺序无关可命中。
|
||||
|
||||
``tag`` 区分取数口径(标准五档 / MAC·EX 字段位),不同口径不互相命中。
|
||||
"""
|
||||
norm = sorted(f"{m}:{c}" for m, c in stocks)
|
||||
return cls(category="quote", extra=",".join(norm))
|
||||
extra = ",".join(norm)
|
||||
return cls(category="quote", extra=f"{tag}#{extra}" if tag else extra)
|
||||
+19
-55
@@ -111,26 +111,17 @@ def _pct(price: float, pre: float) -> str:
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def cmd_quotes(td: TdxData, symbols: list[str]) -> None:
|
||||
cn, ex = [], []
|
||||
for sym in symbols:
|
||||
s = parse_symbol(sym)
|
||||
if s.kind == "cn":
|
||||
cn.append((Market(s.market), s.code))
|
||||
else:
|
||||
ex.append((s.market, s.code))
|
||||
for q in await td.get_quotes(cn):
|
||||
_print_cn_quote(q)
|
||||
if ex:
|
||||
from .protocol.commands.ex_proto import GetExInstrumentQuoteCmd
|
||||
for market, code in ex:
|
||||
q = await td._execute_ex(GetExInstrumentQuoteCmd(market, code))
|
||||
_print_ex_quote(market, code, q)
|
||||
quotes = await td.get_quotes(symbols)
|
||||
for q in quotes:
|
||||
_print_quote(q)
|
||||
|
||||
|
||||
def _print_cn_quote(q) -> None:
|
||||
def _print_quote(q) -> None:
|
||||
pct = (q.price / q.pre_close - 1) * 100 if q.pre_close else 0
|
||||
mkt = {31: "港股", 74: "美股"}.get(q.market, "")
|
||||
print("=" * 58)
|
||||
print(" %s %s" % (q.code, q.server_time or datetime.now().strftime("%H:%M:%S")))
|
||||
label = "%s %s" % (mkt, q.code) if mkt else "%s %s" % (q.code, q.server_time or datetime.now().strftime("%H:%M:%S"))
|
||||
print(" %s" % label)
|
||||
print(" 最新 %-10.2f 涨跌 %+8.2f (%+.2f%%)" % (q.price, q.price - q.pre_close, pct))
|
||||
print(" 今开 %-10.2f 最高 %.2f 最低 %.2f" % (q.open, q.high, q.low))
|
||||
print(" 昨收 %-10.2f 成交量 %s 成交额 %s" % (q.pre_close, _fmt_num(q.vol), _fmt_num(q.amount)))
|
||||
@@ -144,31 +135,9 @@ def _print_cn_quote(q) -> None:
|
||||
print()
|
||||
|
||||
|
||||
def _print_ex_quote(market: int, code: str, q: dict | None) -> None:
|
||||
if not q:
|
||||
print(" %s: 无报价数据" % code)
|
||||
return
|
||||
price, pre = q.get("price") or 0, q.get("pre_close") or 0
|
||||
mkt = {31: "港股", 74: "美股"}.get(market, "扩展")
|
||||
print("=" * 58)
|
||||
print(" %s %s" % (mkt, code))
|
||||
print(" 最新 %-10.2f 涨跌 %+8.2f (%s)" % (price, price - pre, _pct(price, pre)))
|
||||
print(" 今开 %-10.2f 最高 %.2f 最低 %.2f" % (
|
||||
q.get("open") or 0, q.get("high") or 0, q.get("low") or 0))
|
||||
print(" 昨收 %-10.2f 总量 %s" % (pre, _fmt_num(q.get("zongliang") or 0)))
|
||||
print()
|
||||
|
||||
|
||||
async def cmd_kline(td: TdxData, sym: str, period: KlinePeriod, count: int,
|
||||
start: int, adjust: Adjust) -> None:
|
||||
s = parse_symbol(sym)
|
||||
if s.kind == "cn":
|
||||
bars = await td.get_kline(Market(s.market), s.code, period, start=start,
|
||||
count=count, adjust=adjust)
|
||||
elif s.kind == "index":
|
||||
bars = await td.get_index_kline(Market(s.market), s.code, period, start=start, count=count)
|
||||
else:
|
||||
bars = await td.get_kline(ExMarket(s.market), s.code, period, start=start, count=count)
|
||||
bars = await td.get_bars(sym, period, start=start, count=count, adjust=adjust)
|
||||
print("%s K线 (%s, %d根):" % (sym, period.name, len(bars)))
|
||||
print(" %-12s %8s %8s %8s %8s %12s" % ("日期", "开盘", "最高", "最低", "收盘", "成交量"))
|
||||
for b in bars:
|
||||
@@ -256,8 +225,7 @@ async def cmd_list(td: TdxData, market: str, count: int) -> None:
|
||||
|
||||
|
||||
async def cmd_auction(td: TdxData, sym: str) -> None:
|
||||
s = parse_symbol(sym)
|
||||
items = await td.get_auction(Market(s.market), s.code)
|
||||
items = await td.get_auction(sym)
|
||||
print("%s 集合竞价 (%d条):" % (sym, len(items)))
|
||||
for a in items:
|
||||
print(" %s 价格=%.3f 量=%d %s" % (
|
||||
@@ -266,7 +234,7 @@ async def cmd_auction(td: TdxData, sym: str) -> None:
|
||||
|
||||
|
||||
async def cmd_unusual(td: TdxData, market: str, count: int) -> None:
|
||||
items = await td.get_unusual(MARKET_NAMES[market], count=count)
|
||||
items = await td.get_unusual(market, count=count)
|
||||
print("市场异动 (%d条):" % len(items))
|
||||
for u in items:
|
||||
print(" %s %s %s" % (getattr(u, "code", ""), getattr(u, "name", ""),
|
||||
@@ -274,8 +242,7 @@ async def cmd_unusual(td: TdxData, market: str, count: int) -> None:
|
||||
|
||||
|
||||
async def cmd_xdxr(td: TdxData, sym: str) -> None:
|
||||
s = parse_symbol(sym)
|
||||
items = await td.get_xdxr(Market(s.market), s.code)
|
||||
items = await td.get_xdxr(sym)
|
||||
print("%s 除权除息 (%d条):" % (sym, len(items)))
|
||||
for x in items[:20]:
|
||||
print(" %s 送%g 配%g 派%g" % (
|
||||
@@ -284,23 +251,20 @@ async def cmd_xdxr(td: TdxData, sym: str) -> None:
|
||||
|
||||
|
||||
async def cmd_finance(td: TdxData, sym: str) -> None:
|
||||
s = parse_symbol(sym)
|
||||
f = await td.get_finance(Market(s.market), s.code)
|
||||
if not f:
|
||||
fins = await td.get_finance(sym)
|
||||
if not fins:
|
||||
print("无财务数据")
|
||||
return
|
||||
for k, v in asdict(f).items():
|
||||
for k, v in asdict(fins[0]).items():
|
||||
print(" %-24s %s" % (k, v))
|
||||
|
||||
|
||||
async def cmd_flow(td: TdxData, sym: str) -> None:
|
||||
s = parse_symbol(sym)
|
||||
f = await td.get_capital_flow(Market(s.market), s.code)
|
||||
if isinstance(f, dict):
|
||||
items = f.items()
|
||||
else:
|
||||
items = asdict(f).items()
|
||||
for k, v in items:
|
||||
flows = await td.get_capital_flow(sym)
|
||||
if not flows:
|
||||
print("无资金流向数据")
|
||||
return
|
||||
for k, v in asdict(flows[0]).items():
|
||||
print(" %-20s %s" % (k, v))
|
||||
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ class Adjust(IntEnum):
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SecurityBar:
|
||||
"""K线记录(价格单位:元)"""
|
||||
"""K线记录(价格单位:元)。跨市场统一模型(A股/港股/美股/期货共用)。"""
|
||||
market: int
|
||||
code: str
|
||||
open: float
|
||||
@@ -108,6 +108,7 @@ class SecurityBar:
|
||||
day: int
|
||||
hour: int = 0
|
||||
minute: int = 0
|
||||
symbol: str = "" # 规范化标的串(sz000001 / hk00700),由 API 层填充
|
||||
|
||||
@property
|
||||
def datetime(self) -> datetime:
|
||||
@@ -120,9 +121,26 @@ class IndexBar(SecurityBar):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class IndicatorSet:
|
||||
"""K线 + 技术指标组合(``TdxData.get_indicators`` 的返回单元)。
|
||||
|
||||
``indicators`` 里每个序列与 ``bars`` 等长、尾部对齐;预热期为 ``None`` 的指标
|
||||
(如 BOLL 前三档)保留 ``None``。
|
||||
"""
|
||||
symbol: str
|
||||
bars: list[SecurityBar] = field(default_factory=list)
|
||||
indicators: dict[str, list[float | None]] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SecurityQuote:
|
||||
"""实时五档报价"""
|
||||
"""报价(跨市场统一模型)。
|
||||
|
||||
A股(标准通道):五档 ``bid``/``ask`` + 买卖量 + 涨跌停价齐全,``name`` 为空。
|
||||
A股(``fields=[...]`` 走 MAC 0x122B):``name`` 与 ``fields`` 齐全,五档为空。
|
||||
扩展市场(港股/美股/期货):``name`` + 基础价量在属性上,其余字段位在 ``fields``。
|
||||
"""
|
||||
market: int
|
||||
code: str
|
||||
price: float
|
||||
@@ -144,39 +162,51 @@ class SecurityQuote:
|
||||
limit_down: float = 0.0 # 跌停价
|
||||
decimal_point: int = 2 # 价格小数位
|
||||
open_amount: float = 0.0 # 开盘金额(个股)
|
||||
symbol: str = "" # 规范化标的串
|
||||
name: str = "" # 名称(仅 MAC/EX 通道有)
|
||||
fields: dict[str, float] = field(default_factory=dict) # 原始字段位("0x7" 等)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SecurityInfo:
|
||||
"""证券列表条目"""
|
||||
"""标的清单条目(跨市场统一模型:A股证券列表 + 扩展市场商品列表)"""
|
||||
market: int
|
||||
code: str
|
||||
name: str
|
||||
volunit: int
|
||||
decimal_point: int
|
||||
pre_close: float
|
||||
symbol: str = "" # 规范化标的串
|
||||
kind: str = "" # 分类描述(扩展市场的 category/desc)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TransactionRecord:
|
||||
"""逐笔成交(MAC通道含 trade_count=成交笔数)"""
|
||||
"""逐笔成交(跨市场统一模型;A股 MAC 通道含 trade_count=成交笔数)"""
|
||||
market: int
|
||||
code: str
|
||||
time: str # HH:MM:SS
|
||||
time: str # HH:MM:SS(扩展市场为 HH:MM)
|
||||
price: float
|
||||
vol: float # 手(MAC逐笔)
|
||||
trade_count: int # 成交笔数(MAC=逐笔记录字段;标准当日逐笔协议也有但需单独解析)
|
||||
bs_flag: int # 1=主动买 0=主动卖
|
||||
symbol: str = ""
|
||||
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(增仓等)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MinuteBar:
|
||||
"""分时数据"""
|
||||
"""分时(跨市场统一模型;A股 MAC 0x122D / 扩展市场 0x122D 同构)"""
|
||||
price: float
|
||||
vol: float
|
||||
avg_price: float = 0.0 # 均价(协议第2字段)
|
||||
hour: int = 0
|
||||
minute: int = 0
|
||||
symbol: str = ""
|
||||
market: int = 0
|
||||
code: str = ""
|
||||
date: int = 0 # YYYYMMDD
|
||||
fields: dict[str, float] = field(default_factory=dict) # 扩展市场额外字段(动量等)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -201,6 +231,7 @@ class XdxrRecord:
|
||||
qian_zongguben: float = 0.0
|
||||
panhou_liutong: float = 0.0
|
||||
hou_zongguben: float = 0.0
|
||||
symbol: str = ""
|
||||
|
||||
@property
|
||||
def date(self) -> str:
|
||||
@@ -248,6 +279,7 @@ class FinanceRecord:
|
||||
weifen_lirun: float = 0.0
|
||||
meigujing_zichan: float = 0.0
|
||||
reserve2: float = 0.0
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
# ===== MAC 扩展命令模型 =====
|
||||
@@ -268,15 +300,21 @@ class BoardInfo:
|
||||
symbol_price: float = 0.0
|
||||
symbol_rise_speed: float = 0.0
|
||||
symbol_pre_close: float = 0.0
|
||||
symbol: str = "" # 规范化标的串(板块码,如 sh881001)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MemberQuote:
|
||||
"""板块成分股报价(MAC自定义字段)"""
|
||||
"""板块成分/自定义字段报价的**协议层原始记录**。
|
||||
|
||||
API 层会把它归一成 :class:`SecurityQuote`(``fields`` 原样保留、基础字段位
|
||||
填进属性),所以普通调用不会看到本类。
|
||||
"""
|
||||
market: int
|
||||
code: str
|
||||
name: str
|
||||
fields: dict[str, float] = field(default_factory=dict)
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -287,6 +325,7 @@ class BelongBoard:
|
||||
board_name: str
|
||||
close: float
|
||||
pre_close: float
|
||||
symbol: str = "" # 被查询的个股(非板块)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -296,6 +335,7 @@ class AuctionItem:
|
||||
price: float
|
||||
matched: int
|
||||
unmatched: int
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -308,6 +348,7 @@ class UnusualItem:
|
||||
desc: str
|
||||
value: float
|
||||
time: str
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -328,6 +369,7 @@ class SymbolSnapshot:
|
||||
amount: float
|
||||
turnover: float
|
||||
avg_price: float
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -361,6 +403,7 @@ class CapitalFlow:
|
||||
sell5: float
|
||||
big5: float
|
||||
mid5: float
|
||||
symbol: str = ""
|
||||
|
||||
|
||||
# ===== 服务器文件解析模型(板块/行业/历史专业财报) =====
|
||||
|
||||
@@ -211,6 +211,10 @@ class DynamicPool:
|
||||
# 2. 可扩容(未达上限且有可用服务器)→ 新建连接
|
||||
if self._total < self.max_size:
|
||||
host = self._next_available_server()
|
||||
if host is None:
|
||||
# 兜底:全部服务器都在冷却中,而池子未满 —— 此时等 release
|
||||
# 永远等不到(没人持有),只能挑最健康的一台顶着冷却重试
|
||||
host = self._next_available_server(ignore_cooldown=True)
|
||||
if host:
|
||||
try:
|
||||
pc = await self._new_conn(host)
|
||||
@@ -244,18 +248,19 @@ class DynamicPool:
|
||||
break
|
||||
return out
|
||||
|
||||
def _next_available_server(self) -> str | None:
|
||||
def _next_available_server(self, *, ignore_cooldown: bool = False) -> str | None:
|
||||
ranked = self.health.rank(self.servers)
|
||||
# 1. 优先选未冷却且未达并发上限的服务器
|
||||
for h in ranked:
|
||||
if self.health.in_cooldown(h):
|
||||
if self.health.in_cooldown(h) and not ignore_cooldown:
|
||||
continue
|
||||
if self._server_count.get(h, 0) < self.per_server_cap:
|
||||
return h
|
||||
# 2. 兜底:仅从「未冷却」的已占用服务器里随机复用(避免反复打坏服务器)
|
||||
alive = [
|
||||
h for h in ranked
|
||||
if not self.health.in_cooldown(h) and self._server_count.get(h, 0) > 0
|
||||
if (ignore_cooldown or not self.health.in_cooldown(h))
|
||||
and self._server_count.get(h, 0) > 0
|
||||
]
|
||||
return random.choice(alive) if alive else None
|
||||
|
||||
|
||||
@@ -36,6 +36,15 @@ class PageResult:
|
||||
items: list[Any]
|
||||
|
||||
|
||||
class _Slot:
|
||||
"""worker 当前持有的连接槽:失败换连时原地更新,保证最终能精确归还。"""
|
||||
|
||||
__slots__ = ("pc",)
|
||||
|
||||
def __init__(self, pc: PooledConnection) -> None:
|
||||
self.pc: PooledConnection | None = pc
|
||||
|
||||
|
||||
class Paginator:
|
||||
"""用至多 concurrency 个连接并行拉取分页数据。"""
|
||||
|
||||
@@ -64,22 +73,27 @@ class Paginator:
|
||||
conns = await self.pool.acquire_many(eff_conc)
|
||||
if not conns:
|
||||
raise PoolTimeoutError("连接池获取超时(无可用连接)")
|
||||
# 每个 worker 一个连接槽:中途换连会更新槽内引用,
|
||||
# 归还时按槽归还(否则换掉的新连接会漏还,把池耗干)
|
||||
slots = [_Slot(pc) for pc in conns]
|
||||
try:
|
||||
stop = asyncio.Event()
|
||||
out: list[PageResult] = []
|
||||
out_lock = asyncio.Lock()
|
||||
k = len(conns)
|
||||
k = len(slots)
|
||||
workers = [
|
||||
asyncio.create_task(
|
||||
self._worker(wid, conns[wid % k], jobs[wid::k], cmd_factory,
|
||||
self._worker(slots[wid], jobs[wid::k], cmd_factory,
|
||||
stop, out, out_lock, spec)
|
||||
)
|
||||
for wid in range(k)
|
||||
]
|
||||
await asyncio.gather(*workers)
|
||||
finally:
|
||||
for pc in conns:
|
||||
await self.pool.release(pc)
|
||||
for s in slots:
|
||||
if s.pc is not None:
|
||||
pc, s.pc = s.pc, None
|
||||
await self.pool.release(pc)
|
||||
return self._assemble(out, spec.ordered)
|
||||
|
||||
def _plan_starts(self, spec: PageSpec) -> list[tuple[int, int]]:
|
||||
@@ -102,49 +116,47 @@ class Paginator:
|
||||
return jobs
|
||||
|
||||
async def _worker(
|
||||
self, wid: int, conn: PooledConnection, jobs: list[tuple[int, int]],
|
||||
self, slot: _Slot, jobs: list[tuple[int, int]],
|
||||
cmd_factory: Callable[[int, int], Any], stop: asyncio.Event,
|
||||
out: list[PageResult], out_lock: asyncio.Lock, spec: PageSpec,
|
||||
) -> None:
|
||||
current = conn
|
||||
for start, count in jobs:
|
||||
if stop.is_set():
|
||||
if stop.is_set() or slot.pc is None:
|
||||
return
|
||||
items, current = await self._fetch_one(
|
||||
current, cmd_factory(start, count), count)
|
||||
if items is None:
|
||||
continue # 该页失败(strict=False 时留空)
|
||||
items, ok = await self._fetch_one(slot, cmd_factory(start, count), count)
|
||||
if not ok:
|
||||
return # 换连接失败 → 本 worker 退出(该页留空)
|
||||
async with out_lock:
|
||||
out.append(PageResult(start=start, count=count, items=items))
|
||||
if spec.stop_when_short and len(items) < count:
|
||||
stop.set()
|
||||
return
|
||||
|
||||
async def _fetch_one(self, conn: PooledConnection, cmd, page_size: int):
|
||||
async def _fetch_one(self, slot: _Slot, cmd, page_size: int):
|
||||
"""单页拉取,失败换连接重试。
|
||||
|
||||
返回 (items, current_conn) — current_conn 始终指向当前可用连接,
|
||||
worker 据此更新自己的连接引用,避免跨页使用已关闭连接。
|
||||
返回 ``(items, ok)``。失败时连接一律 ``broken=True`` 归还并把槽清空,
|
||||
调用方据此退出,不会留下悬空引用。
|
||||
"""
|
||||
current = conn
|
||||
for attempt in range(self.retries + 1):
|
||||
try:
|
||||
result = await current.execute(cmd)
|
||||
return (list(result) if result is not None else []), current
|
||||
result = await slot.pc.execute(cmd) # type: ignore[union-attr]
|
||||
return (list(result) if result is not None else []), True
|
||||
except Exception as e:
|
||||
if slot.pc is not None:
|
||||
await self.pool.release(slot.pc, broken=True)
|
||||
slot.pc = None
|
||||
if attempt >= self.retries:
|
||||
if self.strict:
|
||||
raise
|
||||
log.warning("分页拉取失败(strict=False留空): %s", e)
|
||||
return None, current
|
||||
# 换连接重试
|
||||
await self.pool.release(current, broken=True)
|
||||
return None, False
|
||||
try:
|
||||
current = await self.pool.acquire(timeout=3.0)
|
||||
slot.pc = await self.pool.acquire(timeout=3.0)
|
||||
except PoolTimeoutError:
|
||||
log.warning("分页重试获取连接失败,跳过该页: %s", e)
|
||||
return None, current
|
||||
return None, current
|
||||
return None, False
|
||||
return None, False
|
||||
|
||||
def _assemble(self, results: list[PageResult], ordered: bool) -> list[Any]:
|
||||
if ordered:
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""标的代码解析:全库唯一的字符串口径。
|
||||
|
||||
统一写法(也是 CLI 的写法)::
|
||||
|
||||
sz000001 / sh600000 / bj920992 A股(6位代码,必须带市场前缀)
|
||||
hk00700 港股主板(5位)
|
||||
usAAPL 美股(ticker)
|
||||
cffex:IFL0 / zz:AP0 期货(交易所前缀 + 合约,可带冒号)
|
||||
000001 裸 6 位数字 = 沪市指数
|
||||
|
||||
**裸 6 位数字只当作沪市指数**:A股代码不唯一(``000001`` 既是上证指数也是平安银行),
|
||||
要股票请写全前缀 ``sh000001`` / ``sz000001``。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from .models import ExMarket, Market
|
||||
|
||||
# 通道:cn=标准/MAC A股通道,ex=扩展市场通道(端口 7727)
|
||||
CN = "cn"
|
||||
EX = "ex"
|
||||
INDEX = "index"
|
||||
|
||||
_CN_ALIASES: dict[str, Market] = {
|
||||
"sz": Market.SZ,
|
||||
"sh": Market.SH,
|
||||
"bj": Market.BJ,
|
||||
}
|
||||
_CN_PREFIX: dict[int, str] = {int(m): k for k, m in _CN_ALIASES.items()}
|
||||
|
||||
# EX 常用别名(短前缀优先;其余成员用枚举名小写,如 hk_gem:08001)
|
||||
_EX_ALIASES: dict[str, ExMarket] = {
|
||||
"hk": ExMarket.HK_MAIN_BOARD,
|
||||
"us": ExMarket.US_STOCK,
|
||||
"zz": ExMarket.ZZ_FUTURES,
|
||||
"dl": ExMarket.DL_FUTURES,
|
||||
"shf": ExMarket.SH_FUTURES,
|
||||
"cffex": ExMarket.CFFEX_FUTURES,
|
||||
"gz": ExMarket.GZ_FUTURES,
|
||||
}
|
||||
_EX_PREFIX: dict[int, str] = {int(m): k for k, m in _EX_ALIASES.items()}
|
||||
|
||||
ALL = "all"
|
||||
|
||||
|
||||
def _ex_by_name(name: str) -> ExMarket | None:
|
||||
"""按枚举名匹配(hk_main_board / us_stock / ...),保证 format→parse 可往返。"""
|
||||
key = name.upper()
|
||||
for member in ExMarket:
|
||||
if member.name == key:
|
||||
return member
|
||||
return None
|
||||
|
||||
|
||||
def _lookup(text: str) -> tuple[int, str] | None:
|
||||
"""前缀 -> (市场号, 通道)。"""
|
||||
if text in _CN_ALIASES:
|
||||
return int(_CN_ALIASES[text]), CN
|
||||
if text in _EX_ALIASES:
|
||||
return int(_EX_ALIASES[text]), EX
|
||||
member = _ex_by_name(text)
|
||||
if member is not None:
|
||||
return int(member), EX
|
||||
return None
|
||||
|
||||
|
||||
def _hint() -> str:
|
||||
cn = "/".join(sorted(_CN_ALIASES))
|
||||
ex = "/".join(sorted(_EX_ALIASES))
|
||||
return f"A股: {cn};扩展市场: {ex}(详见 pytdxdata.models.ExMarket)"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Symbol:
|
||||
"""解析后的标的。``kind``: cn=A股 / ex=扩展市场 / index=裸数字指数。"""
|
||||
|
||||
market: int
|
||||
code: str
|
||||
kind: str
|
||||
raw: str = ""
|
||||
|
||||
@property
|
||||
def is_ex(self) -> bool:
|
||||
return self.kind == EX
|
||||
|
||||
@property
|
||||
def is_index(self) -> bool:
|
||||
return self.kind == INDEX
|
||||
|
||||
@property
|
||||
def channel(self) -> str:
|
||||
"""路由通道:ex 走扩展市场池,其余走标准/MAC A股池。"""
|
||||
return EX if self.is_ex else "std"
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
"""规范化写法,同时用作记录上的 ``.symbol``。"""
|
||||
if self.is_index:
|
||||
return self.code
|
||||
return format_symbol(self.market, self.code)
|
||||
|
||||
def as_pair(self) -> tuple[int, str]:
|
||||
"""(市场号, 代码) 元组(协议层用)。"""
|
||||
return self.market, self.code
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.text
|
||||
|
||||
|
||||
def _prefix_for(market: int) -> str | None:
|
||||
"""市场号 -> 短前缀;无短别名的扩展市场回退到枚举名小写。"""
|
||||
m = int(market)
|
||||
prefix = _CN_PREFIX.get(m) or _EX_PREFIX.get(m)
|
||||
if prefix is not None:
|
||||
return prefix
|
||||
try:
|
||||
return ExMarket(m).name.lower()
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def format_symbol(market: int, code: str) -> str:
|
||||
"""(市场号, 代码) -> 规范化字符串(``1, "600000"`` -> ``"sh600000"``)。"""
|
||||
code = str(code).strip()
|
||||
if not code:
|
||||
return ""
|
||||
prefix = _prefix_for(market)
|
||||
if prefix is None:
|
||||
return code
|
||||
# 2 字母前缀贴代码(hk00700),长前缀用冒号(cffex:IFL0 / hk_gem:08001)
|
||||
return f"{prefix}:{code}" if len(prefix) > 2 else f"{prefix}{code}"
|
||||
|
||||
|
||||
def market_name(market: int) -> str:
|
||||
"""市场号 -> 市场选择器字符串(``1`` -> ``"sh"``,``31`` -> ``"hk"``)。
|
||||
|
||||
用于把旧接口的市场号参数转成统一接口要的市场选择器。
|
||||
"""
|
||||
prefix = _prefix_for(market)
|
||||
if prefix is None:
|
||||
raise ValueError(f"未知市场号: {market}")
|
||||
return prefix
|
||||
|
||||
|
||||
def parse_symbol(text: str) -> Symbol:
|
||||
"""字符串 -> Symbol。无法识别时抛 ValueError 并列出可用前缀。"""
|
||||
raw = text
|
||||
sym = str(text).strip()
|
||||
if not sym:
|
||||
raise ValueError("标的为空")
|
||||
|
||||
if ":" in sym:
|
||||
head, code = sym.split(":", 1)
|
||||
head, code = head.strip().lower(), code.strip()
|
||||
hit = _lookup(head)
|
||||
if hit is None:
|
||||
raise ValueError(f"未知市场前缀: {head}({_hint()})")
|
||||
if not code:
|
||||
raise ValueError(f"缺少代码: {raw}")
|
||||
return Symbol(market=hit[0], code=code.upper(), kind=hit[1], raw=raw)
|
||||
|
||||
head, code = sym[:2].lower(), sym[2:]
|
||||
hit = _lookup(head)
|
||||
if hit is not None and code:
|
||||
return Symbol(market=hit[0], code=code.upper(), kind=hit[1], raw=raw)
|
||||
|
||||
if sym.isdigit() and len(sym) == 6:
|
||||
# 裸 6 位 = 沪市指数(A股代码不唯一,股票必须带前缀)
|
||||
return Symbol(market=int(Market.SH), code=sym, kind=INDEX, raw=raw)
|
||||
|
||||
raise ValueError(f"无法识别标的: {raw}({_hint()};裸6位数字=沪市指数)")
|
||||
|
||||
|
||||
def parse_symbols(symbols: str | Sequence[str] | None) -> list[Symbol]:
|
||||
"""接受单个字符串 / 字符串序列 / Symbol 序列,去重并保持输入顺序。"""
|
||||
if symbols is None:
|
||||
raise ValueError("symbols 不能为空")
|
||||
items: list = [symbols] if isinstance(symbols, str) else list(symbols)
|
||||
if not items:
|
||||
raise ValueError("symbols 不能为空")
|
||||
out: list[Symbol] = []
|
||||
seen: set[tuple[int, str]] = set()
|
||||
for item in items:
|
||||
sym = item if isinstance(item, Symbol) else parse_symbol(item)
|
||||
if sym.as_pair() in seen:
|
||||
continue
|
||||
seen.add(sym.as_pair())
|
||||
out.append(sym)
|
||||
return out
|
||||
|
||||
|
||||
def cn_markets() -> list[int]:
|
||||
"""A股市场号(深/沪/北)。"""
|
||||
return [int(m) for m in Market]
|
||||
|
||||
|
||||
def ex_markets() -> list[int]:
|
||||
"""扩展市场号,按枚举值升序。"""
|
||||
return sorted(int(m) for m in ExMarket)
|
||||
|
||||
|
||||
def market_targets(text: str | None) -> list[tuple[int, str]]:
|
||||
"""市场选择器 -> [(市场号, 通道)];``None`` / ``"all"`` = 全部市场。
|
||||
|
||||
市场号在两条通道里会撞车(``Market.SH=1`` 与 ``ExMarket.TEMP_STOCK=1``),
|
||||
所以必须带通道一起返回,调用方按通道分别请求。
|
||||
"""
|
||||
key = "" if text is None else str(text).strip().lower()
|
||||
if not key or key == ALL:
|
||||
return ([(m, CN) for m in cn_markets()]
|
||||
+ [(m, EX) for m in ex_markets()])
|
||||
hit = _lookup(key)
|
||||
if hit is None:
|
||||
raise ValueError(f"未知市场: {text}({_hint()};全部用 all)")
|
||||
return [hit]
|
||||
|
||||
|
||||
def parse_market(text: str | None) -> int | None:
|
||||
"""市场选择器 -> 单个市场号;``None`` / ``"all"`` 返回 None。
|
||||
|
||||
只用于「本来就是单市场」的接口(如市场异动)。需要跨市场时用
|
||||
:func:`market_targets`。
|
||||
"""
|
||||
targets = market_targets(text)
|
||||
return None if len(targets) > 1 else targets[0][0]
|
||||
|
||||
|
||||
def is_cn_index(market: int, code: str) -> bool:
|
||||
"""A股指数代码判定:88开头板块指数 / 沪市000 / 深市399。
|
||||
|
||||
深市股票 000001 不是指数,必须带市场判断。
|
||||
"""
|
||||
code = str(code)
|
||||
return (
|
||||
code.startswith("88")
|
||||
or (code.startswith("000") and int(market) == int(Market.SH))
|
||||
or (code.startswith("399") and int(market) == int(Market.SZ))
|
||||
)
|
||||
Reference in new issue
Block a user