stock-analysis-plugin 0.2.10 → 0.2.12
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.
- package/README.md +237 -381
- package/docs/mcp.md +60 -0
- package/hermes/__init__.py +35 -0
- package/hermes/plugin.yaml +131 -0
- package/hermes/schemas.py +6 -0
- package/hermes/tools.py +630 -0
- package/mcp_host/__init__.py +1 -0
- package/mcp_host/__main__.py +3 -0
- package/mcp_host/server.py +222 -0
- package/package.json +17 -10
- package/pi/index.ts +53 -2887
- package/scripts/cli-json.mjs +23 -0
- package/scripts/exec-process.mjs +89 -0
- package/scripts/setup-python.mjs +37 -4
- package/scripts/tool-calls.mjs +489 -0
- package/skills/event-driven/SKILL.md +2 -2
- package/skills/growth-quality/SKILL.md +1 -1
- package/skills/stock-analysis/SKILL.md +12 -7
- package/skills/stock-analysis/references/stateless-analysis.md +9 -1
- package/tools/_cache.py +13 -0
- package/tools/_subproc.py +46 -0
- package/tools/alert_rules.py +65 -16
- package/tools/backtest.py +3 -3
- package/tools/capabilities.py +32 -9
- package/tools/cli_budgets.json +2 -0
- package/tools/diagnostics.py +3 -4
- package/tools/gather.py +2 -6
- package/tools/import_parser.py +3 -4
- package/tools/lixinger.py +119 -27
- package/tools/market_regime.py +5 -2
- package/tools/market_review.py +5 -6
- package/tools/name_resolver.py +82 -21
- package/tools/report_renderer.py +3 -3
- package/tools/requirements.txt +6 -5
- package/tools/risk_screening.py +3 -2
- package/tools/screener.py +6 -4
- package/tools/search_intel.py +81 -12
- package/tools/sec_edgar.py +266 -0
- package/tools/sec_holders.py +6 -0
- package/tools/signal_tracker.py +11 -10
- package/tools/stateless_analysis.py +115 -0
- package/tools/stock_data.py +707 -222
- package/tools/tiaa_disclosures.py +267 -0
- package/tools/tool_schemas.json +2704 -0
- package/tools/trading_calendar.py +65 -30
- package/tools/value_data.py +366 -134
- package/tools/watchlist.py +43 -5
package/tools/lixinger.py
CHANGED
|
@@ -1,42 +1,71 @@
|
|
|
1
|
-
"""Optional Lixinger HK non-financial
|
|
1
|
+
"""Optional Lixinger open-API provider: CN/HK non-financial companies and CN indexes.
|
|
2
|
+
|
|
3
|
+
Callers pass a provider market ("cn"/"hk") and the provider's stock code; symbol parsing stays with them."""
|
|
2
4
|
|
|
3
5
|
import os
|
|
4
|
-
from datetime import
|
|
6
|
+
from datetime import timedelta
|
|
5
7
|
|
|
8
|
+
import pandas as pd
|
|
6
9
|
import requests
|
|
7
10
|
from _cache import DAY, cached
|
|
11
|
+
from trading_calendar import market_now
|
|
12
|
+
|
|
13
|
+
API = "https://open.lixinger.com/api"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def post(path, payload):
|
|
17
|
+
response = requests.post(f"{API}/{path}", json={"token": os.environ["LIXINGER_TOKEN"], **payload}, timeout=20)
|
|
18
|
+
response.raise_for_status()
|
|
19
|
+
body = response.json()
|
|
20
|
+
if body.get("code") != 1 or not isinstance(body.get("data"), list):
|
|
21
|
+
raise ValueError(f"Lixinger {path} unavailable; check token permissions/company type")
|
|
22
|
+
return body["data"]
|
|
8
23
|
|
|
9
24
|
|
|
10
|
-
def
|
|
11
|
-
|
|
12
|
-
end = date.today()
|
|
25
|
+
def company_data(market, code, dataset, metrics):
|
|
26
|
+
end = market_now("HK" if market == "hk" else "CN").date()
|
|
13
27
|
try:
|
|
14
28
|
start = end.replace(year=end.year - 10)
|
|
15
29
|
except ValueError:
|
|
16
30
|
start = end.replace(year=end.year - 10, day=28) + timedelta(days=1)
|
|
17
31
|
|
|
18
32
|
def fetch():
|
|
19
|
-
|
|
20
|
-
f"
|
|
21
|
-
|
|
22
|
-
"token": os.environ["LIXINGER_TOKEN"],
|
|
23
|
-
"stockCodes": [code],
|
|
24
|
-
"startDate": start.isoformat(),
|
|
25
|
-
"endDate": end.isoformat(),
|
|
26
|
-
"metricsList": metrics,
|
|
27
|
-
},
|
|
28
|
-
timeout=20,
|
|
33
|
+
data = post(
|
|
34
|
+
f"{market}/company/{dataset}/non_financial",
|
|
35
|
+
{"stockCodes": [code], "startDate": start.isoformat(), "endDate": end.isoformat(), "metricsList": metrics},
|
|
29
36
|
)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
37
|
+
if not data:
|
|
38
|
+
raise ValueError(f"Lixinger {market} non-financial data unavailable; check token permissions/company type")
|
|
39
|
+
return data
|
|
40
|
+
|
|
41
|
+
return cached(f"lixinger-{market}:{dataset}:{code}:{end}:{','.join(metrics)}", DAY, fetch)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def valuation_history(market, code, years):
|
|
45
|
+
"""Daily PE-TTM/PB within the last `years`; raises when either metric is entirely missing."""
|
|
46
|
+
cutoff = (market_now("HK" if market == "hk" else "CN").date() - pd.DateOffset(years=years)).date().isoformat()
|
|
47
|
+
history = []
|
|
48
|
+
for row in company_data(market, code, "fundamental", ["pe_ttm", "pb"]):
|
|
49
|
+
stamp = str(row.get("date") or "")[:10]
|
|
50
|
+
if stamp >= cutoff:
|
|
51
|
+
history.append({"date": stamp, **{field: number(row.get(field)) for field in ("pe_ttm", "pb")}})
|
|
52
|
+
history.sort(key=lambda r: r["date"])
|
|
53
|
+
if not history or not all(any(r[field] is not None for r in history) for field in ("pe_ttm", "pb")):
|
|
54
|
+
raise ValueError("Lixinger valuation history incomplete")
|
|
55
|
+
return history
|
|
35
56
|
|
|
36
|
-
return cached(f"lixinger-hk:{dataset}:{code}:{end}:{','.join(metrics)}", DAY, fetch)
|
|
37
57
|
|
|
58
|
+
def number(value):
|
|
59
|
+
value = pd.to_numeric(value, errors="coerce")
|
|
60
|
+
return float(value) if pd.notna(value) and abs(value) != float("inf") else None
|
|
38
61
|
|
|
39
|
-
|
|
62
|
+
|
|
63
|
+
def metric(row, field):
|
|
64
|
+
table, name = field.split(".")
|
|
65
|
+
return row.get("q", {}).get(table, {}).get(name, {}).get("t")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def financials_hk(code, periods, annual):
|
|
40
69
|
fields = {
|
|
41
70
|
"roe": "m.roe",
|
|
42
71
|
"gross_margin": "ps.gp_m",
|
|
@@ -45,12 +74,12 @@ def financials_hk(symbol, periods, annual):
|
|
|
45
74
|
"net_income": "ps.np",
|
|
46
75
|
"operating_cash_flow": "cfs.ncffoa",
|
|
47
76
|
}
|
|
48
|
-
data =
|
|
77
|
+
data = company_data("hk", code, "fs", [f"q.{field}.t" for field in fields.values()])
|
|
49
78
|
history = []
|
|
50
79
|
for row in sorted(data, key=lambda r: r.get("date", ""), reverse=True):
|
|
51
80
|
if annual and row.get("reportType") != "annual_report":
|
|
52
81
|
continue
|
|
53
|
-
if not row.get("date") or row.get("stockCode",
|
|
82
|
+
if not row.get("date") or row.get("stockCode", code) != code:
|
|
54
83
|
continue
|
|
55
84
|
entry = {
|
|
56
85
|
"report_date": row["date"][:10],
|
|
@@ -60,8 +89,7 @@ def financials_hk(symbol, periods, annual):
|
|
|
60
89
|
"source": "lixinger",
|
|
61
90
|
}
|
|
62
91
|
for key, field in fields.items():
|
|
63
|
-
|
|
64
|
-
value = row.get("q", {}).get(table, {}).get(metric, {}).get("t")
|
|
92
|
+
value = metric(row, field)
|
|
65
93
|
entry[key] = (
|
|
66
94
|
value * 100 if value is not None and key in ("roe", "gross_margin", "net_profit_margin") else value
|
|
67
95
|
)
|
|
@@ -74,7 +102,6 @@ def financials_hk(symbol, periods, annual):
|
|
|
74
102
|
result = {
|
|
75
103
|
**dict.fromkeys(("name", "market_cap", "pe", "forward_pe", "pb", "debt_to_equity", "dividend_yield")),
|
|
76
104
|
"snapshot_available": False,
|
|
77
|
-
"symbol": symbol,
|
|
78
105
|
"source": "lixinger",
|
|
79
106
|
"report_date": latest["report_date"],
|
|
80
107
|
"currency": latest["currency"],
|
|
@@ -98,3 +125,68 @@ def financials_hk(symbol, periods, annual):
|
|
|
98
125
|
if len(history) < periods:
|
|
99
126
|
result["warnings"] = ["Requested financial history incomplete; only actual available periods returned"]
|
|
100
127
|
return result
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# Field codes from https://www.lixinger.com/api/open-api/html-doc/{cn,hk}/company/fs/non_financial.
|
|
131
|
+
# HK has no operating income, capex or D&A; the caller fills those from Yahoo.
|
|
132
|
+
DCF_FIELDS = {
|
|
133
|
+
"cn": {
|
|
134
|
+
"revenue": ("ps.toi",),
|
|
135
|
+
"operating_income": ("ps.op",),
|
|
136
|
+
"pretax_income": ("ps.tp",),
|
|
137
|
+
"income_tax": ("ps.ite",),
|
|
138
|
+
"operating_cash_flow": ("cfs.ncffoa",),
|
|
139
|
+
"capital_expenditure": ("cfs.cpfpfiaolta",),
|
|
140
|
+
"depreciation_amortization": ("cfs.daa",),
|
|
141
|
+
"cash": ("cfs.bocaceatpe",),
|
|
142
|
+
"total_debt": ("bs.stl", "bs.stbp", "bs.ncldwioy", "bs.ltl", "bs.bp"),
|
|
143
|
+
"lease_liabilities": ("bs.ll",),
|
|
144
|
+
"minority_interest": ("bs.etmsh",),
|
|
145
|
+
"shares_outstanding": ("bs.tsc",),
|
|
146
|
+
},
|
|
147
|
+
"hk": {
|
|
148
|
+
"revenue": ("ps.toi",),
|
|
149
|
+
"pretax_income": ("ps.tp",),
|
|
150
|
+
"income_tax": ("ps.ite",),
|
|
151
|
+
"operating_cash_flow": ("cfs.ncffoa",),
|
|
152
|
+
"cash": ("cfs.bocaceatpe",),
|
|
153
|
+
"total_debt": (
|
|
154
|
+
"bs.stl",
|
|
155
|
+
"bs.stpl",
|
|
156
|
+
"bs.stbp",
|
|
157
|
+
"bs.stlcofcb",
|
|
158
|
+
"bs.stsn",
|
|
159
|
+
"bs.ltl",
|
|
160
|
+
"bs.ltpl",
|
|
161
|
+
"bs.sn",
|
|
162
|
+
"bs.bp",
|
|
163
|
+
"bs.ltlcofcb",
|
|
164
|
+
),
|
|
165
|
+
"lease_liabilities": ("bs.stll", "bs.ltll"),
|
|
166
|
+
"minority_interest": ("bs.etmsh",),
|
|
167
|
+
"shares_outstanding": ("bs.tsc",),
|
|
168
|
+
},
|
|
169
|
+
}
|
|
170
|
+
DCF_WARNINGS = {
|
|
171
|
+
"cn": "Lixinger CN statements; operating_income is 营业利润 (includes investment and fair-value gains, not EBIT); "
|
|
172
|
+
"total_debt sums borrowings, bonds and current non-current liabilities "
|
|
173
|
+
"(the latter may include current lease liabilities); long-term leases are in lease_liabilities.",
|
|
174
|
+
"hk": "Lixinger HK statements; total_debt sums borrowings, bonds, notes and convertibles and excludes leases.",
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def dcf_inputs(market, code, periods):
|
|
179
|
+
fields = DCF_FIELDS[market]
|
|
180
|
+
metrics = [f"q.{field}.t" for names in fields.values() for field in names]
|
|
181
|
+
rows = []
|
|
182
|
+
for row in sorted(company_data(market, code, "fs", metrics), key=lambda r: r.get("date", ""), reverse=True):
|
|
183
|
+
if row.get("reportType") != "annual_report" or not row.get("date") or row.get("stockCode", code) != code:
|
|
184
|
+
continue
|
|
185
|
+
entry = {"period_end": row["date"][:10], "currency": row.get("currency")}
|
|
186
|
+
for key, names in fields.items():
|
|
187
|
+
values = [value for name in names if (value := metric(row, name)) is not None]
|
|
188
|
+
entry[key] = sum(values) if values else None
|
|
189
|
+
rows.append(entry)
|
|
190
|
+
if not rows:
|
|
191
|
+
raise ValueError(f"Lixinger returned no annual {market} statements")
|
|
192
|
+
return {"source": "lixinger", "periods": rows[:periods], "warnings": [DCF_WARNINGS[market]]}
|
package/tools/market_regime.py
CHANGED
|
@@ -18,6 +18,9 @@ INDEX_MAP = {
|
|
|
18
18
|
"A": ("000001", "上证综指"),
|
|
19
19
|
"HK": ("^HSI", "恒生指数"),
|
|
20
20
|
"US": ("^GSPC", "标普500"),
|
|
21
|
+
"JP": ("^N225", "日经225"),
|
|
22
|
+
"KR": ("^KS11", "韩国KOSPI"),
|
|
23
|
+
"TW": ("^TWII", "台湾加权指数"),
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
REGIME_CN = {
|
|
@@ -166,7 +169,7 @@ def _detect_sector_heat(market: str) -> bool:
|
|
|
166
169
|
def detect_regime(market: str = "A") -> dict:
|
|
167
170
|
market = market.upper()
|
|
168
171
|
if market not in INDEX_MAP:
|
|
169
|
-
return {"error": f"Unsupported market: {market}. Use
|
|
172
|
+
return {"error": f"Unsupported market: {market}. Use {'/'.join(INDEX_MAP)}"}
|
|
170
173
|
|
|
171
174
|
code, name = INDEX_MAP[market]
|
|
172
175
|
klines = _get_index_kline(market)
|
|
@@ -229,7 +232,7 @@ def main():
|
|
|
229
232
|
sub = parser.add_subparsers(dest="command")
|
|
230
233
|
|
|
231
234
|
p_detect = sub.add_parser("detect")
|
|
232
|
-
p_detect.add_argument("market", nargs="?", default="A", choices=
|
|
235
|
+
p_detect.add_argument("market", nargs="?", default="A", choices=list(INDEX_MAP))
|
|
233
236
|
|
|
234
237
|
args = parser.parse_args()
|
|
235
238
|
if not args.command:
|
package/tools/market_review.py
CHANGED
|
@@ -18,9 +18,10 @@ from pathlib import Path
|
|
|
18
18
|
|
|
19
19
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
20
20
|
|
|
21
|
-
from _subproc import command_timeout, utf8_stdio
|
|
21
|
+
from _subproc import command_timeout, error_message, utf8_stdio
|
|
22
22
|
from _subproc import run_tool as _run_tool
|
|
23
23
|
from signal_tracker import _append_record, _load_records, _store_lock
|
|
24
|
+
from trading_calendar import market_now
|
|
24
25
|
|
|
25
26
|
|
|
26
27
|
def _index_change(row):
|
|
@@ -81,8 +82,6 @@ def _signal_to_stance(signal: str) -> str | None:
|
|
|
81
82
|
|
|
82
83
|
def review_market(market: str = "A", *, run=None) -> dict:
|
|
83
84
|
"""Gather market data and compute review for a single market."""
|
|
84
|
-
from datetime import datetime
|
|
85
|
-
|
|
86
85
|
tasks = {}
|
|
87
86
|
|
|
88
87
|
if market == "A":
|
|
@@ -135,7 +134,7 @@ def review_market(market: str = "A", *, run=None) -> dict:
|
|
|
135
134
|
|
|
136
135
|
output = {
|
|
137
136
|
"market": market,
|
|
138
|
-
"date":
|
|
137
|
+
"date": market_now("CN" if market == "A" else market).strftime("%Y-%m-%d"),
|
|
139
138
|
"indices": results.get("indices"),
|
|
140
139
|
"stats": results.get("stats"),
|
|
141
140
|
"sectors": results.get("sectors"),
|
|
@@ -169,7 +168,7 @@ def save_review(report: dict, store: Path | None = None) -> dict:
|
|
|
169
168
|
with _store_lock(store):
|
|
170
169
|
_append_record(store, report)
|
|
171
170
|
except (OSError, ValueError) as e:
|
|
172
|
-
return {"error":
|
|
171
|
+
return {"error": error_message(e)}
|
|
173
172
|
return {"saved": True, "date": report.get("review_date") or report.get("date")}
|
|
174
173
|
|
|
175
174
|
|
|
@@ -181,7 +180,7 @@ def cmd_history(args) -> dict:
|
|
|
181
180
|
records = _load_records(store)
|
|
182
181
|
except (OSError, UnicodeDecodeError) as e:
|
|
183
182
|
# store is a directory / not UTF-8 — same clean-error contract as save_review
|
|
184
|
-
return {"error":
|
|
183
|
+
return {"error": error_message(e)}
|
|
185
184
|
limit = max(args.limit, 0)
|
|
186
185
|
recent = records[-limit:][::-1] if limit else []
|
|
187
186
|
return {"count": len(recent), "records": recent}
|
package/tools/name_resolver.py
CHANGED
|
@@ -2,41 +2,78 @@
|
|
|
2
2
|
"""Resolve Chinese stock names / pinyin / fuzzy input to stock codes."""
|
|
3
3
|
|
|
4
4
|
import argparse
|
|
5
|
+
import functools
|
|
5
6
|
import json
|
|
7
|
+
import re
|
|
6
8
|
import sys
|
|
7
9
|
from difflib import SequenceMatcher
|
|
8
10
|
from pathlib import Path
|
|
9
11
|
|
|
10
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
13
|
|
|
12
|
-
from
|
|
13
|
-
from
|
|
14
|
-
|
|
15
|
-
_STOCK_MAP_CACHE = None
|
|
14
|
+
from _cache import DAY, cached # noqa: E402
|
|
15
|
+
from _subproc import error_message, utf8_stdio # noqa: E402
|
|
16
|
+
from stock_data import _akshare_retry, normalize_us_symbol # noqa: E402
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
def _load_stock_map() -> list[dict]:
|
|
19
|
-
|
|
20
|
-
if _STOCK_MAP_CACHE is not None:
|
|
21
|
-
return _STOCK_MAP_CACHE
|
|
22
|
-
try:
|
|
20
|
+
def fetch():
|
|
23
21
|
import akshare as ak
|
|
24
22
|
|
|
25
23
|
df = _akshare_retry(ak.stock_zh_a_spot_em)
|
|
26
24
|
records = []
|
|
27
|
-
for
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
25
|
+
for row in df.to_dict("records"):
|
|
26
|
+
code, name = str(row["代码"]), row["名称"]
|
|
27
|
+
if (
|
|
28
|
+
len(code) != 6
|
|
29
|
+
or not code.isascii()
|
|
30
|
+
or not code.isdigit()
|
|
31
|
+
or not isinstance(name, str)
|
|
32
|
+
or not name.strip()
|
|
33
|
+
):
|
|
34
|
+
raise ValueError("Stock name map contains invalid codes or names")
|
|
35
|
+
records.append({"code": code, "name": name})
|
|
35
36
|
return records
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
return cached("stock-name-map:v1", DAY, fetch)
|
|
36
40
|
except Exception as e:
|
|
37
41
|
raise RuntimeError(f"Failed to load stock list: {e}") from e
|
|
38
42
|
|
|
39
43
|
|
|
44
|
+
@functools.cache # one attempt per process: import_parser resolves many names and failures are not disk-cached
|
|
45
|
+
def _load_international_stock_map() -> list[dict]:
|
|
46
|
+
# Odd provider rows are skipped: one unexpected code must not drop a whole market's names.
|
|
47
|
+
def fetch_hk():
|
|
48
|
+
import akshare as ak
|
|
49
|
+
|
|
50
|
+
records = []
|
|
51
|
+
for row in _akshare_retry(ak.stock_hk_spot_em).to_dict("records"):
|
|
52
|
+
code, name = str(row["代码"]).split(".", 1)[0].zfill(5), row["名称"]
|
|
53
|
+
if code.isdigit() and len(code) == 5 and isinstance(name, str) and name.strip():
|
|
54
|
+
records.append({"code": f"{code}.HK", "name": name})
|
|
55
|
+
return records
|
|
56
|
+
|
|
57
|
+
def fetch_us():
|
|
58
|
+
import akshare as ak
|
|
59
|
+
|
|
60
|
+
records = []
|
|
61
|
+
for row in _akshare_retry(ak.stock_us_spot_em).to_dict("records"):
|
|
62
|
+
code, name = normalize_us_symbol(row["代码"]), row["名称"]
|
|
63
|
+
if re.fullmatch(r"[A-Z0-9-]{1,10}", code) and isinstance(name, str) and name.strip():
|
|
64
|
+
records.append({"code": code, "name": name})
|
|
65
|
+
return records
|
|
66
|
+
|
|
67
|
+
records = []
|
|
68
|
+
for key, fetch in (("stock-name-map:hk:v1", fetch_hk), ("stock-name-map:us:v1", fetch_us)):
|
|
69
|
+
try:
|
|
70
|
+
records.extend(cached(key, DAY, fetch))
|
|
71
|
+
except Exception:
|
|
72
|
+
# One unavailable market must not hide the other markets' names.
|
|
73
|
+
continue
|
|
74
|
+
return records
|
|
75
|
+
|
|
76
|
+
|
|
40
77
|
def _to_pinyin(text: str) -> str:
|
|
41
78
|
try:
|
|
42
79
|
from pypinyin import lazy_pinyin
|
|
@@ -55,16 +92,16 @@ def _to_pinyin_initials(text: str) -> str:
|
|
|
55
92
|
return ""
|
|
56
93
|
|
|
57
94
|
|
|
58
|
-
def
|
|
59
|
-
stocks = _load_stock_map()
|
|
95
|
+
def _resolve_stocks(query: str, top: int, stocks: list[dict]) -> list[dict]:
|
|
60
96
|
query = query.strip()
|
|
61
97
|
q_lower = query.lower()
|
|
98
|
+
q_code = query.upper()
|
|
62
99
|
|
|
63
|
-
exact = [s for s in stocks if s["code"] ==
|
|
100
|
+
exact = [s for s in stocks if s["code"].upper() == q_code or s["name"] == query]
|
|
64
101
|
if exact:
|
|
65
102
|
return exact[:top]
|
|
66
103
|
|
|
67
|
-
prefix_code = [s for s in stocks if s["code"].startswith(
|
|
104
|
+
prefix_code = [s for s in stocks if s["code"].upper().startswith(q_code)]
|
|
68
105
|
if prefix_code:
|
|
69
106
|
return prefix_code[:top]
|
|
70
107
|
|
|
@@ -102,6 +139,30 @@ def resolve(query: str, top: int = 5) -> list[dict]:
|
|
|
102
139
|
return [{"code": s["code"], "name": s["name"], "score": round(sc, 2)} for sc, s in scored[:top]]
|
|
103
140
|
|
|
104
141
|
|
|
142
|
+
def resolve(query: str, top: int = 5) -> list[dict]:
|
|
143
|
+
load_error = None
|
|
144
|
+
try:
|
|
145
|
+
stocks = _load_stock_map()
|
|
146
|
+
local = _resolve_stocks(query, top, stocks)
|
|
147
|
+
except Exception as exc:
|
|
148
|
+
stocks, local, load_error = [], [], exc
|
|
149
|
+
query = query.strip()
|
|
150
|
+
code_like = re.fullmatch(r"[A-Za-z][A-Za-z0-9.-]{0,14}", query)
|
|
151
|
+
# A substring hit (京东 → 京东方A) is not proof the user meant an A share (京东集团-SW is HK).
|
|
152
|
+
partial_name = bool(local) and "score" not in local[0] and query != local[0]["name"] and query in local[0]["name"]
|
|
153
|
+
# Pinyin/initials scores are not proof either (特斯拉 → 天士力 scores 0.9), so only literal hits short-circuit.
|
|
154
|
+
if local and "score" not in local[0] and not code_like and not partial_name:
|
|
155
|
+
return local
|
|
156
|
+
international = _load_international_stock_map()
|
|
157
|
+
if international:
|
|
158
|
+
hits = _resolve_stocks(query, top, stocks + international)
|
|
159
|
+
if load_error is None or (hits and "score" not in hits[0]): # fuzzy-only hits are a miss
|
|
160
|
+
return hits
|
|
161
|
+
if load_error is not None:
|
|
162
|
+
raise load_error
|
|
163
|
+
return local
|
|
164
|
+
|
|
165
|
+
|
|
105
166
|
def main():
|
|
106
167
|
parser = argparse.ArgumentParser(description="Stock name resolver")
|
|
107
168
|
sub = parser.add_subparsers(dest="command")
|
|
@@ -118,7 +179,7 @@ def main():
|
|
|
118
179
|
try:
|
|
119
180
|
result = resolve(args.query, args.top)
|
|
120
181
|
except RuntimeError as e:
|
|
121
|
-
result = {"error":
|
|
182
|
+
result = {"error": error_message(e)}
|
|
122
183
|
print(json.dumps(result, ensure_ascii=False))
|
|
123
184
|
|
|
124
185
|
|
package/tools/report_renderer.py
CHANGED
|
@@ -12,7 +12,7 @@ from datetime import datetime, timezone
|
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
|
|
14
14
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
-
from _subproc import utf8_stdio
|
|
15
|
+
from _subproc import error_message, utf8_stdio
|
|
16
16
|
from market_review import save_review
|
|
17
17
|
|
|
18
18
|
try:
|
|
@@ -55,12 +55,12 @@ def render(kind: str, template: str, report: dict) -> dict:
|
|
|
55
55
|
try:
|
|
56
56
|
tpl = _env().get_template(tpl_path)
|
|
57
57
|
except Exception as e:
|
|
58
|
-
return {"error": f"failed to load template {tpl_path}: {e}"}
|
|
58
|
+
return {"error": f"failed to load template {tpl_path}: {error_message(e)}"}
|
|
59
59
|
|
|
60
60
|
try:
|
|
61
61
|
content = tpl.render(**report)
|
|
62
62
|
except Exception as e:
|
|
63
|
-
return {"error": f"render failed: {e}", "template": tpl_path}
|
|
63
|
+
return {"error": f"render failed: {error_message(e)}", "template": tpl_path}
|
|
64
64
|
|
|
65
65
|
return {
|
|
66
66
|
"meta": {
|
package/tools/requirements.txt
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
akshare>=1.
|
|
1
|
+
akshare>=1.20.24; python_version >= "3.11"
|
|
2
2
|
akshare>=1.14.0; python_version < "3.11"
|
|
3
3
|
yfinance>=0.2.36
|
|
4
|
-
pandas>=2.0.0
|
|
4
|
+
pandas>=2.0.0,<4
|
|
5
5
|
numpy>=1.24.0
|
|
6
6
|
pyyaml>=6.0
|
|
7
7
|
pypinyin>=0.50.0
|
|
8
|
+
pypdf>=5.0.0
|
|
8
9
|
requests>=2.33.0
|
|
9
10
|
exchange-calendars>=4.5.0
|
|
10
|
-
|
|
11
|
+
jinja2>=3.1.6
|
|
12
|
+
# optional providers: failover-only sources; setup-python.mjs only warns when one cannot install
|
|
11
13
|
efinance>=0.5.0
|
|
12
14
|
baostock>=0.8.8
|
|
13
|
-
pytdx>=1.72
|
|
14
15
|
longport>=1.0.0
|
|
15
16
|
finnhub-python>=2.4.0
|
|
16
|
-
|
|
17
|
+
newspaper4k>=0.9.6.1
|
package/tools/risk_screening.py
CHANGED
|
@@ -7,12 +7,13 @@ import math
|
|
|
7
7
|
import os
|
|
8
8
|
import sys
|
|
9
9
|
from concurrent.futures import Future, ThreadPoolExecutor
|
|
10
|
-
from datetime import
|
|
10
|
+
from datetime import timedelta
|
|
11
11
|
|
|
12
12
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
13
13
|
|
|
14
14
|
from _subproc import run_tool as _run_tool
|
|
15
15
|
from _subproc import utf8_stdio
|
|
16
|
+
from trading_calendar import market_now
|
|
16
17
|
|
|
17
18
|
|
|
18
19
|
def _safe_float(val) -> float | None:
|
|
@@ -181,7 +182,7 @@ def _fetch_lockup(symbol: str) -> dict:
|
|
|
181
182
|
if df.empty:
|
|
182
183
|
return result
|
|
183
184
|
|
|
184
|
-
now =
|
|
185
|
+
now = market_now("CN").replace(hour=0, minute=0, second=0, microsecond=0)
|
|
185
186
|
cutoff = now + timedelta(days=30)
|
|
186
187
|
|
|
187
188
|
date_col = None
|
package/tools/screener.py
CHANGED
|
@@ -148,12 +148,13 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
148
148
|
mom_parts.append(_minmax(df["volume_ratio"]))
|
|
149
149
|
df["momentum_score"] = pd.concat(mom_parts, axis=1).mean(axis=1) if mom_parts else np.nan
|
|
150
150
|
|
|
151
|
-
# Liquidity: higher turnover_rate and
|
|
151
|
+
# Liquidity: higher turnover_rate and money traded → higher score. Share volume would
|
|
152
|
+
# favour low-priced stocks, so the cross-stock leg ranks turnover (成交额).
|
|
152
153
|
liq_parts = []
|
|
153
154
|
if "turnover_rate" in df.columns:
|
|
154
155
|
liq_parts.append(_minmax(df["turnover_rate"]))
|
|
155
|
-
if "
|
|
156
|
-
liq_parts.append(_minmax(df["
|
|
156
|
+
if "turnover" in df.columns:
|
|
157
|
+
liq_parts.append(_minmax(df["turnover"].astype(float)))
|
|
157
158
|
df["liquidity_score"] = pd.concat(liq_parts, axis=1).mean(axis=1) if liq_parts else np.nan
|
|
158
159
|
|
|
159
160
|
groups = df[[f"{group}_score" for group in L1_WEIGHTS]].rename(columns=lambda name: name.removesuffix("_score"))
|
|
@@ -465,6 +466,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
465
466
|
"price",
|
|
466
467
|
"change_pct",
|
|
467
468
|
"volume",
|
|
469
|
+
"turnover",
|
|
468
470
|
"turnover_rate",
|
|
469
471
|
"pe",
|
|
470
472
|
"pe_basis",
|
|
@@ -489,7 +491,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
489
491
|
factor_inputs = {
|
|
490
492
|
"value": ("pe", "pb", "dividend_yield"),
|
|
491
493
|
"momentum": ("change_pct", "volume_ratio"),
|
|
492
|
-
"liquidity": ("turnover_rate", "
|
|
494
|
+
"liquidity": ("turnover_rate", "turnover"),
|
|
493
495
|
}
|
|
494
496
|
weights = L1_WEIGHTS
|
|
495
497
|
available = [
|