market-quote 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kwai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: market-quote
3
+ Version: 0.1.0
4
+ Summary: A lightweight Python SDK for China A-share real-time quotes and minute bars
5
+ Author: Kwai
6
+ License-Expression: MIT
7
+ Keywords: china-stock,a-share,market-data,quote,etf
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Office/Business :: Financial :: Investment
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests<3,>=2.28
21
+ Provides-Extra: tdx
22
+ Requires-Dist: pytdx>=1.72; extra == "tdx"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest<9,>=8; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # market-quote
28
+
29
+ 面向 A 股指数、股票和 ETF 的轻量行情 SDK。底层包只负责请求、解析和统一数据模型,不依赖 Redis、MongoDB 或业务调度器。
30
+
31
+ 当前支持:
32
+
33
+ - 指数、股票、ETF 实时行情;
34
+ - 五档买卖盘;
35
+ - 指数、股票、ETF 的 1 分钟 K 线;
36
+ - 批量切片、并发、限速和失败明细;
37
+ - 腾讯 HTTP 默认后端;
38
+ - 可选通达信后端。
39
+
40
+ ## 安装
41
+
42
+ ```bash
43
+ pip install -e .
44
+ ```
45
+
46
+ 需要通达信后端时:
47
+
48
+ ```bash
49
+ pip install -e '.[tdx]'
50
+ ```
51
+
52
+ ## 快速使用
53
+
54
+ ```python
55
+ from market_quote import MarketQuoteClient
56
+
57
+ with MarketQuoteClient() as client:
58
+ result = client.get_quotes([
59
+ "sh000001", # 上证指数
60
+ "sh600519", # 股票
61
+ "sh510300", # ETF
62
+ ])
63
+ for quote in result.items.values():
64
+ print(quote.symbol, quote.name, quote.price, quote.change_percent)
65
+
66
+ bars = client.get_minute_bars("sh600519", count=240)
67
+ print(bars[-1])
68
+ ```
69
+
70
+ 批量分钟线:
71
+
72
+ ```python
73
+ with MarketQuoteClient(concurrency=8, max_rps=20) as client:
74
+ result = client.get_minute_bars_batch(
75
+ ["sh000001", "sh600519", "sh510300"],
76
+ count=240,
77
+ )
78
+ print(result.items.keys())
79
+ print(result.empty)
80
+ print(result.failed)
81
+ ```
82
+
83
+ ## Provider
84
+
85
+ 默认配置:
86
+
87
+ ```python
88
+ MarketQuoteClient(
89
+ realtime_provider="tencent",
90
+ minute_provider="tencent",
91
+ )
92
+ ```
93
+
94
+ 使用通达信分钟线:
95
+
96
+ ```python
97
+ MarketQuoteClient(
98
+ minute_provider="tdx",
99
+ tdx_hosts=[("sztdx.gtjas.com", 7709)],
100
+ )
101
+ ```
102
+
103
+ `minute_provider="auto"` 时,指数优先使用通达信,股票和 ETF 使用腾讯;通达信不可用时自动回退腾讯。由于资产类型无法始终从六位代码准确判断,可通过 `instrument_types` 显式传入:
104
+
105
+ ```python
106
+ result = client.get_minute_bars_batch(
107
+ ["sh000001", "sh600519", "sh510300"],
108
+ instrument_types={
109
+ "sh000001": "index",
110
+ "sh600519": "stock",
111
+ "sh510300": "etf",
112
+ },
113
+ )
114
+ ```
115
+
116
+ ## 字段单位
117
+
118
+ - 价格:元;
119
+ - `volume_lots`:手;
120
+ - `amount_cny`:元;
121
+ - `change_percent`:百分数,`-1.67` 表示 `-1.67%`;
122
+ - 时间:带 `Asia/Shanghai` 时区的 `datetime`;
123
+ - 空值:`None`,不会强制转换为 `0`。
124
+
125
+ ## 边界
126
+
127
+ 当前第一版支持沪深市场的 `sh`、`sz` symbol。北交所尚未经过接口验证,会明确拒绝而不是错误映射到沪深市场。
128
+
@@ -0,0 +1,102 @@
1
+ # market-quote
2
+
3
+ 面向 A 股指数、股票和 ETF 的轻量行情 SDK。底层包只负责请求、解析和统一数据模型,不依赖 Redis、MongoDB 或业务调度器。
4
+
5
+ 当前支持:
6
+
7
+ - 指数、股票、ETF 实时行情;
8
+ - 五档买卖盘;
9
+ - 指数、股票、ETF 的 1 分钟 K 线;
10
+ - 批量切片、并发、限速和失败明细;
11
+ - 腾讯 HTTP 默认后端;
12
+ - 可选通达信后端。
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ pip install -e .
18
+ ```
19
+
20
+ 需要通达信后端时:
21
+
22
+ ```bash
23
+ pip install -e '.[tdx]'
24
+ ```
25
+
26
+ ## 快速使用
27
+
28
+ ```python
29
+ from market_quote import MarketQuoteClient
30
+
31
+ with MarketQuoteClient() as client:
32
+ result = client.get_quotes([
33
+ "sh000001", # 上证指数
34
+ "sh600519", # 股票
35
+ "sh510300", # ETF
36
+ ])
37
+ for quote in result.items.values():
38
+ print(quote.symbol, quote.name, quote.price, quote.change_percent)
39
+
40
+ bars = client.get_minute_bars("sh600519", count=240)
41
+ print(bars[-1])
42
+ ```
43
+
44
+ 批量分钟线:
45
+
46
+ ```python
47
+ with MarketQuoteClient(concurrency=8, max_rps=20) as client:
48
+ result = client.get_minute_bars_batch(
49
+ ["sh000001", "sh600519", "sh510300"],
50
+ count=240,
51
+ )
52
+ print(result.items.keys())
53
+ print(result.empty)
54
+ print(result.failed)
55
+ ```
56
+
57
+ ## Provider
58
+
59
+ 默认配置:
60
+
61
+ ```python
62
+ MarketQuoteClient(
63
+ realtime_provider="tencent",
64
+ minute_provider="tencent",
65
+ )
66
+ ```
67
+
68
+ 使用通达信分钟线:
69
+
70
+ ```python
71
+ MarketQuoteClient(
72
+ minute_provider="tdx",
73
+ tdx_hosts=[("sztdx.gtjas.com", 7709)],
74
+ )
75
+ ```
76
+
77
+ `minute_provider="auto"` 时,指数优先使用通达信,股票和 ETF 使用腾讯;通达信不可用时自动回退腾讯。由于资产类型无法始终从六位代码准确判断,可通过 `instrument_types` 显式传入:
78
+
79
+ ```python
80
+ result = client.get_minute_bars_batch(
81
+ ["sh000001", "sh600519", "sh510300"],
82
+ instrument_types={
83
+ "sh000001": "index",
84
+ "sh600519": "stock",
85
+ "sh510300": "etf",
86
+ },
87
+ )
88
+ ```
89
+
90
+ ## 字段单位
91
+
92
+ - 价格:元;
93
+ - `volume_lots`:手;
94
+ - `amount_cny`:元;
95
+ - `change_percent`:百分数,`-1.67` 表示 `-1.67%`;
96
+ - 时间:带 `Asia/Shanghai` 时区的 `datetime`;
97
+ - 空值:`None`,不会强制转换为 `0`。
98
+
99
+ ## 边界
100
+
101
+ 当前第一版支持沪深市场的 `sh`、`sz` symbol。北交所尚未经过接口验证,会明确拒绝而不是错误映射到沪深市场。
102
+
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "market-quote"
7
+ version = "0.1.0"
8
+ description = "A lightweight Python SDK for China A-share real-time quotes and minute bars"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ {name = "Kwai"},
15
+ ]
16
+ keywords = ["china-stock", "a-share", "market-data", "quote", "etf"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Office/Business :: Financial :: Investment",
26
+ "Typing :: Typed",
27
+ ]
28
+ dependencies = [
29
+ "requests>=2.28,<3",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ tdx = ["pytdx>=1.72"]
34
+ dev = ["pytest>=8,<9"]
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ addopts = "-q"
42
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,18 @@
1
+ from .client import MarketQuoteClient
2
+ from .exceptions import MarketQuoteError, ProviderUnavailableError, SymbolError
3
+ from .models import BatchResult, MinuteBar, OrderLevel, Quote
4
+ from .symbols import normalize_symbol, to_symbol
5
+
6
+ __all__ = [
7
+ "BatchResult",
8
+ "MarketQuoteClient",
9
+ "MarketQuoteError",
10
+ "MinuteBar",
11
+ "OrderLevel",
12
+ "ProviderUnavailableError",
13
+ "Quote",
14
+ "SymbolError",
15
+ "normalize_symbol",
16
+ "to_symbol",
17
+ ]
18
+
@@ -0,0 +1,136 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+
5
+ from .exceptions import MarketQuoteError, ProviderUnavailableError
6
+ from .models import BatchResult, MinuteBar, Quote
7
+ from .providers.tdx import TdxProvider
8
+ from .providers.tencent import TencentProvider
9
+ from .symbols import infer_instrument_type, normalize_symbol
10
+
11
+
12
+ class MarketQuoteClient:
13
+ def __init__(
14
+ self,
15
+ realtime_provider: str = "tencent",
16
+ minute_provider: str = "tencent",
17
+ timeout: float = 8.0,
18
+ concurrency: int = 8,
19
+ max_rps: float = 20.0,
20
+ batch_size: int = 200,
21
+ use_env_proxy: bool = False,
22
+ tdx_hosts: Sequence[tuple[str, int]] | None = None,
23
+ ):
24
+ if realtime_provider not in {"tencent", "tdx"}:
25
+ raise ValueError("realtime_provider must be 'tencent' or 'tdx'")
26
+ if minute_provider not in {"tencent", "tdx", "auto"}:
27
+ raise ValueError("minute_provider must be 'tencent', 'tdx', or 'auto'")
28
+ self.realtime_provider_name = realtime_provider
29
+ self.minute_provider_name = minute_provider
30
+ self.tencent = TencentProvider(
31
+ timeout=timeout,
32
+ concurrency=concurrency,
33
+ max_rps=max_rps,
34
+ batch_size=batch_size,
35
+ use_env_proxy=use_env_proxy,
36
+ )
37
+ self._tdx_hosts = tdx_hosts
38
+ self._tdx_concurrency = concurrency
39
+ self._tdx: TdxProvider | None = None
40
+
41
+ @property
42
+ def tdx(self) -> TdxProvider:
43
+ if self._tdx is None:
44
+ self._tdx = TdxProvider(self._tdx_hosts, concurrency=self._tdx_concurrency)
45
+ return self._tdx
46
+
47
+ def get_quotes(
48
+ self,
49
+ symbols: Sequence[str],
50
+ instrument_types: dict[str, str] | None = None,
51
+ ) -> BatchResult[Quote]:
52
+ provider = self.tencent if self.realtime_provider_name == "tencent" else self.tdx
53
+ return provider.get_quotes(symbols, instrument_types)
54
+
55
+ def get_quote(self, symbol: str, instrument_type: str | None = None) -> Quote:
56
+ value = normalize_symbol(symbol)
57
+ types = {value: instrument_type} if instrument_type else None
58
+ result = self.get_quotes([value], types)
59
+ if value in result.items:
60
+ return result.items[value]
61
+ reason = result.failed.get(value) or "provider returned no data"
62
+ raise MarketQuoteError(f"quote unavailable for {value}: {reason}")
63
+
64
+ def get_minute_bars(
65
+ self,
66
+ symbol: str,
67
+ count: int = 240,
68
+ instrument_type: str | None = None,
69
+ ) -> list[MinuteBar]:
70
+ value = normalize_symbol(symbol)
71
+ types = {value: instrument_type} if instrument_type else None
72
+ result = self.get_minute_bars_batch([value], count, types)
73
+ if value in result.items:
74
+ return result.items[value]
75
+ reason = result.failed.get(value) or "provider returned no data"
76
+ raise MarketQuoteError(f"minute bars unavailable for {value}: {reason}")
77
+
78
+ def get_minute_bars_batch(
79
+ self,
80
+ symbols: Sequence[str],
81
+ count: int = 240,
82
+ instrument_types: dict[str, str] | None = None,
83
+ ) -> BatchResult[list[MinuteBar]]:
84
+ normalized = list(dict.fromkeys(normalize_symbol(symbol) for symbol in symbols))
85
+ types = {normalize_symbol(key): value for key, value in (instrument_types or {}).items()}
86
+ if self.minute_provider_name == "tencent":
87
+ return self.tencent.get_minute_bars_batch(normalized, count, types)
88
+ if self.minute_provider_name == "tdx":
89
+ return self.tdx.get_minute_bars_batch(normalized, count, types)
90
+
91
+ index_symbols = [
92
+ symbol for symbol in normalized
93
+ if types.get(symbol) == "index" or (symbol not in types and infer_instrument_type(symbol) == "index")
94
+ ]
95
+ other_symbols = [symbol for symbol in normalized if symbol not in set(index_symbols)]
96
+ result: BatchResult[list[MinuteBar]] = BatchResult()
97
+ if other_symbols:
98
+ self._merge(result, self.tencent.get_minute_bars_batch(other_symbols, count, types))
99
+ if index_symbols:
100
+ try:
101
+ tdx_result = self.tdx.get_minute_bars_batch(index_symbols, count, types)
102
+ except ProviderUnavailableError:
103
+ tdx_result = BatchResult(failed={symbol: "TDX unavailable" for symbol in index_symbols})
104
+ retry = list(dict.fromkeys(tdx_result.empty + list(tdx_result.failed)))
105
+ for symbol in retry:
106
+ tdx_result.failed.pop(symbol, None)
107
+ self._merge(result, tdx_result)
108
+ if retry:
109
+ self._merge(result, self.tencent.get_minute_bars_batch(retry, count, types))
110
+ return result
111
+
112
+ @staticmethod
113
+ def _merge(target: BatchResult, source: BatchResult) -> None:
114
+ target.items.update(source.items)
115
+ succeeded = set(source.items)
116
+ if succeeded:
117
+ target.empty = [symbol for symbol in target.empty if symbol not in succeeded]
118
+ for symbol in succeeded:
119
+ target.failed.pop(symbol, None)
120
+ target.empty.extend(
121
+ symbol for symbol in source.empty
122
+ if symbol not in target.items and symbol not in target.empty
123
+ )
124
+ target.failed.update({symbol: error for symbol, error in source.failed.items() if symbol not in target.items})
125
+
126
+ def close(self) -> None:
127
+ self.tencent.close()
128
+ if self._tdx is not None:
129
+ self._tdx.close()
130
+
131
+ def __enter__(self) -> "MarketQuoteClient":
132
+ return self
133
+
134
+ def __exit__(self, *exc: object) -> None:
135
+ self.close()
136
+
@@ -0,0 +1,15 @@
1
+ class MarketQuoteError(RuntimeError):
2
+ """Base error for this package."""
3
+
4
+
5
+ class SymbolError(ValueError, MarketQuoteError):
6
+ """Raised when a symbol is not supported or malformed."""
7
+
8
+
9
+ class ProviderUnavailableError(MarketQuoteError):
10
+ """Raised when a requested provider cannot be used."""
11
+
12
+
13
+ class ProviderRequestError(MarketQuoteError):
14
+ """Raised when all endpoints for a provider fail."""
15
+
@@ -0,0 +1,70 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import datetime
5
+ from typing import Generic, TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class OrderLevel:
12
+ price: float | None
13
+ volume_lots: float | None
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Quote:
18
+ symbol: str
19
+ market: str
20
+ code: str
21
+ instrument_type: str | None
22
+ name: str
23
+ price: float | None
24
+ previous_close: float | None
25
+ open: float | None
26
+ high: float | None
27
+ low: float | None
28
+ volume_lots: float | None
29
+ amount_cny: float | None
30
+ change: float | None
31
+ change_percent: float | None
32
+ observed_at: datetime
33
+ source_time: datetime | None
34
+ source: str
35
+ status: str = ""
36
+ turnover_percent: float | None = None
37
+ amplitude_percent: float | None = None
38
+ volume_ratio: float | None = None
39
+ average_price: float | None = None
40
+ limit_up: float | None = None
41
+ limit_down: float | None = None
42
+ market_cap_100m: float | None = None
43
+ float_cap_100m: float | None = None
44
+ bids: tuple[OrderLevel, ...] = ()
45
+ asks: tuple[OrderLevel, ...] = ()
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class MinuteBar:
50
+ symbol: str
51
+ timestamp: datetime
52
+ open: float | None
53
+ high: float | None
54
+ low: float | None
55
+ close: float | None
56
+ volume_lots: float | None
57
+ amount_cny: float | None
58
+ source: str
59
+
60
+
61
+ @dataclass
62
+ class BatchResult(Generic[T]):
63
+ items: dict[str, T] = field(default_factory=dict)
64
+ empty: list[str] = field(default_factory=list)
65
+ failed: dict[str, str] = field(default_factory=dict)
66
+
67
+ @property
68
+ def ok(self) -> bool:
69
+ return not self.empty and not self.failed
70
+
@@ -0,0 +1,5 @@
1
+ from .tdx import TdxProvider
2
+ from .tencent import TencentProvider
3
+
4
+ __all__ = ["TdxProvider", "TencentProvider"]
5
+
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Protocol, Sequence
4
+
5
+ from ..models import BatchResult, MinuteBar, Quote
6
+
7
+
8
+ class QuoteProvider(Protocol):
9
+ def get_quotes(self, symbols: Sequence[str], instrument_types: dict[str, str] | None = None) -> BatchResult[Quote]: ...
10
+ def close(self) -> None: ...
11
+
12
+
13
+ class MinuteProvider(Protocol):
14
+ def get_minute_bars_batch(
15
+ self,
16
+ symbols: Sequence[str],
17
+ count: int = 240,
18
+ instrument_types: dict[str, str] | None = None,
19
+ ) -> BatchResult[list[MinuteBar]]: ...
20
+ def close(self) -> None: ...
21
+