jq-docs-mcp 2.0.0__py3-none-any.whl

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,3 @@
1
+ """JoinQuant (聚宽) public API documentation MCP server."""
2
+
3
+ __version__ = "2.0.0"
@@ -0,0 +1,6 @@
1
+ """Run jq-docs-mcp with `python -m jq_docs_mcp`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
jq_docs_mcp/cli.py ADDED
@@ -0,0 +1,39 @@
1
+ """Command-line entry point for jq-docs-mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+
7
+ from . import __version__
8
+ from .server import create_server
9
+
10
+
11
+ def build_parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(
13
+ prog="jq-docs-mcp",
14
+ description="JoinQuant public API documentation MCP server",
15
+ )
16
+ parser.add_argument(
17
+ "--transport",
18
+ choices=("stdio", "http"),
19
+ default="stdio",
20
+ help="MCP transport: stdio (default) or Streamable HTTP",
21
+ )
22
+ parser.add_argument("--host", default="127.0.0.1", help="HTTP bind host (default: 127.0.0.1)")
23
+ parser.add_argument("--port", type=int, default=8000, help="HTTP bind port (default: 8000)")
24
+ parser.add_argument("--db", default=None, help="optional path to jq_knowledge.db")
25
+ parser.add_argument("--version", action="version", version=f"jq-docs-mcp {__version__}")
26
+ return parser
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> None:
30
+ args = build_parser().parse_args(argv)
31
+ mcp = create_server(args.db)
32
+ if args.transport == "http":
33
+ mcp.run(transport="streamable-http", host=args.host, port=args.port)
34
+ else:
35
+ mcp.run(transport="stdio")
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
Binary file
jq_docs_mcp/db.py ADDED
@@ -0,0 +1,174 @@
1
+ """SQLite schema, connection management, and CJK bigram helpers for jq-docs-mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import sqlite3
8
+ from pathlib import Path
9
+
10
+ SCHEMA_VERSION = "2.0"
11
+
12
+ DEFAULT_DB_PATH = Path(__file__).resolve().parent / "data" / "jq_knowledge.db"
13
+
14
+ _CJK_RE = re.compile(r"[\u4e00-\u9fff]+")
15
+
16
+ SCHEMA_SQL = """
17
+ PRAGMA foreign_keys = ON;
18
+
19
+ CREATE TABLE IF NOT EXISTS meta (
20
+ key TEXT PRIMARY KEY,
21
+ value TEXT NOT NULL
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS api_docs (
25
+ id TEXT PRIMARY KEY,
26
+ function_name TEXT NOT NULL,
27
+ namespace TEXT NOT NULL DEFAULT 'core',
28
+ chinese_name TEXT,
29
+ section TEXT NOT NULL,
30
+ page_name TEXT NOT NULL,
31
+ call_signature TEXT,
32
+ description TEXT,
33
+ return_type TEXT,
34
+ example_code TEXT,
35
+ source_url TEXT NOT NULL,
36
+ anchor TEXT,
37
+ scraped_at TEXT NOT NULL
38
+ );
39
+
40
+ CREATE TABLE IF NOT EXISTS api_params (
41
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
42
+ doc_id TEXT NOT NULL REFERENCES api_docs(id) ON DELETE CASCADE,
43
+ param_name TEXT NOT NULL,
44
+ param_type TEXT,
45
+ default_value TEXT,
46
+ is_required INTEGER NOT NULL DEFAULT 1,
47
+ description TEXT,
48
+ position INTEGER NOT NULL DEFAULT 0,
49
+ UNIQUE(doc_id, param_name)
50
+ );
51
+
52
+ CREATE TABLE IF NOT EXISTS api_warnings (
53
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
54
+ doc_id TEXT NOT NULL REFERENCES api_docs(id) ON DELETE CASCADE,
55
+ category TEXT NOT NULL DEFAULT 'general',
56
+ content TEXT NOT NULL,
57
+ UNIQUE(doc_id, content)
58
+ );
59
+
60
+ CREATE TABLE IF NOT EXISTS api_objects (
61
+ object_name TEXT PRIMARY KEY,
62
+ chinese_name TEXT,
63
+ section TEXT NOT NULL,
64
+ description TEXT,
65
+ source_url TEXT NOT NULL,
66
+ anchor TEXT
67
+ );
68
+
69
+ CREATE TABLE IF NOT EXISTS api_object_attrs (
70
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
71
+ object_name TEXT NOT NULL REFERENCES api_objects(object_name) ON DELETE CASCADE,
72
+ attr_name TEXT NOT NULL,
73
+ attr_type TEXT,
74
+ description TEXT,
75
+ UNIQUE(object_name, attr_name)
76
+ );
77
+
78
+ CREATE TABLE IF NOT EXISTS doc_tables (
79
+ table_name TEXT PRIMARY KEY,
80
+ module TEXT NOT NULL DEFAULT 'general',
81
+ chinese_name TEXT,
82
+ section TEXT NOT NULL,
83
+ description TEXT,
84
+ query_example TEXT,
85
+ source_url TEXT NOT NULL,
86
+ anchor TEXT,
87
+ column_count INTEGER NOT NULL DEFAULT 0
88
+ );
89
+
90
+ CREATE TABLE IF NOT EXISTS table_columns (
91
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
92
+ table_name TEXT NOT NULL REFERENCES doc_tables(table_name) ON DELETE CASCADE,
93
+ column_name TEXT NOT NULL,
94
+ column_type TEXT,
95
+ meaning TEXT,
96
+ description TEXT,
97
+ UNIQUE(table_name, column_name)
98
+ );
99
+
100
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_entities USING fts5(
101
+ entity_id UNINDEXED,
102
+ entity_type UNINDEXED,
103
+ title,
104
+ keywords,
105
+ body,
106
+ cjk_bigrams,
107
+ tokenize = "unicode61 tokenchars '_.'"
108
+ );
109
+
110
+ CREATE INDEX IF NOT EXISTS idx_api_docs_name ON api_docs(function_name);
111
+ CREATE INDEX IF NOT EXISTS idx_api_docs_section ON api_docs(section);
112
+ CREATE INDEX IF NOT EXISTS idx_api_docs_namespace ON api_docs(namespace);
113
+ CREATE INDEX IF NOT EXISTS idx_api_params_doc ON api_params(doc_id);
114
+ CREATE INDEX IF NOT EXISTS idx_api_warnings_doc ON api_warnings(doc_id);
115
+ CREATE INDEX IF NOT EXISTS idx_api_warnings_cat ON api_warnings(category);
116
+ CREATE INDEX IF NOT EXISTS idx_api_object_attrs_obj ON api_object_attrs(object_name);
117
+ CREATE INDEX IF NOT EXISTS idx_doc_tables_module ON doc_tables(module);
118
+ CREATE INDEX IF NOT EXISTS idx_table_columns_table ON table_columns(table_name);
119
+ CREATE INDEX IF NOT EXISTS idx_table_columns_name ON table_columns(column_name);
120
+ """
121
+
122
+
123
+ def extract_cjk_bigrams(text: str) -> str:
124
+ """Expand CJK runs into space-separated character bigrams (and singletons for 1-char runs)."""
125
+ if not text:
126
+ return ""
127
+ tokens: list[str] = []
128
+ for run in _CJK_RE.findall(text):
129
+ n = len(run)
130
+ if n == 1:
131
+ tokens.append(run)
132
+ else:
133
+ for i in range(n - 1):
134
+ tokens.append(run[i : i + 2])
135
+ return " ".join(tokens)
136
+
137
+
138
+ def resolve_db_path(db_path: str | Path | None = None) -> Path:
139
+ """Resolve DB path from explicit arg, JQ_DB_PATH env var, or bundled data DB."""
140
+ if db_path is not None:
141
+ return Path(db_path)
142
+ env_path = os.environ.get("JQ_DB_PATH")
143
+ if env_path:
144
+ return Path(env_path)
145
+ return DEFAULT_DB_PATH
146
+
147
+
148
+ def init_db(db_path_or_conn: str | Path | sqlite3.Connection) -> sqlite3.Connection:
149
+ """Initialize a writable SQLite database with the v2 schema."""
150
+ if isinstance(db_path_or_conn, sqlite3.Connection):
151
+ conn = db_path_or_conn
152
+ else:
153
+ path = Path(db_path_or_conn)
154
+ path.parent.mkdir(parents=True, exist_ok=True)
155
+ conn = sqlite3.connect(str(path))
156
+ conn.row_factory = sqlite3.Row
157
+ conn.executescript(SCHEMA_SQL)
158
+ return conn
159
+
160
+
161
+ def open_readonly_db(db_path: str | Path | None = None) -> sqlite3.Connection:
162
+ """Open the SQLite knowledge base in read-only mode."""
163
+ path = resolve_db_path(db_path)
164
+ if not path.exists():
165
+ raise FileNotFoundError(f"JoinQuant knowledge DB not found at {path}")
166
+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False)
167
+ conn.row_factory = sqlite3.Row
168
+ return conn
169
+
170
+
171
+ def get_meta(conn: sqlite3.Connection) -> dict[str, str]:
172
+ """Return all key-value metadata rows from the meta table."""
173
+ rows = conn.execute("SELECT key, value FROM meta ORDER BY key").fetchall()
174
+ return {r["key"]: r["value"] for r in rows}
@@ -0,0 +1,249 @@
1
+ """Progressive, token-conscious Markdown formatters for jq-docs-mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable
7
+
8
+ from .search import SearchHit
9
+
10
+
11
+ def _get(obj, key: str, default=""):
12
+ if obj is None:
13
+ return default
14
+ if isinstance(obj, dict):
15
+ value = obj.get(key, default)
16
+ else:
17
+ try:
18
+ value = obj[key]
19
+ except (IndexError, KeyError, TypeError):
20
+ value = getattr(obj, key, default)
21
+ return default if value is None else value
22
+
23
+
24
+ def _one_line(text: object, max_len: int = 110) -> str:
25
+ value = re.sub(r"\s+", " ", str(text or "")).strip()
26
+ return value if len(value) <= max_len else value[: max_len - 1].rstrip() + "…"
27
+
28
+
29
+ def _md_cell(text: object, max_len: int = 90) -> str:
30
+ return _one_line(text, max_len).replace("|", "\\|") or "-"
31
+
32
+
33
+ def _source_url(obj) -> str:
34
+ url = str(_get(obj, "source_url", "") or "")
35
+ anchor = str(_get(obj, "anchor", "") or "")
36
+ if anchor:
37
+ anchor_part = anchor[1:] if anchor.startswith("#") else anchor
38
+ if not url.endswith(f"#{anchor_part}"):
39
+ url = f"{url}#{anchor_part}"
40
+ return url
41
+
42
+
43
+ def _next_step(hit: SearchHit) -> str:
44
+ if hit.entity_type == "function" and hit.doc_id:
45
+ display = hit.title or hit.doc_id
46
+ return f"`get_function_doc(\"{display}\")`"
47
+ if hit.entity_type == "object" and hit.object_name:
48
+ return f"`get_function_doc(\"{hit.object_name}\")`"
49
+ if hit.entity_type == "table" and hit.table_name:
50
+ return f"`get_table_schema(\"{hit.table_name}\")`"
51
+ if hit.entity_type == "column" and hit.table_name:
52
+ if hit.column_name:
53
+ return f"`get_table_schema(\"{hit.table_name}\", column_filter=\"{hit.column_name}\")`"
54
+ return f"`get_table_schema(\"{hit.table_name}\")`"
55
+ return "`search_jq_docs(...)`"
56
+
57
+
58
+ def format_search_results(query: str, hits: list[SearchHit], exact_doc_markdown: str | None = None) -> str:
59
+ """Format compact top-K search cards with progressive next-step hints."""
60
+ parts: list[str] = []
61
+ if exact_doc_markdown:
62
+ parts.extend([exact_doc_markdown.rstrip(), "", "---", ""])
63
+ if not hits:
64
+ parts.append(f"## Search Results: `{query}`\n\nNo matching JoinQuant documentation entity found.")
65
+ parts.append("Try `list_catalog(\"tables\")`, or search a shorter function/table/field keyword.")
66
+ return "\n".join(parts)
67
+
68
+ parts.append(f"## Search Results: `{query}` — top {len(hits)}")
69
+ for index, hit in enumerate(hits, start=1):
70
+ badge = f" ⚠️ 含未来函数/避坑提示({hit.warning_count})" if hit.warning_count > 0 else ""
71
+ type_label = hit.entity_type
72
+ subtitle = _one_line(hit.subtitle or "-", 80)
73
+ parts.append(f"{index}. **{hit.title}** `{type_label}` — {subtitle}{badge}")
74
+ signature = _one_line(hit.signature or type_label, 68)
75
+ parts.append(f" `{signature}` · `{hit.entity_id}` → {_next_step(hit)}")
76
+ parts.append("Resources: `jq://function/{name}` · `jq://table/{table_name}`")
77
+ return "\n".join(parts)
78
+
79
+
80
+ def format_function_doc(doc, params: Iterable, warnings: Iterable, include_examples: bool = False, compact: bool = False) -> str:
81
+ """Format one function document, omitting example code unless requested."""
82
+ namespace = _get(doc, "namespace", "core")
83
+ name = _get(doc, "function_name") if namespace in {"core", "jqdata"} else (_get(doc, "id") or _get(doc, "function_name"))
84
+ lines = [f"# Function: `{name}`"]
85
+ if _get(doc, "chinese_name"):
86
+ lines.append(f"**Chinese Name:** {_get(doc, 'chinese_name')}")
87
+ if _get(doc, "namespace") and _get(doc, "namespace") != "core":
88
+ lines.append(f"**Namespace:** `{_get(doc, 'namespace')}`")
89
+ lines.append(f"**Section:** {_get(doc, 'section', '-')}")
90
+ if _get(doc, "call_signature"):
91
+ lines.extend(["", "## Signature", f"`{_get(doc, 'call_signature')}`"])
92
+ if _get(doc, "description"):
93
+ description = str(_get(doc, "description")).strip()
94
+ if compact:
95
+ description = _one_line(description, 260)
96
+ lines.extend(["", "## Description", description])
97
+
98
+ params = list(params or [])
99
+ lines.extend(["", "## Parameters"])
100
+ if params:
101
+ lines.append("| Name | Type | Required | Default | Description |")
102
+ lines.append("|---|---|---|---|---|")
103
+ for param in params:
104
+ required = "Yes" if int(_get(param, "is_required", 1) or 0) else "No"
105
+ lines.append(
106
+ "| {name} | {ptype} | {req} | {default} | {desc} |".format(
107
+ name=_md_cell(_get(param, "param_name"), 40),
108
+ ptype=_md_cell(_get(param, "param_type"), 35),
109
+ req=required,
110
+ default=_md_cell(_get(param, "default_value"), 120),
111
+ desc=_md_cell(_get(param, "description"), 70 if compact else 120),
112
+ )
113
+ )
114
+ else:
115
+ lines.append("_No documented parameters._")
116
+
117
+ warnings = list(warnings or [])
118
+ unique_warnings = []
119
+ seen_warnings = set()
120
+ for warning in warnings:
121
+ content = str(_get(warning, "content", "")).strip()
122
+ marker = re.sub(r"\s+", "", content)[:180]
123
+ if content and marker not in seen_warnings:
124
+ seen_warnings.add(marker)
125
+ unique_warnings.append(warning)
126
+ omitted_warning_count = max(0, len(unique_warnings) - 5) if compact else 0
127
+ if compact:
128
+ unique_warnings = unique_warnings[:5]
129
+ lines.extend(["", "## ⚠️ 注意 / 避坑"])
130
+ if unique_warnings:
131
+ for warning in unique_warnings:
132
+ category = _get(warning, "category", "general") or "general"
133
+ content = str(_get(warning, "content", "")).strip()
134
+ if compact:
135
+ content = _one_line(content, 180)
136
+ if content:
137
+ lines.append(f"- **{category}** — {content}")
138
+ if omitted_warning_count:
139
+ lines.append(f"- … 另有 {omitted_warning_count} 条提示;用 `get_function_doc` 展开查看。")
140
+ else:
141
+ lines.append("_暂无特殊风险提示;仍请以聚宽官方文档和回测结果为准。_")
142
+
143
+ if _get(doc, "return_type"):
144
+ lines.extend(["", "## Return Type", f"`{_get(doc, 'return_type')}`"])
145
+ if include_examples and _get(doc, "example_code"):
146
+ lines.extend(["", "## Example", "```python", str(_get(doc, "example_code")).strip(), "```"])
147
+ source = _source_url(doc)
148
+ if source:
149
+ lines.extend(["", f"**Source:** {source}"])
150
+ return "\n".join(lines)
151
+
152
+
153
+ def format_object_doc(obj, attrs: Iterable) -> str:
154
+ """Format one strategy object document (Context, Portfolio, Position, Order, ...)."""
155
+ name = _get(obj, "object_name")
156
+ lines = [f"# Object: `{name}`"]
157
+ if _get(obj, "chinese_name"):
158
+ lines.append(f"**Chinese Name:** {_get(obj, 'chinese_name')}")
159
+ lines.append(f"**Section:** {_get(obj, 'section', '-')}")
160
+ if _get(obj, "description"):
161
+ lines.extend(["", "## Description", str(_get(obj, "description")).strip()])
162
+ attrs = list(attrs or [])
163
+ lines.extend(["", "## Attributes"])
164
+ if attrs:
165
+ lines.append("| Name | Type | Description |")
166
+ lines.append("|---|---|---|")
167
+ for attr in attrs:
168
+ lines.append(
169
+ f"| {_md_cell(_get(attr, 'attr_name'), 45)} | {_md_cell(_get(attr, 'attr_type'), 40)} | "
170
+ f"{_md_cell(_get(attr, 'description'), 130)} |"
171
+ )
172
+ else:
173
+ lines.append("_No documented attributes._")
174
+ source = _source_url(obj)
175
+ if source:
176
+ lines.extend(["", f"**Source:** {source}"])
177
+ return "\n".join(lines)
178
+
179
+
180
+ def format_table_schema(table, columns: Iterable, total_count: int, limit: int, offset: int, column_filter: str | None = None) -> str:
181
+ """Format a compact, paginated table schema."""
182
+ columns = list(columns or [])
183
+ name = _get(table, "table_name")
184
+ title = f"# Table: `{name}`"
185
+ chinese_name = str(_get(table, "chinese_name", "") or "")
186
+ if chinese_name and chinese_name != str(name) and not chinese_name.startswith(f"{name} "):
187
+ title += f" — {chinese_name}"
188
+ lines = [title]
189
+ lines.append(f"**Module:** `{_get(table, 'module', 'general')}`")
190
+ if _get(table, "description"):
191
+ lines.append(f"**Description:** {_one_line(_get(table, 'description'), 180)}")
192
+ shown_from = offset + 1 if columns else 0
193
+ shown_to = offset + len(columns)
194
+ filter_note = f" matching `{column_filter}`" if column_filter else ""
195
+ lines.append(f"**Columns:** showing {shown_from}–{shown_to} of {total_count}{filter_note}")
196
+ if _get(table, "query_example"):
197
+ lines.extend(["", "## Query Example", "```python", str(_get(table, "query_example")).strip(), "```"])
198
+
199
+ lines.extend(["", "| Column | Type | Meaning | Description |", "|---|---|---|---|"])
200
+ if columns:
201
+ for column in columns:
202
+ lines.append(
203
+ f"| {_md_cell(_get(column, 'column_name'), 48)} | {_md_cell(_get(column, 'column_type'), 28)} | "
204
+ f"{_md_cell(_get(column, 'meaning'), 65)} | {_md_cell(_get(column, 'description'), 90)} |"
205
+ )
206
+ else:
207
+ lines.append("| - | - | - | No columns in this page/filter |")
208
+
209
+ if total_count > offset + len(columns):
210
+ next_offset = offset + len(columns)
211
+ args = [f'"{name}"']
212
+ if column_filter:
213
+ args.append(f'column_filter="{column_filter}"')
214
+ args.extend([f"limit={limit}", f"offset={next_offset}"])
215
+ lines.extend(["", f"> More columns available: `get_table_schema({', '.join(args)})`"])
216
+ elif column_filter:
217
+ lines.extend(["", f"> Filtered view. Clear `column_filter` or use `jq://table/{name}` for the full schema."])
218
+ source = _source_url(table)
219
+ if source:
220
+ lines.extend(["", f"**Source:** {source}"])
221
+ return "\n".join(lines)
222
+
223
+
224
+ def format_catalog(scope: str, items: Iterable[dict], total_count: int) -> str:
225
+ """Format a compact catalog of sections, tables, or strategy objects."""
226
+ items = list(items or [])
227
+ lines = [f"# Catalog: `{scope}` — showing {len(items)} of {total_count}"]
228
+ if not items:
229
+ lines.append("_No entries found._")
230
+ return "\n".join(lines)
231
+ for item in items:
232
+ if scope == "sections":
233
+ lines.append(
234
+ f"- **{item.get('section', '-')}** — {item.get('function_count', 0)} functions, "
235
+ f"{item.get('object_count', 0)} objects, {item.get('table_count', 0)} tables"
236
+ )
237
+ elif scope == "tables":
238
+ label = item.get("table_name", "-")
239
+ cn = f" — {item.get('chinese_name')}" if item.get("chinese_name") else ""
240
+ lines.append(
241
+ f"- `{label}`{cn} · module `{item.get('module', 'general')}` · {item.get('column_count', 0)} columns"
242
+ )
243
+ else:
244
+ label = item.get("object_name", "-")
245
+ cn = f" — {item.get('chinese_name')}" if item.get("chinese_name") else ""
246
+ lines.append(f"- `{label}`{cn} · {item.get('attr_count', 0)} attributes")
247
+ if total_count > len(items):
248
+ lines.append(f"\nUse `list_catalog(\"{scope}\", limit={min(total_count, len(items) * 2)})` for more.")
249
+ return "\n".join(lines)
@@ -0,0 +1,176 @@
1
+ """JoinQuant / A-share bilingual quant glossary and table aliases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ ALIASES: list[dict] = [
8
+ {"surface": ["市盈率", "pe", "pe_ttm", "pettm", "市盈"],
9
+ "expands": ["valuation", "pe_ratio", "市盈率"], "hints": []},
10
+ {"surface": ["市净率", "pb", "pb_mrq"],
11
+ "expands": ["valuation", "pb_ratio", "市净率"], "hints": []},
12
+ {"surface": ["市销率", "ps", "ps_ttm"],
13
+ "expands": ["valuation", "ps_ratio", "市销率"], "hints": []},
14
+ {"surface": ["市现率", "pcf"],
15
+ "expands": ["valuation", "pcf_ratio", "市现率"], "hints": []},
16
+ {"surface": ["换手率", "turnover"],
17
+ "expands": ["valuation", "turnover_ratio", "换手率"], "hints": []},
18
+ {"surface": ["净利润", "net profit"],
19
+ "expands": ["income", "net_profit", "净利润"], "hints": []},
20
+ {"surface": ["roe", "净资产收益率"],
21
+ "expands": ["indicator", "roe", "净资产收益率"], "hints": []},
22
+ {"surface": ["roa", "总资产收益率", "资产回报率"],
23
+ "expands": ["indicator", "roa", "总资产收益率"], "hints": []},
24
+ {"surface": ["eps", "每股收益"],
25
+ "expands": ["income", "eps", "basic_eps", "每股收益"], "hints": []},
26
+ {"surface": ["bps", "每股净资产"],
27
+ "expands": ["bps", "每股净资产"], "hints": []},
28
+ {"surface": ["总市值", "市值"],
29
+ "expands": ["valuation", "market_cap", "总市值"], "hints": []},
30
+ {"surface": ["流通市值"],
31
+ "expands": ["valuation", "circulating_market_cap", "流通市值"], "hints": []},
32
+ {"surface": ["股息率", "分红率"],
33
+ "expands": ["dividend_yield", "股息率"], "hints": []},
34
+ {"surface": ["销售毛利率", "毛利率"],
35
+ "expands": ["indicator", "gross_profit_margin", "销售毛利率"], "hints": []},
36
+ {"surface": ["日期", "解禁日期", "解除限售日期"],
37
+ "expands": ["date", "day", "日期"], "hints": []},
38
+ {"surface": ["比例", "比率"],
39
+ "expands": ["ratio", "比例", "比率"], "hints": []},
40
+ {"surface": ["复权", "前复权", "后复权", "不复权"],
41
+ "expands": ["fq", "pre", "post", "复权", "动态复权"], "hints": []},
42
+ {"surface": ["停牌", "停复牌"],
43
+ "expands": ["paused", "停牌"], "hints": []},
44
+ {"surface": ["涨跌停", "涨停", "跌停", "涨跌停价"],
45
+ "expands": ["high_limit", "low_limit", "涨跌停"], "hints": []},
46
+ {"surface": ["龙虎榜", "买卖席位"],
47
+ "expands": ["billboard", "龙虎榜"], "hints": ["function:get_billboard_list"]},
48
+ {"surface": ["融资融券", "两融", "融券", "融资余额"],
49
+ "expands": ["mtss", "margin", "融资融券"], "hints": ["function:get_mtss"]},
50
+ {"surface": ["北向资金持股", "北向持股", "陆股通持股", "沪深港通持股"],
51
+ "expands": ["STK_HK_HOLD_INFO", "hk_hold", "持股比例", "持股数量"],
52
+ "hints": ["table:STK_HK_HOLD_INFO"]},
53
+ {"surface": ["北向", "北向资金", "陆股通", "沪股通", "深股通", "市场通"],
54
+ "expands": ["STK_ML_QUOTA", "STK_HK_HOLD_INFO", "hk_hold", "市场通", "持股比例"],
55
+ "hints": ["table:STK_ML_QUOTA", "table:STK_HK_HOLD_INFO"]},
56
+ {"surface": ["分红", "除权", "除息", "送股", "送转", "转增", "派息"],
57
+ "expands": ["xr_xd", "STK_XR_XD", "分红", "除权", "送转"], "hints": ["table:STK_XR_XD"]},
58
+ {"surface": ["限售", "解禁", "限售股", "大小非"],
59
+ "expands": ["limited_shares", "unlimit", "STK_LIMITED_SHARES_UNLIMIT", "解禁"],
60
+ "hints": ["table:STK_LIMITED_SHARES_UNLIMIT"]},
61
+ {"surface": ["十大股东", "前十大股东", "股东持股"],
62
+ "expands": ["STK_SHAREHOLDER_TOP10", "shareholder", "十大股东"],
63
+ "hints": ["table:STK_SHAREHOLDER_TOP10"]},
64
+ {"surface": ["股东户数", "户数"],
65
+ "expands": ["STK_HOLDER_NUM", "holder_num", "股东户数"],
66
+ "hints": ["table:STK_HOLDER_NUM"]},
67
+ {"surface": ["股权质押", "质押"],
68
+ "expands": ["STK_SHARES_PLEDGE", "pledge", "质押"],
69
+ "hints": ["table:STK_SHARES_PLEDGE"]},
70
+ {"surface": ["定时", "定时任务", "定时运行", "每天", "收盘前"],
71
+ "expands": ["run_daily", "run_weekly", "run_monthly", "定时"],
72
+ "hints": ["function:run_daily"]},
73
+ {"surface": ["滑点", "slippage"],
74
+ "expands": ["slippage", "set_slippage", "滑点"], "hints": ["function:set_slippage"]},
75
+ {"surface": ["手续费", "佣金", "印花税", "交易成本"],
76
+ "expands": ["order_cost", "set_order_cost", "commission", "佣金", "印花税"],
77
+ "hints": ["function:set_order_cost"]},
78
+ {"surface": ["未来函数", "未来数据", "lookahead"],
79
+ "expands": ["avoid_future_data", "get_price", "get_bars", "未来函数", "future"],
80
+ "hints": ["function:get_price", "function:get_bars"]},
81
+ {"surface": ["资产负债表"],
82
+ "expands": ["balance", "STK_BALANCE_SHEET", "资产负债表"], "hints": ["table:balance"]},
83
+ {"surface": ["利润表", "损益表"],
84
+ "expands": ["income", "STK_INCOME_STATEMENT", "利润表"], "hints": ["table:income"]},
85
+ {"surface": ["现金流量表", "现金流"],
86
+ "expands": ["cash_flow", "STK_CASHFLOW_STATEMENT", "现金流量表"], "hints": ["table:cash_flow"]},
87
+ {"surface": ["财务指标", "指标表"],
88
+ "expands": ["indicator", "财务指标"], "hints": ["table:indicator"]},
89
+ {"surface": ["估值表", "财务估值表", "估值"],
90
+ "expands": ["valuation", "估值"], "hints": ["table:valuation"]},
91
+ {"surface": ["指数成分股", "指数权重", "成分股权重"],
92
+ "expands": ["index_weights", "index_stocks", "权重"], "hints": []},
93
+ {"surface": ["行业成分股", "行业分类", "行业"],
94
+ "expands": ["industry_stocks", "industry", "行业"], "hints": []},
95
+ {"surface": ["概念股", "概念", "概念板块"],
96
+ "expands": ["concept_stocks", "concept", "概念"], "hints": []},
97
+ {"surface": ["交易日", "交易日历", "trading day"],
98
+ "expands": ["trade_days", "交易日"], "hints": []},
99
+ {"surface": ["基准", "benchmark"],
100
+ "expands": ["set_benchmark", "benchmark", "基准"], "hints": []},
101
+ {"surface": ["全部证券", "所有股票", "证券列表", "标的信息"],
102
+ "expands": ["all_securities", "securities", "证券"], "hints": []},
103
+ {"surface": ["动态复权", "真实价格", "use_real_price"],
104
+ "expands": ["use_real_price", "set_option", "动态复权", "真实价格"], "hints": []},
105
+ {"surface": ["资金流", "主力资金", "超大单", "净流入"],
106
+ "expands": ["money_flow", "资金流", "净流入"], "hints": []},
107
+ {"surface": ["均线", "ma", "移动平均"],
108
+ "expands": ["ma", "均线"], "hints": []},
109
+ {"surface": ["分钟线", "分钟k线", "五分钟", "1分钟", "5分钟", "15分钟", "30分钟", "60分钟"],
110
+ "expands": ["minute", "frequency", "分钟"], "hints": []},
111
+ {"surface": ["快照", "snapshot", "当前数据"],
112
+ "expands": ["current_data", "快照"], "hints": []},
113
+ {"surface": ["调仓", "下单", "买入", "卖出", "目标市值", "目标仓位"],
114
+ "expands": ["order", "order_target", "order_target_value", "目标价值", "调仓"], "hints": []},
115
+ {"surface": ["历史行情", "历史数据", "k线"],
116
+ "expands": ["history", "get_price", "get_bars", "历史数据"], "hints": []},
117
+ {"surface": ["证券信息", "上市日期", "退市日期"],
118
+ "expands": ["all_securities", "start_date", "end_date", "上市"], "hints": []},
119
+ ]
120
+
121
+ TABLE_ALIASES = {
122
+ "balance_sheet": "balance",
123
+ "balancesheet": "balance",
124
+ "balance_sheet_table": "balance",
125
+ "资产负债表": "balance",
126
+ "income_statement": "income",
127
+ "profit_statement": "income",
128
+ "profit_loss": "income",
129
+ "利润表": "income",
130
+ "损益表": "income",
131
+ "cashflow": "cash_flow",
132
+ "cash_flow_statement": "cash_flow",
133
+ "cashflow_statement": "cash_flow",
134
+ "现金流量表": "cash_flow",
135
+ "valuation_table": "valuation",
136
+ "估值表": "valuation",
137
+ "财务估值表": "valuation",
138
+ "financial_indicator": "indicator",
139
+ "financial_indicators": "indicator",
140
+ "finance_indicator": "indicator",
141
+ "财务指标": "indicator",
142
+ "财务指标表": "indicator",
143
+ }
144
+
145
+ _ASCII_SURFACE_RE = re.compile(r"^[a-z0-9_.-]+$", re.IGNORECASE)
146
+
147
+
148
+ def normalize_table_alias(name: str) -> str:
149
+ return re.sub(r"[\s-]+", "_", (name or "").strip().lower())
150
+
151
+
152
+ def resolve_table_alias(name: str) -> str:
153
+ """Return the canonical table name for a common alias, otherwise the stripped input."""
154
+ raw = (name or "").strip()
155
+ return TABLE_ALIASES.get(normalize_table_alias(raw), TABLE_ALIASES.get(raw, raw))
156
+
157
+
158
+ def _surface_matches(surface: str, query_lower: str) -> bool:
159
+ s = surface.lower()
160
+ if not s:
161
+ return False
162
+ if _ASCII_SURFACE_RE.match(s):
163
+ return re.search(rf"(?<![a-z0-9_]){re.escape(s)}(?![a-z0-9_])", query_lower) is not None
164
+ return s in query_lower
165
+
166
+
167
+ def expand(query: str) -> tuple[list[str], list[str], list[str]]:
168
+ """Return (matched_surfaces, expansion_terms, hint_entity_ids)."""
169
+ q = (query or "").lower()
170
+ surfaces, terms, hints = [], [], []
171
+ for entry in ALIASES:
172
+ if any(_surface_matches(s, q) for s in entry["surface"]):
173
+ surfaces.append("/".join(entry["surface"][:3]))
174
+ terms.extend(entry["expands"])
175
+ hints.extend(entry["hints"])
176
+ return surfaces, list(dict.fromkeys(terms)), list(dict.fromkeys(hints))
@@ -0,0 +1,5 @@
1
+ """JoinQuant public-documentation scraper, parser, DB builder, and auditor."""
2
+
3
+ from .pages import PAGE_SPECS, PAGES, PageSpec, get_page_spec
4
+
5
+ __all__ = ["PAGE_SPECS", "PAGES", "PageSpec", "get_page_spec"]