Tortoise/sidecar/symbols.py
2026-06-24 16:50:59 +08:00

59 lines
2.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""股票代码标准化工具。"""
from __future__ import annotations
from typing import Tuple
def normalize_symbol(symbol: str) -> str:
"""
功能说明:把股票代码统一为交易所前缀格式。
参数说明symbol 为 600000、sh600000、SZ000001 等格式。
返回值说明:返回小写交易所前缀格式,例如 sh600000。
注意事项:仅覆盖 A 股常用沪深北代码规则。
"""
text = symbol.strip().lower().replace(".", "")
if text.startswith(("sh", "sz", "bj")) and len(text) == 8:
return text
code = text[-6:]
if code.startswith(("6", "5", "9")):
return "sh" + code
if code.startswith(("0", "1", "2", "3")):
return "sz" + code
if code.startswith(("4", "8")):
return "bj" + code
raise ValueError("无法识别股票代码: %s" % symbol)
def split_symbol(symbol: str) -> Tuple[str, str]:
"""
功能说明:拆分标准股票代码。
参数说明symbol 为任意支持格式的股票代码。
返回值说明:返回二元组 (market, code),例如 (sh, 600000)。
注意事项:会先调用 normalize_symbol 做格式标准化。
"""
normalized = normalize_symbol(symbol)
return normalized[:2], normalized[2:]
def mootdx_market(symbol: str) -> int:
"""
功能说明:转换 mootdx 所需市场编号。
参数说明symbol 为任意支持格式的股票代码。
返回值说明:沪市返回 1深市和北交所返回 0。
注意事项mootdx 对北交所支持随版本变化,这里按通达信常见约定归入 0。
"""
market, _ = split_symbol(symbol)
return 1 if market == "sh" else 0
def is_index_symbol(symbol: str) -> bool:
"""
功能说明:判断代码是否为常见沪深指数代码。
参数说明symbol 为任意支持格式的股票或指数代码。
返回值说明:指数代码返回 True其他代码返回 False。
注意事项:仅按沪市 000、深市 399 前缀识别,避免影响普通股票 K 线。
"""
market, code = split_symbol(symbol)
return (market == "sh" and code.startswith("000")) or (market == "sz" and code.startswith("399"))