quantdb-sdk 0.1.0__tar.gz → 0.1.2__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.
Files changed (25) hide show
  1. quantdb_sdk-0.1.2/CHANGELOG.md +34 -0
  2. quantdb_sdk-0.1.2/LICENSE +21 -0
  3. quantdb_sdk-0.1.2/MANIFEST.in +5 -0
  4. {quantdb_sdk-0.1.0/quantdb_sdk.egg-info → quantdb_sdk-0.1.2}/PKG-INFO +5 -1
  5. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/README.md +60 -60
  6. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/pyproject.toml +17 -1
  7. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/client.py +3 -1
  8. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2/quantdb_sdk.egg-info}/PKG-INFO +5 -1
  9. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk.egg-info/SOURCES.txt +7 -1
  10. quantdb_sdk-0.1.2/quantdb_sdk.egg-info/entry_points.txt +2 -0
  11. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk.egg-info/requires.txt +1 -0
  12. quantdb_sdk-0.1.2/tests/test_async_client.py +134 -0
  13. quantdb_sdk-0.1.2/tests/test_client.py +152 -0
  14. quantdb_sdk-0.1.2/tests/test_technical_indicators.py +237 -0
  15. quantdb_sdk-0.1.0/MANIFEST.in +0 -22
  16. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/__init__.py +0 -0
  17. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/__main__.py +0 -0
  18. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/_utils.py +0 -0
  19. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/async_client.py +0 -0
  20. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/errors.py +0 -0
  21. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk/py.typed +0 -0
  22. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk.egg-info/dependency_links.txt +0 -0
  23. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/quantdb_sdk.egg-info/top_level.txt +0 -0
  24. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/requirements.txt +0 -0
  25. {quantdb_sdk-0.1.0 → quantdb_sdk-0.1.2}/setup.cfg +0 -0
@@ -0,0 +1,34 @@
1
+ # Changelog
2
+
3
+ 所有 notable 变更都会记录在此文件。格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
+ 版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
5
+
6
+ ## [0.1.2] - 2026-07-25
7
+
8
+ ### Added
9
+ - **CLI 入口**:`[project.scripts]` 注册 `quantdb` 命令,装包后可直接 `quantdb --help` / `quantdb check <key>`,等价于 `python -m quantdb_sdk`。修复了 0.1.0/0.1.1 README 中 `python -m quantdb`(用连字符)会报 `No module named quantdb` 的问题。
10
+ - `CHANGELOG.md` 与 `LICENSE`(MIT)文本随仓库发布。
11
+ - `pyproject.toml` 新增 `Changelog` 项目 URL。
12
+
13
+ ### Notes
14
+ - 0.1.2 严格向后兼容 0.1.1,仅元数据层面的修补,不改任何运行时行为。
15
+ - 若 0.1.1 已经在生产环境运行,可选升级;不升级也不受影响。
16
+
17
+ ## [0.1.1] - 2026-07-25
18
+
19
+ ### Fixed
20
+ - **关键 packaging bug**:`pyarrow` 未声明在 `pyproject.toml` 的运行时依赖,但 `client.py:482` 与 `async_client.py:413` 调用了 `pd.read_parquet(io.BytesIO(...))`。
21
+ - **影响**:任何 `pip install quantdb-sdk==0.1.0` 的用户,在首次调用 `query_kline` / `query_tick` / `query_financial` 等下载类接口时会抛 `ImportError: Missing optional dependency 'pyarrow'`。只有 `get_usage` / `query_stock_list` 等非 parquet 接口 OOTB 可用。
22
+ - **修复**:在 `dependencies` 加入 `pyarrow>=10.0.0`。
23
+ - **服务端 User-Agent** 同步从 `0.1.0` 升级到 `0.1.1`,便于服务端按版本做调用归因与问题分流。
24
+
25
+ ## [0.1.0] - 2026-07-22
26
+
27
+ ### Added
28
+ - 初版发布。
29
+ - `QuantDBClient` 同步客户端(基于 `requests`)。
30
+ - `AsyncQuantDBClient` 异步客户端(基于 `httpx`)。
31
+ - `DuckDBWarehouse` 本地仓库管理:自动下载 Parquet → 注册 DuckDB 视图 → 跨表 SQL 查询。
32
+ - 异常体系:`QuantDBError` / `AuthError` / `RateLimitError` / `InsufficientTrafficError` / `NotFoundError` / `ServerError` / `ValidationError`。
33
+ - 覆盖接口:流量查询、用户信息、API Key 管理、订阅与订单、股票列表、交易日历、K 线、Tick、财务、按日分片分钟线。
34
+ - `py.typed` 标记(PEP 561),第三方库可获得完整类型信息。
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QuantDB Team
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,5 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
4
+ include pyproject.toml
5
+ recursive-include quantdb_sdk *.py *.typed
@@ -1,12 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantdb-sdk
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: QuantDB 量化数据平台官方 Python SDK
5
5
  Author: QuantDB Team
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://www.quantmindai.cn
8
8
  Project-URL: Documentation, https://www.quantmindai.cn/docs/sdk.html
9
9
  Project-URL: Repository, https://github.com/quantdb/quantdb
10
+ Project-URL: Changelog, https://github.com/quantdb/quantdb/blob/main/CHANGELOG.md
10
11
  Keywords: quant,finance,data,a-share,parquet
11
12
  Classifier: Development Status :: 3 - Alpha
12
13
  Classifier: Intended Audience :: Developers
@@ -21,15 +22,18 @@ Classifier: Programming Language :: Python :: 3.12
21
22
  Classifier: Topic :: Office/Business :: Financial
22
23
  Requires-Python: >=3.8
23
24
  Description-Content-Type: text/markdown
25
+ License-File: LICENSE
24
26
  Requires-Dist: requests>=2.25.0
25
27
  Requires-Dist: pandas>=1.3.0
26
28
  Requires-Dist: httpx>=0.24.0
27
29
  Requires-Dist: duckdb>=0.8.0
30
+ Requires-Dist: pyarrow>=10.0.0
28
31
  Provides-Extra: dev
29
32
  Requires-Dist: pytest>=7.0.0; extra == "dev"
30
33
  Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
31
34
  Requires-Dist: responses>=0.23.0; extra == "dev"
32
35
  Requires-Dist: respx>=0.20.0; extra == "dev"
36
+ Dynamic: license-file
33
37
 
34
38
  # QuantDB Python SDK
35
39
 
@@ -1,60 +1,60 @@
1
- # QuantDB Python SDK
2
-
3
- QuantDB 量化数据平台官方 Python SDK,提供同步与异步两种客户端,封装了全部 API 端点。
4
-
5
- ## 安装
6
-
7
- ```bash
8
- pip install quantdb-sdk
9
- ```
10
-
11
- 开发依赖:
12
-
13
- ```bash
14
- pip install -e ".[dev]"
15
- ```
16
-
17
- ## 快速开始
18
-
19
- ### API Key 鉴权(推荐)
20
-
21
- ```python
22
- from quantdb_sdk import QuantDBClient
23
-
24
- client = QuantDBClient(api_key="qdb_xxx...")
25
-
26
- # 查询用量
27
- usage = client.get_usage()
28
- print(f"已用: {usage['used_gb']:.2f} GB, 剩余: {usage['remaining_gb']:.2f} GB")
29
-
30
- # K 线查询(免费)
31
- df = client.query_kline(
32
- "600519.SH",
33
- adj_type="forward",
34
- start_date="2026-01-01",
35
- end_date="2026-07-22",
36
- )
37
- print(df.head())
38
- ```
39
-
40
- ### 用户名密码鉴权
41
-
42
- ```python
43
- client = QuantDBClient(username="admin", password="admin123")
44
- ```
45
-
46
- ## 核心功能
47
-
48
- - **数据查询**:K 线、Tick 通过下载 Parquet 切片后客户端解析(消耗流量);股票列表、交易日历、元数据走网关 JSON(不计流量)。
49
- - **数据下载**:Parquet 文件下载或直读 DataFrame,计入订阅流量。
50
- - **本地分析**:基于 DuckDB 对本地 Parquet 执行 SQL。
51
- - **账户管理**:查询用户信息、用量、API Key、订阅与订单。
52
- - **异步客户端**:基于 httpx,适用于 asyncio 量化框架。
53
-
54
- ## 流量说明
55
-
56
- 每月前 30 GB 下载流量免费,超出部分按 ¥1/GB 计费;账户余额不足时,下载会被限流,充值后即可恢复。
57
-
58
- ## 文档
59
-
60
- 完整文档请访问:https://www.quantmindai.cn/docs/sdk.html
1
+ # QuantDB Python SDK
2
+
3
+ QuantDB 量化数据平台官方 Python SDK,提供同步与异步两种客户端,封装了全部 API 端点。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pip install quantdb-sdk
9
+ ```
10
+
11
+ 开发依赖:
12
+
13
+ ```bash
14
+ pip install -e ".[dev]"
15
+ ```
16
+
17
+ ## 快速开始
18
+
19
+ ### API Key 鉴权(推荐)
20
+
21
+ ```python
22
+ from quantdb_sdk import QuantDBClient
23
+
24
+ client = QuantDBClient(api_key="qdb_xxx...")
25
+
26
+ # 查询用量
27
+ usage = client.get_usage()
28
+ print(f"已用: {usage['used_gb']:.2f} GB, 剩余: {usage['remaining_gb']:.2f} GB")
29
+
30
+ # K 线查询(免费)
31
+ df = client.query_kline(
32
+ "600519.SH",
33
+ adj_type="forward",
34
+ start_date="2026-01-01",
35
+ end_date="2026-07-22",
36
+ )
37
+ print(df.head())
38
+ ```
39
+
40
+ ### 用户名密码鉴权
41
+
42
+ ```python
43
+ client = QuantDBClient(username="admin", password="admin123")
44
+ ```
45
+
46
+ ## 核心功能
47
+
48
+ - **数据查询**:K 线、Tick 通过下载 Parquet 切片后客户端解析(消耗流量);股票列表、交易日历、元数据走网关 JSON(不计流量)。
49
+ - **数据下载**:Parquet 文件下载或直读 DataFrame,计入订阅流量。
50
+ - **本地分析**:基于 DuckDB 对本地 Parquet 执行 SQL。
51
+ - **账户管理**:查询用户信息、用量、API Key、订阅与订单。
52
+ - **异步客户端**:基于 httpx,适用于 asyncio 量化框架。
53
+
54
+ ## 流量说明
55
+
56
+ 每月前 30 GB 下载流量免费,超出部分按 ¥1/GB 计费;账户余额不足时,下载会被限流,充值后即可恢复。
57
+
58
+ ## 文档
59
+
60
+ 完整文档请访问:https://www.quantmindai.cn/docs/sdk.html
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quantdb-sdk"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "QuantDB 量化数据平台官方 Python SDK"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -31,8 +31,19 @@ dependencies = [
31
31
  "pandas>=1.3.0",
32
32
  "httpx>=0.24.0",
33
33
  "duckdb>=0.8.0",
34
+ # 0.1.1 修复:pyarrow 是 pd.read_parquet 的硬依赖(client.py:482, async_client.py:413),
35
+ # 但 0.1.0 漏声明,导致 pip install 后首次 K线/Tick 查询会抛 ImportError。
36
+ # 锁定到 >=10.0.0 以获得 Python 3.10+ 完整支持(pyarrow 14+ 更好)。
37
+ "pyarrow>=10.0.0",
34
38
  ]
35
39
 
40
+ # 0.1.2 新增:装包后提供 `quantdb` shell 命令,等价于 `python -m quantdb_sdk`。
41
+ # 0.1.0/0.1.1 README 写的是 `python -m quantdb`(用了 PyPI 名带连字符),
42
+ # 但 Python 模块名是下划线,安装后 `python -m quantdb` 会报 No module named quantdb。
43
+ # 加这个 entry point 后两个名字都能用,README 不需要再改。
44
+ [project.scripts]
45
+ quantdb = "quantdb_sdk.__main__:main"
46
+
36
47
  [project.optional-dependencies]
37
48
  dev = [
38
49
  "pytest>=7.0.0",
@@ -45,7 +56,12 @@ dev = [
45
56
  Homepage = "https://www.quantmindai.cn"
46
57
  Documentation = "https://www.quantmindai.cn/docs/sdk.html"
47
58
  Repository = "https://github.com/quantdb/quantdb"
59
+ Changelog = "https://github.com/quantdb/quantdb/blob/main/CHANGELOG.md"
48
60
 
49
61
  [tool.setuptools.packages.find]
50
62
  where = ["."]
51
63
  include = ["quantdb_sdk*"]
64
+
65
+ # 0.1.2 新增:让 wheel 包含 LICENSE 和 CHANGELOG.md
66
+ [tool.setuptools.package-data]
67
+ quantdb_sdk = ["py.typed"]
@@ -51,7 +51,9 @@ class QuantDBClient:
51
51
  raise ValueError("必须提供 api_key 或 username+password")
52
52
 
53
53
  self.session = requests.Session()
54
- self.session.headers.update({"User-Agent": "QuantDB-Python-SDK/0.1.0"})
54
+ # User-Agent 中的版本与 pyproject.toml 同步,用于服务端日志归因
55
+ # 维护提示:每次版本号变化必须同步改这里(init 里的 __version__ 走 metadata 自动同步)
56
+ self.session.headers.update({"User-Agent": "QuantDB-Python-SDK/0.1.2"})
55
57
  if self.headers:
56
58
  self.session.headers.update(self.headers)
57
59
 
@@ -1,12 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantdb-sdk
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: QuantDB 量化数据平台官方 Python SDK
5
5
  Author: QuantDB Team
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://www.quantmindai.cn
8
8
  Project-URL: Documentation, https://www.quantmindai.cn/docs/sdk.html
9
9
  Project-URL: Repository, https://github.com/quantdb/quantdb
10
+ Project-URL: Changelog, https://github.com/quantdb/quantdb/blob/main/CHANGELOG.md
10
11
  Keywords: quant,finance,data,a-share,parquet
11
12
  Classifier: Development Status :: 3 - Alpha
12
13
  Classifier: Intended Audience :: Developers
@@ -21,15 +22,18 @@ Classifier: Programming Language :: Python :: 3.12
21
22
  Classifier: Topic :: Office/Business :: Financial
22
23
  Requires-Python: >=3.8
23
24
  Description-Content-Type: text/markdown
25
+ License-File: LICENSE
24
26
  Requires-Dist: requests>=2.25.0
25
27
  Requires-Dist: pandas>=1.3.0
26
28
  Requires-Dist: httpx>=0.24.0
27
29
  Requires-Dist: duckdb>=0.8.0
30
+ Requires-Dist: pyarrow>=10.0.0
28
31
  Provides-Extra: dev
29
32
  Requires-Dist: pytest>=7.0.0; extra == "dev"
30
33
  Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
31
34
  Requires-Dist: responses>=0.23.0; extra == "dev"
32
35
  Requires-Dist: respx>=0.20.0; extra == "dev"
36
+ Dynamic: license-file
33
37
 
34
38
  # QuantDB Python SDK
35
39
 
@@ -1,3 +1,5 @@
1
+ CHANGELOG.md
2
+ LICENSE
1
3
  MANIFEST.in
2
4
  README.md
3
5
  pyproject.toml
@@ -12,5 +14,9 @@ quantdb_sdk/py.typed
12
14
  quantdb_sdk.egg-info/PKG-INFO
13
15
  quantdb_sdk.egg-info/SOURCES.txt
14
16
  quantdb_sdk.egg-info/dependency_links.txt
17
+ quantdb_sdk.egg-info/entry_points.txt
15
18
  quantdb_sdk.egg-info/requires.txt
16
- quantdb_sdk.egg-info/top_level.txt
19
+ quantdb_sdk.egg-info/top_level.txt
20
+ tests/test_async_client.py
21
+ tests/test_client.py
22
+ tests/test_technical_indicators.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ quantdb = quantdb_sdk.__main__:main
@@ -2,6 +2,7 @@ requests>=2.25.0
2
2
  pandas>=1.3.0
3
3
  httpx>=0.24.0
4
4
  duckdb>=0.8.0
5
+ pyarrow>=10.0.0
5
6
 
6
7
  [dev]
7
8
  pytest>=7.0.0
@@ -0,0 +1,134 @@
1
+ """QuantDB 异步 SDK 单元测试(使用 respx mock HTTP)。"""
2
+
3
+ import io
4
+
5
+ import httpx
6
+ import pandas as pd
7
+ import pytest
8
+ import respx
9
+
10
+ from quantdb_sdk import AsyncQuantDBClient, AuthError, InsufficientTrafficError
11
+
12
+
13
+ API_HOST = "http://localhost:5000"
14
+
15
+
16
+ def _kline_parquet() -> bytes:
17
+ buf = io.BytesIO()
18
+ pd.DataFrame({
19
+ "trade_date": ["2025-01-02", "2025-01-03"],
20
+ "open": [100.0, 101.0],
21
+ "high": [101.5, 102.5],
22
+ "low": [99.5, 100.5],
23
+ "close": [101.0, 102.0],
24
+ }).to_parquet(buf)
25
+ return buf.getvalue()
26
+
27
+
28
+ @pytest.mark.asyncio
29
+ @respx.mock
30
+ async def test_a_query_kline():
31
+ route = respx.get(f"{API_HOST}/api/v1/data/download").mock(
32
+ return_value=httpx.Response(200, content=_kline_parquet())
33
+ )
34
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
35
+ df = await client.a_query_kline("600519.SH")
36
+ assert "trade_date" in df.columns
37
+ assert "open" in df.columns
38
+ assert "close" in df.columns
39
+ assert len(df) == 2
40
+ assert route.called
41
+
42
+
43
+ @pytest.mark.asyncio
44
+ @respx.mock
45
+ async def test_a_auth_error_raises_auth_error():
46
+ respx.get(f"{API_HOST}/api/v1/data/download").mock(
47
+ return_value=httpx.Response(401, json={"detail": "invalid key"})
48
+ )
49
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="bad-key") as client:
50
+ with pytest.raises(AuthError):
51
+ await client.a_query_kline("600519.SH")
52
+
53
+
54
+ @pytest.mark.asyncio
55
+ @respx.mock
56
+ async def test_a_insufficient_traffic_error():
57
+ respx.get(f"{API_HOST}/api/v1/data/download").mock(
58
+ return_value=httpx.Response(402, json={"detail": "no active subscription"})
59
+ )
60
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
61
+ with pytest.raises(InsufficientTrafficError):
62
+ await client.a_load_as_df("1", "daily_forward", symbol="600519.SH")
63
+
64
+
65
+ @pytest.mark.asyncio
66
+ @respx.mock
67
+ async def test_a_get_usage_with_subscription():
68
+ respx.get(f"{API_HOST}/api/v1/auth/usage").mock(
69
+ return_value=httpx.Response(
70
+ 200,
71
+ json={
72
+ "used_traffic": 1073741824,
73
+ "traffic_limit": 53687091200,
74
+ "credit_limit": 0,
75
+ "balance_yuan": 0.0,
76
+ "subscription": {"plan_id": "pro-annual", "status": "active"},
77
+ },
78
+ )
79
+ )
80
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
81
+ usage = await client.a_get_usage()
82
+ assert usage["used_gb"] == 1.0
83
+ assert usage["limit_gb"] == 50.0
84
+ assert usage["subscription"]["status"] == "active"
85
+ assert usage["is_active"] is True
86
+
87
+
88
+ @pytest.mark.asyncio
89
+ @respx.mock
90
+ async def test_a_list_plans():
91
+ respx.get(f"{API_HOST}/api/v1/subscription/plans").mock(
92
+ return_value=httpx.Response(
93
+ 200, json={"plans": [{"id": "pro-annual", "amount_yuan": 999}]}
94
+ )
95
+ )
96
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
97
+ plans = await client.a_list_plans()
98
+ assert len(plans) == 1
99
+ assert plans[0]["id"] == "pro-annual"
100
+
101
+
102
+ @pytest.mark.asyncio
103
+ @respx.mock
104
+ async def test_a_create_order():
105
+ respx.post(f"{API_HOST}/api/v1/subscription/orders").mock(
106
+ return_value=httpx.Response(
107
+ 200, json={"order_id": 2, "pay_url": "https://example.com/pay"}
108
+ )
109
+ )
110
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
111
+ order = await client.a_create_order("pro-annual")
112
+ assert order["order_id"] == 2
113
+
114
+
115
+ @pytest.mark.asyncio
116
+ @respx.mock
117
+ async def test_a_delete_api_key():
118
+ respx.post(f"{API_HOST}/api/v1/auth/api-keys/qdb_abc123/delete").mock(
119
+ return_value=httpx.Response(200, json={"message": "API Key 撤销成功"})
120
+ )
121
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
122
+ result = await client.a_delete_api_key("qdb_abc123")
123
+ assert result["message"] == "API Key 撤销成功"
124
+
125
+
126
+ @pytest.mark.asyncio
127
+ @respx.mock
128
+ async def test_a_get_version():
129
+ respx.get(f"{API_HOST}/api/v1/version").mock(
130
+ return_value=httpx.Response(200, json={"latest_version": "1.0.0", "min_required": "1.0.0"})
131
+ )
132
+ async with AsyncQuantDBClient(api_host=API_HOST, api_key="test-key") as client:
133
+ version = await client.a_get_version()
134
+ assert version["latest_version"] == "1.0.0"
@@ -0,0 +1,152 @@
1
+ """QuantDB 同步 SDK 单元测试(使用 responses mock HTTP)。"""
2
+
3
+ import io
4
+
5
+ import pandas as pd
6
+ import pytest
7
+ import responses
8
+
9
+ from quantdb_sdk import AuthError, InsufficientTrafficError, QuantDBClient
10
+
11
+
12
+ API_HOST = "http://localhost:5000"
13
+
14
+
15
+ def _kline_parquet() -> bytes:
16
+ """构造一份含 trade_date/open/high/low/close 列的 parquet 字节流。"""
17
+ buf = io.BytesIO()
18
+ pd.DataFrame({
19
+ "trade_date": ["2025-01-02", "2025-01-03"],
20
+ "open": [100.0, 101.0],
21
+ "high": [101.5, 102.5],
22
+ "low": [99.5, 100.5],
23
+ "close": [101.0, 102.0],
24
+ }).to_parquet(buf)
25
+ return buf.getvalue()
26
+
27
+
28
+ @responses.activate
29
+ def test_query_kline():
30
+ # query_kline 走 /data/download 下载 parquet 切片后客户端解析(消耗流量)
31
+ responses.get(
32
+ f"{API_HOST}/api/v1/data/download",
33
+ body=_kline_parquet(),
34
+ status=200,
35
+ content_type="application/octet-stream",
36
+ )
37
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
38
+ df = client.query_kline("600519.SH")
39
+ assert "trade_date" in df.columns
40
+ assert "open" in df.columns
41
+ assert "close" in df.columns
42
+ assert len(df) == 2
43
+
44
+
45
+ @responses.activate
46
+ def test_auth_error_raises_auth_error():
47
+ responses.get(
48
+ f"{API_HOST}/api/v1/data/download",
49
+ json={"detail": "invalid key"},
50
+ status=401,
51
+ )
52
+ client = QuantDBClient(api_host=API_HOST, api_key="bad-key")
53
+ with pytest.raises(AuthError):
54
+ client.query_kline("600519.SH")
55
+
56
+
57
+ @responses.activate
58
+ def test_insufficient_traffic_error():
59
+ responses.get(
60
+ f"{API_HOST}/api/v1/data/download",
61
+ json={"detail": "no active subscription"},
62
+ status=402,
63
+ )
64
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
65
+ with pytest.raises(InsufficientTrafficError):
66
+ client.load_as_df("1", "daily_forward", symbol="600519.SH")
67
+
68
+
69
+ @responses.activate
70
+ def test_get_usage_with_subscription():
71
+ responses.get(
72
+ f"{API_HOST}/api/v1/auth/usage",
73
+ json={
74
+ "used_traffic": 1073741824,
75
+ "traffic_limit": 32212254720,
76
+ "credit_limit": 0,
77
+ "balance_yuan": 0.0,
78
+ "subscription": {"plan_id": "pro-monthly", "status": "active"},
79
+ },
80
+ status=200,
81
+ )
82
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
83
+ usage = client.get_usage()
84
+ assert usage["used_gb"] == 1.0
85
+ assert usage["limit_gb"] == 30.0
86
+ assert usage["subscription"]["status"] == "active"
87
+ assert usage["is_active"] is True
88
+
89
+
90
+ @responses.activate
91
+ def test_list_plans():
92
+ responses.get(
93
+ f"{API_HOST}/api/v1/subscription/plans",
94
+ json={"plans": [{"id": "pro-monthly", "amount_yuan": 99}]},
95
+ status=200,
96
+ )
97
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
98
+ plans = client.list_plans()
99
+ assert len(plans) == 1
100
+ assert plans[0]["id"] == "pro-monthly"
101
+
102
+
103
+ @responses.activate
104
+ def test_create_order():
105
+ responses.post(
106
+ f"{API_HOST}/api/v1/subscription/orders",
107
+ json={"order_id": 1, "pay_url": "https://example.com/pay"},
108
+ status=200,
109
+ )
110
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
111
+ order = client.create_order("pro-monthly")
112
+ assert order["order_id"] == 1
113
+
114
+
115
+ @responses.activate
116
+ def test_delete_api_key():
117
+ responses.post(
118
+ f"{API_HOST}/api/v1/auth/api-keys/qdb_abc123/delete",
119
+ json={"message": "API Key 撤销成功"},
120
+ status=200,
121
+ )
122
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
123
+ result = client.delete_api_key("qdb_abc123")
124
+ assert result["message"] == "API Key 撤销成功"
125
+
126
+
127
+ @responses.activate
128
+ def test_get_version():
129
+ responses.get(
130
+ f"{API_HOST}/api/v1/version",
131
+ json={"latest_version": "1.0.0", "min_required": "1.0.0"},
132
+ status=200,
133
+ )
134
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
135
+ version = client.get_version()
136
+ assert version["latest_version"] == "1.0.0"
137
+
138
+
139
+ def test_duckdb_warehouse(tmp_path):
140
+ pytest.importorskip("duckdb")
141
+ # 测试 DuckDBWarehouse 注册本地 parquet 文件与 SQL 查询
142
+ file_path = tmp_path / "test.parquet"
143
+ pd.DataFrame({"code": ["000001.SZ", "600519.SH"], "val": [10, 20]}).to_parquet(file_path)
144
+
145
+ client = QuantDBClient(api_host=API_HOST, api_key="test-key")
146
+ wh = client.get_local_warehouse(save_dir=str(tmp_path))
147
+ wh.register_file("stock_val", str(file_path))
148
+
149
+ df = wh.query("SELECT * FROM stock_val WHERE val > 15")
150
+ assert len(df) == 1
151
+ assert df.iloc[0]["code"] == "600519.SH"
152
+
@@ -0,0 +1,237 @@
1
+ """
2
+ 技术指标计算真值测试。
3
+
4
+ 目的:在改公式前先立基准。对合成 OHLCV 断言 compute_technical_indicators
5
+ 符合「通达信口径」规格(见 .claude/plans/technical-indicator-fix-plan.md)。
6
+
7
+ 当前代码(Phase 1 前)应当失败:
8
+ - macd_hist 缺 ×2(应 = 2*(DIF-DEA),现为 DIF-DEA)
9
+ - rsi 首行被强制设为 100(应为 NaN)
10
+ - rsi 平盘日未设为 50(纯涨=100 已对,但 ag=al=0 时按公式算得 NaN)
11
+ - 列名为 volume_ratio_5/20(应为 vol_to_ma5/20)
12
+ - 滚动前未去重
13
+
14
+ 失败即说明测试有效。Phase 1 修复后此测试全绿。
15
+
16
+ 断言策略:
17
+ - 易手算且口径明确的指标(MA / ma_gap / vol_to_ma / pct_change / return_Nd /
18
+ macd 三者关系)用精确数值匹配。
19
+ - 难手算的递归平滑指标(RSI / KDJ / EMA 系列的绝对值)用「边界与单调性」
20
+ 属性断言,避免把 ewm 递归的手算误差写死进测试。
21
+ """
22
+ import os
23
+ import sys
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ import pytest
28
+
29
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "pipeline", "collectors"))
30
+
31
+ # 09_technical.py 数字开头文件名无法直接 import,用 importlib 动态加载。
32
+ import importlib.util
33
+
34
+
35
+ def _load_technical_module():
36
+ """动态加载 09_technical.py(数字开头文件名无法直接 import)。"""
37
+ here = os.path.dirname(os.path.abspath(__file__))
38
+ # 尝试 09_technical.py 与可能的 technical.py 两种文件名
39
+ for cand in ("09_technical.py", "technical.py"):
40
+ path = os.path.join(here, "..", "pipeline", "collectors", cand)
41
+ if os.path.exists(path):
42
+ spec = importlib.util.spec_from_file_location("quantdb_technical", path)
43
+ mod = importlib.util.module_from_spec(spec)
44
+ spec.loader.exec_module(mod)
45
+ return mod
46
+ raise ImportError("找不到 09_technical.py / technical.py")
47
+
48
+
49
+ _technical = _load_technical_module()
50
+ compute_technical_indicators = _technical.compute_technical_indicators
51
+
52
+
53
+ def _make_df(closes, highs=None, lows=None, opens=None, volumes=None, amounts=None):
54
+ """构造单股日线 DataFrame。缺省按 close 推导 high/low/open,volume/amount 给定常量。"""
55
+ n = len(closes)
56
+ closes = np.asarray(closes, dtype=float)
57
+ if highs is None:
58
+ highs = closes * 1.01
59
+ if lows is None:
60
+ lows = closes * 0.99
61
+ if opens is None:
62
+ opens = closes
63
+ if volumes is None:
64
+ volumes = [10000.0] * n
65
+ if amounts is None:
66
+ amounts = [v * c for v, c in zip(volumes, closes)]
67
+ times = pd.date_range("2024-01-02", periods=n, freq="B")
68
+ return pd.DataFrame({
69
+ "time": times,
70
+ "open": opens,
71
+ "high": highs,
72
+ "low": lows,
73
+ "close": closes,
74
+ "volume": volumes,
75
+ "amount": amounts,
76
+ })
77
+
78
+
79
+ # ============ MA / ma_gap(精确) ============
80
+
81
+ def test_ma5_and_gap_exact():
82
+ closes = [10, 11, 12, 13, 14, 15]
83
+ df = _make_df(closes)
84
+ out = compute_technical_indicators(df)
85
+ # 第 5 行(idx=4,0-based)首次有 5 日 MA:(10+11+12+13+14)/5 = 12.0
86
+ assert out.loc[4, "ma5"] == pytest.approx(12.0)
87
+ # 第 6 行 MA5 = (11+12+13+14+15)/5 = 13.0
88
+ assert out.loc[5, "ma5"] == pytest.approx(13.0)
89
+ # 前 4 行 MA5 为 NaN
90
+ assert out["ma5"].iloc[:4].isna().all()
91
+ # ma_gap_5 = (close - ma5)/ma5 * 100,idx=4: (14-12)/12*100
92
+ assert out.loc[4, "ma_gap_5"] == pytest.approx((14 - 12) / 12 * 100)
93
+
94
+
95
+ # ============ RSI 边界与属性 ============
96
+
97
+ def test_rsi_first_row_is_nan():
98
+ """首行无前收,RSI 应为 NaN(当前代码错误地设为 100)。"""
99
+ df = _make_df([10, 11, 12, 13, 14, 15, 16])
100
+ out = compute_technical_indicators(df)
101
+ assert np.isnan(out.loc[0, "rsi_6"])
102
+ assert np.isnan(out.loc[0, "rsi_14"])
103
+
104
+
105
+ def test_rsi_pure_uptrend_is_100():
106
+ """连续纯涨(每天上涨、无下跌日)-> RSI = 100。"""
107
+ df = _make_df([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
108
+ out = compute_technical_indicators(df)
109
+ # 从第 2 行起 delta>0、loss=0 -> RSI=100
110
+ rsi6 = out["rsi_6"].iloc[1:]
111
+ assert (rsi6 == 100.0).all(), f"纯涨 RSI6 应全为 100,实际: {rsi6.tolist()}"
112
+
113
+
114
+ def test_rsi_flat_is_50():
115
+ """全程平盘(每天与前日相同,无涨无跌)-> RSI = 50(中性)。
116
+
117
+ 通达信口径:gain=loss=0 始终 -> avg_gain=avg_loss=0 -> RSI=50。
118
+ (注意:EMA alpha=1/6 衰减缓慢,"上涨后接若干平盘"会让 avg_gain 暂不为 0、
119
+ avg_loss=0,此时 RSI 仍为 100 而非 50--这不是本测试场景。本测试要求
120
+ 从首日起就全程平盘。)
121
+ """
122
+ df = _make_df([10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
123
+ out = compute_technical_indicators(df)
124
+ # 行 0 为 NaN;其余全程平盘 -> 50
125
+ assert np.isnan(out.loc[0, "rsi_6"])
126
+ rsi6 = out["rsi_6"].iloc[1:]
127
+ assert (rsi6 == 50.0).all(), f"全程平盘 RSI6 应为 50,实际: {rsi6.tolist()}"
128
+
129
+
130
+ def test_rsi_range_and_pure_downtrend_zero():
131
+ """纯跌 -> RSI 趋近 0;全程 RSI ∈ [0,100] 或 NaN。"""
132
+ df = _make_df([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10])
133
+ out = compute_technical_indicators(df)
134
+ rsi6 = out["rsi_6"].iloc[1:]
135
+ # 纯跌 avg_gain=0 -> 公式 RSI = 0(100-100/(1+0));但代码未对 avg_gain==0 设 0
136
+ # 规格:纯跌应得 0。这里仅断言非 NaN 的 RSI 落在 [0,100]
137
+ finite = rsi6.dropna()
138
+ if len(finite):
139
+ assert (finite >= 0).all() and (finite <= 100).all()
140
+
141
+
142
+ # ============ KDJ 属性 ============
143
+
144
+ def test_kdj_warmup_nan_then_finite():
145
+ """前 8 行 RSV 为 NaN(9 日窗口)-> KDJ 也 NaN;之后有限。"""
146
+ df = _make_df(list(range(10, 40))) # 30 根
147
+ out = compute_technical_indicators(df)
148
+ assert out["kdj_k"].iloc[:8].isna().all()
149
+ assert out["kdj_k"].iloc[8:].notna().all()
150
+
151
+
152
+ def test_kdj_j_formula():
153
+ """J = 3K - 2D,逐行成立。"""
154
+ df = _make_df([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])
155
+ out = compute_technical_indicators(df)
156
+ k, d, j = out["kdj_k"], out["kdj_d"], out["kdj_j"]
157
+ mask = k.notna()
158
+ assert np.allclose(j[mask], 3 * k[mask] - 2 * d[mask])
159
+
160
+
161
+ # ============ MACD(关系精确,口径断言) ============
162
+
163
+ def test_macd_hist_is_twice_diff():
164
+ """通达信口径:hist = 2*(DIF - DEA)。当前代码缺 ×2 -> 此测试失败。"""
165
+ df = _make_df([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
166
+ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
167
+ 29, 28, 27, 26, 25, 24, 23, 22, 21, 20])
168
+ out = compute_technical_indicators(df)
169
+ dif, dea, hist = out["macd_dif"], out["macd_dea"], out["macd_hist"]
170
+ mask = dif.notna() & dea.notna()
171
+ # 通达信口径:hist = 2*(dif - dea)
172
+ expected = 2 * (dif[mask] - dea[mask])
173
+ assert np.allclose(hist[mask], expected, rtol=1e-9), \
174
+ "macd_hist 应 = 2*(DIF-DEA)(通达信口径)"
175
+
176
+
177
+ def test_macd_dif_dea_ema_relationship():
178
+ """DEA = EMA9(DIF),与 ewm 关系一致(adjust=False)。"""
179
+ df = _make_df([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
180
+ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30])
181
+ out = compute_technical_indicators(df)
182
+ dif = out["macd_dif"]
183
+ expected_dea = dif.ewm(span=9, adjust=False).mean()
184
+ assert np.allclose(out["macd_dea"], expected_dea, rtol=1e-9)
185
+
186
+
187
+ # ============ 成交量比(精确 + 改名) ============
188
+
189
+ def test_vol_to_ma5_renamed_and_exact():
190
+ """列名应为 vol_to_ma5(非 volume_ratio_5),且 = volume / 5日均量。"""
191
+ volumes = [100, 200, 300, 400, 500, 600]
192
+ df = _make_df([10, 11, 12, 13, 14, 15], volumes=volumes)
193
+ out = compute_technical_indicators(df)
194
+ assert "vol_to_ma5" in out.columns, "应重命名为 vol_to_ma5"
195
+ assert "volume_ratio_5" not in out.columns, "旧名 volume_ratio_5 应已移除"
196
+ # idx=4: vol=500, ma5=(100+200+300+400+500)/5=300 -> 500/300
197
+ assert out.loc[4, "vol_to_ma5"] == pytest.approx(500 / 300)
198
+ # idx=5: vol=600, ma5=(200+300+400+500+600)/5=400 -> 600/400
199
+ assert out.loc[5, "vol_to_ma5"] == pytest.approx(600 / 400)
200
+
201
+
202
+ # ============ 收益率(方向精确:未来 vs 过去) ============
203
+
204
+ def test_return_1d_is_forward():
205
+ """return_1d = 未来 1 日收益(shift(-1)),与 pct_change(过去) 方向相反。"""
206
+ closes = [10, 11, 12, 13, 14]
207
+ df = _make_df(closes)
208
+ out = compute_technical_indicators(df)
209
+ # idx=0: return_1d = (11/10 - 1)*100 = 10
210
+ assert out.loc[0, "return_1d"] == pytest.approx((11 / 10 - 1) * 100)
211
+ # pct_change idx=0 = NaN(无前日)
212
+ assert np.isnan(out.loc[0, "pct_change"])
213
+ # pct_change idx=1 = (11/10-1)*100
214
+ assert out.loc[1, "pct_change"] == pytest.approx((11 / 10 - 1) * 100)
215
+ # 最后一行 return_1d = NaN(无未来)
216
+ assert np.isnan(out.loc[len(closes) - 1, "return_1d"])
217
+
218
+
219
+ # ============ 去重(Phase 1 新增) ============
220
+
221
+ def test_dedup_before_rolling():
222
+ """重复 time 行应在滚动前删除,否则 rolling 会重复计数。"""
223
+ df = _make_df([10, 11, 12, 13, 14])
224
+ # 复制第 3 行追加
225
+ dup = pd.concat([df, df.iloc[[2]]], ignore_index=True)
226
+ out = compute_technical_indicators(dup)
227
+ # 去重后应只剩 5 行
228
+ assert len(out) == 5, f"重复 time 行未被去重,行数={len(out)}"
229
+
230
+
231
+ # ============ 排序稳定 ============
232
+
233
+ def test_sort_by_time():
234
+ df = _make_df([10, 11, 12, 13, 14])
235
+ shuffled = df.iloc[[3, 1, 4, 0, 2]].reset_index(drop=True)
236
+ out = compute_technical_indicators(shuffled)
237
+ assert out["close"].tolist() == [10, 11, 12, 13, 14]
@@ -1,22 +0,0 @@
1
- # MANIFEST.in - 确保发布到 PyPI 时包含必要的非 Python 文件
2
-
3
- # 包含 README 和许可证
4
- include README.md
5
- include LICENSE
6
-
7
- # 包含依赖文件
8
- include requirements.txt
9
-
10
- # 包含类型标记文件
11
- include quantdb_sdk/py.typed
12
-
13
- # 排除不需要的文件
14
- exclude .gitignore
15
- exclude Makefile
16
- recursive-exclude tests *
17
- recursive-exclude .github *
18
- recursive-exclude docs *
19
- recursive-exclude website *
20
- recursive-exclude frontend *
21
- recursive-exclude backend *
22
- recursive-exclude pipeline *
File without changes