@weaxs/dsh-stock-analysis 0.2.4 → 0.2.6

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/tools/gather.py CHANGED
@@ -10,6 +10,7 @@ from pathlib import Path
10
10
  sys.path.insert(0, str(Path(__file__).resolve().parent))
11
11
  from _subproc import json_safe, run_tool, utf8_stdio # noqa: E402
12
12
  from stock_data import detect_market # noqa: E402
13
+ from technical import analyze_records # noqa: E402
13
14
 
14
15
 
15
16
  # gather fans out the heavier CLIs, so the default timeout stays 60s; raw stdout
@@ -32,36 +33,41 @@ def _parse_json(raw: str | None):
32
33
  return raw
33
34
 
34
35
 
35
- def _run_all(tasks: dict) -> dict:
36
+ def _run_all(tasks: dict, symbol: str) -> dict:
36
37
  with ThreadPoolExecutor(max_workers=len(tasks)) as pool:
37
38
  futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
38
- return {key: _parse_json(f.result()) for f, key in futures.items()}
39
+ result = {key: _parse_json(f.result()) for f, key in futures.items()}
40
+ result["technical"] = analyze_records(symbol, result["kline"]) if result["kline"] is not None else None
41
+ return result
39
42
 
40
43
 
41
44
  def gather_analysis(symbol: str) -> dict:
45
+ market = detect_market(symbol)
42
46
  tasks = {
43
47
  "quote": ("stock_data.py", ["quote", symbol]),
44
48
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "120"]),
45
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "120"]),
46
49
  "financials": ("stock_data.py", ["financials", symbol]),
47
50
  "capital_flow": ("stock_data.py", ["capital_flow", symbol]),
48
51
  "chip_distribution": ("stock_data.py", ["chip_distribution", symbol]),
49
52
  "news": ("search_intel.py", ["search", _news_query(symbol)]),
50
53
  "social_sentiment": ("search_intel.py", ["sentiment", symbol]),
51
54
  "risk": ("risk_screening.py", ["screen", symbol]),
52
- "regime": ("market_regime.py", ["detect"]),
53
55
  }
54
- return _run_all(tasks)
56
+ if market in ("A", "HK", "US"):
57
+ tasks["regime"] = ("market_regime.py", ["detect", market])
58
+ result = _run_all(tasks, symbol)
59
+ if market not in ("A", "HK", "US"):
60
+ result["regime"] = {"error": f"Market regime unavailable for {market}"}
61
+ return result
55
62
 
56
63
 
57
64
  def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict:
58
65
  tasks = {
59
66
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(kline_count)]),
60
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", str(kline_count)]),
61
67
  }
62
68
  if with_quote:
63
69
  tasks["quote"] = ("stock_data.py", ["quote", symbol])
64
- return _run_all(tasks)
70
+ return _run_all(tasks, symbol)
65
71
 
66
72
 
67
73
  def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -> dict:
@@ -73,16 +79,20 @@ def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -
73
79
 
74
80
 
75
81
  def gather_fundamental(symbol: str) -> dict:
82
+ market = detect_market(symbol)
76
83
  tasks = {
77
84
  "quote": ("stock_data.py", ["quote", symbol]),
78
85
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "60"]),
79
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]),
80
86
  "financials": ("stock_data.py", ["financials", symbol]),
81
87
  "news": ("search_intel.py", ["search", _news_query(symbol)]),
82
88
  "stock_info": ("stock_data.py", ["stock_info", symbol]),
83
- "sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
84
89
  }
85
- return _run_all(tasks)
90
+ if market == "A":
91
+ tasks["sector_rankings"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
92
+ result = _run_all(tasks, symbol)
93
+ if market != "A":
94
+ result["sector_rankings"] = {"error": f"Sector rankings unavailable for {market}"}
95
+ return result
86
96
 
87
97
 
88
98
  def main():
@@ -0,0 +1,100 @@
1
+ """Optional Lixinger HK non-financial datasets (same env token as index data)."""
2
+
3
+ import os
4
+ from datetime import date, timedelta
5
+
6
+ import requests
7
+ from _cache import DAY, cached
8
+
9
+
10
+ def hk_data(symbol, dataset, metrics):
11
+ code = symbol.split(".")[0].zfill(5)
12
+ end = date.today()
13
+ try:
14
+ start = end.replace(year=end.year - 10)
15
+ except ValueError:
16
+ start = end.replace(year=end.year - 10, day=28) + timedelta(days=1)
17
+
18
+ def fetch():
19
+ response = requests.post(
20
+ f"https://open.lixinger.com/api/hk/company/{dataset}/non_financial",
21
+ json={
22
+ "token": os.environ["LIXINGER_TOKEN"],
23
+ "stockCodes": [code],
24
+ "startDate": start.isoformat(),
25
+ "endDate": end.isoformat(),
26
+ "metricsList": metrics,
27
+ },
28
+ timeout=20,
29
+ )
30
+ response.raise_for_status()
31
+ payload = response.json()
32
+ if payload.get("code") != 1 or not isinstance(payload.get("data"), list) or not payload["data"]:
33
+ raise ValueError("Lixinger HK non-financial data unavailable; check token permissions/company type")
34
+ return payload["data"]
35
+
36
+ return cached(f"lixinger-hk:{dataset}:{code}:{end}:{','.join(metrics)}", DAY, fetch)
37
+
38
+
39
+ def financials_hk(symbol, periods, annual):
40
+ fields = {
41
+ "roe": "m.roe",
42
+ "gross_margin": "ps.gp_m",
43
+ "net_profit_margin": "ps.np_s_r",
44
+ "total_revenue": "ps.toi",
45
+ "net_income": "ps.np",
46
+ "operating_cash_flow": "cfs.ncffoa",
47
+ }
48
+ data = hk_data(symbol, "fs", [f"q.{field}.t" for field in fields.values()])
49
+ history = []
50
+ for row in sorted(data, key=lambda r: r.get("date", ""), reverse=True):
51
+ if annual and row.get("reportType") != "annual_report":
52
+ continue
53
+ if not row.get("date") or row.get("stockCode", symbol.split(".")[0].zfill(5)) != symbol.split(".")[0].zfill(5):
54
+ continue
55
+ entry = {
56
+ "report_date": row["date"][:10],
57
+ "disclosure_date": (row.get("reportDate") or "")[:10] or None,
58
+ "report_type": row.get("reportType"),
59
+ "currency": row.get("currency"),
60
+ "source": "lixinger",
61
+ }
62
+ for key, field in fields.items():
63
+ table, metric = field.split(".")
64
+ value = row.get("q", {}).get(table, {}).get(metric, {}).get("t")
65
+ entry[key] = (
66
+ value * 100 if value is not None and key in ("roe", "gross_margin", "net_profit_margin") else value
67
+ )
68
+ if any(entry.get(key) is not None for key in fields):
69
+ history.append(entry)
70
+ if not history:
71
+ raise ValueError("Lixinger returned no matching financial periods")
72
+ history = history[:periods]
73
+ latest = history[0]
74
+ result = {
75
+ **dict.fromkeys(("name", "market_cap", "pe", "forward_pe", "pb", "debt_to_equity", "dividend_yield")),
76
+ "snapshot_available": False,
77
+ "symbol": symbol,
78
+ "source": "lixinger",
79
+ "report_date": latest["report_date"],
80
+ "currency": latest["currency"],
81
+ "total_revenue": latest["total_revenue"],
82
+ "net_income": latest["net_income"],
83
+ "roe": latest["roe"] / 100 if latest["roe"] is not None else None,
84
+ "profit_margin": latest["net_profit_margin"] / 100 if latest["net_profit_margin"] is not None else None,
85
+ "periods": history,
86
+ "requested_periods": periods,
87
+ "available_periods": len(history),
88
+ "history_units": {
89
+ "roe": "percent",
90
+ "gross_margin": "percent",
91
+ "net_profit_margin": "percent",
92
+ "total_revenue": "reported currency",
93
+ "net_income": "reported currency",
94
+ "operating_cash_flow": "reported currency",
95
+ },
96
+ "accounting_basis": "provider-reported HK financial statements; not normalized to A-share accounting",
97
+ }
98
+ if len(history) < periods:
99
+ result["warnings"] = ["Requested financial history incomplete; only actual available periods returned"]
100
+ return result
@@ -54,7 +54,9 @@ def _get_index_kline(market: str) -> list:
54
54
  def _compute_indicators(klines: list) -> dict:
55
55
  import numpy as np
56
56
 
57
- closes = np.array([float(k["close"]) for k in klines if k.get("close") is not None])
57
+ df = pd.DataFrame(klines).reindex(columns=["close", "high", "low"]).apply(pd.to_numeric, errors="coerce")
58
+ df = df[np.isfinite(df).all(axis=1) & (df > 0).all(axis=1)]
59
+ closes = df["close"].to_numpy()
58
60
  if len(closes) < 20:
59
61
  return {}
60
62
 
@@ -65,8 +67,8 @@ def _compute_indicators(klines: list) -> dict:
65
67
  ma60 = float(ma_series(close_s, 60).iloc[-1]) if len(closes) >= 60 else float(np.mean(closes))
66
68
  close = float(closes[-1])
67
69
 
68
- highs = np.array([float(k["high"]) for k in klines if k.get("high") is not None])
69
- lows = np.array([float(k["low"]) for k in klines if k.get("low") is not None])
70
+ highs = df["high"].to_numpy()
71
+ lows = df["low"].to_numpy()
70
72
 
71
73
  tr_values = []
72
74
  for i in range(-min(14, len(closes) - 1), 0):
@@ -226,6 +228,8 @@ def main():
226
228
  if args.command == "detect":
227
229
  result = detect_regime(args.market)
228
230
  print(json.dumps(result, ensure_ascii=False, default=str))
231
+ if "error" in result:
232
+ sys.exit(1)
229
233
 
230
234
 
231
235
  if __name__ == "__main__":
@@ -19,7 +19,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19
19
 
20
20
  from _subproc import run_tool as _run_tool
21
21
  from _subproc import utf8_stdio
22
- from signal_tracker import _load_records
22
+ from signal_tracker import _append_record, _load_records, _store_lock
23
23
 
24
24
 
25
25
  def calc_temperature(stats: dict, indices: list) -> dict:
@@ -145,10 +145,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
145
145
  """Append one review report object to the JSONL archive (side effect of render --save)."""
146
146
  store = store or _default_store()
147
147
  try:
148
- store.parent.mkdir(parents=True, exist_ok=True)
149
- with store.open("a", encoding="utf-8") as f:
150
- f.write(json.dumps(report, ensure_ascii=False, default=str) + "\n")
151
- except OSError as e:
148
+ with _store_lock(store):
149
+ _append_record(store, report)
150
+ except (OSError, ValueError) as e:
152
151
  return {"error": str(e)}
153
152
  return {"saved": True, "date": report.get("review_date") or report.get("date")}
154
153
 
@@ -156,7 +155,9 @@ def save_review(report: dict, store: Path | None = None) -> dict:
156
155
  def cmd_history(args) -> dict:
157
156
  """Recent archived reviews, newest first. Empty store -> clean empty list."""
158
157
  try:
159
- records = _load_records(Path(args.store) if args.store else _default_store())
158
+ store = Path(args.store) if args.store else _default_store()
159
+ with _store_lock(store):
160
+ records = _load_records(store)
160
161
  except (OSError, UnicodeDecodeError) as e:
161
162
  # store is a directory / not UTF-8 — same clean-error contract as save_review
162
163
  return {"error": str(e)}
@@ -6,6 +6,7 @@ Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
6
6
 
7
7
  import argparse
8
8
  import json
9
+ import math
9
10
  import sys
10
11
  from datetime import datetime, timezone
11
12
  from pathlib import Path
@@ -48,13 +49,28 @@ def analyze_position(
48
49
  stop_loss: float | None = None,
49
50
  take_profit: float | None = None,
50
51
  ) -> dict:
52
+ for field, value in (
53
+ ("cost", cost),
54
+ ("quantity", quantity),
55
+ ("stop_loss", stop_loss),
56
+ ("take_profit", take_profit),
57
+ ):
58
+ if value is not None and (not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0):
59
+ return {"symbol": symbol, "error": f"{field} must be finite and positive"}
51
60
  quote = _run_json("stock_data.py", ["quote", symbol]) or {}
52
61
  tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) or {}
53
62
 
54
- price = quote.get("price")
63
+ price = quote.get("price") if isinstance(quote, dict) and "error" not in quote else None
55
64
  if price is None:
56
65
  return {"symbol": symbol, "error": "cannot fetch current price"}
57
- price = float(price)
66
+ try:
67
+ price = float(price)
68
+ except (TypeError, ValueError):
69
+ return {"symbol": symbol, "error": "current price must be finite and positive"}
70
+ if not math.isfinite(price) or price <= 0:
71
+ return {"symbol": symbol, "error": "current price must be finite and positive"}
72
+ if not isinstance(tech, dict):
73
+ tech = {}
58
74
 
59
75
  pnl_per_share = price - cost
60
76
  pnl_pct = (pnl_per_share / cost * 100) if cost else 0.0
@@ -133,6 +149,8 @@ def main():
133
149
  )
134
150
  json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
135
151
  print()
152
+ if "error" in result:
153
+ sys.exit(1)
136
154
 
137
155
 
138
156
  if __name__ == "__main__":
@@ -112,6 +112,8 @@ def main():
112
112
  result["archived"] = save_review(report)
113
113
  json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
114
114
  print()
115
+ if "error" in result:
116
+ sys.exit(1)
115
117
 
116
118
 
117
119
  if __name__ == "__main__":
@@ -3,6 +3,7 @@
3
3
 
4
4
  import argparse
5
5
  import json
6
+ import math
6
7
  import os
7
8
  import sys
8
9
  from concurrent.futures import ThreadPoolExecutor
@@ -19,7 +20,7 @@ def _safe_float(val) -> float | None:
19
20
  return None
20
21
  try:
21
22
  v = float(val)
22
- return v if v == v else None # NaN check
23
+ return v if math.isfinite(v) else None
23
24
  except (ValueError, TypeError):
24
25
  return None
25
26
 
@@ -29,9 +30,12 @@ def _safe_float(val) -> float | None:
29
30
 
30
31
  def check_valuation(symbol: str) -> dict:
31
32
  quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
33
+ if not isinstance(quote, dict) or "error" in quote:
34
+ quote = {}
32
35
  pe = _safe_float(quote.get("pe"))
33
36
  pb = _safe_float(quote.get("pb"))
34
- result = {"pe": pe, "pb": pb, "status": "normal", "flags": []}
37
+ available = pe is not None or pb is not None
38
+ result = {"pe": pe, "pb": pb, "status": "normal" if available else "unknown", "flags": [], "available": available}
35
39
 
36
40
  if pe is not None:
37
41
  if pe < 0:
@@ -91,14 +95,15 @@ def check_valuation(symbol: str) -> dict:
91
95
 
92
96
  def check_technical(symbol: str) -> dict:
93
97
  ta = _run_tool("technical.py", ["analyze", symbol])
94
- result = {"flags": []}
98
+ result = {"flags": [], "available": False}
95
99
 
96
- if not ta or "error" in ta:
100
+ if not isinstance(ta, dict) or not ta or "error" in ta:
97
101
  return result
98
102
 
99
103
  signal = ta.get("buy_signal", "")
100
104
  score = _safe_float(ta.get("signal_score"))
101
- trend = ta.get("trend", {}).get("overall", "")
105
+ result["available"] = score is not None
106
+ trend = (ta.get("trend") or {}).get("overall", "")
102
107
 
103
108
  if signal in ("STRONG_SELL",):
104
109
  result["flags"].append(
@@ -130,7 +135,7 @@ def check_technical(symbol: str) -> dict:
130
135
  )
131
136
 
132
137
  macd = ta.get("macd", {})
133
- if macd.get("signal") == "death_cross":
138
+ if macd.get("cross") == "death_cross":
134
139
  result["flags"].append(
135
140
  {"category": "technical", "severity": "medium", "description": "MACD死叉", "source": "data"}
136
141
  )
@@ -145,15 +150,27 @@ def check_technical(symbol: str) -> dict:
145
150
 
146
151
 
147
152
  def check_lockup(symbol: str) -> dict:
148
- result = {"upcoming_30d": [], "flags": []}
153
+ result = _run_tool("risk_screening.py", ["lockup", symbol], timeout=25)
154
+ return (
155
+ result
156
+ if isinstance(result, dict) and "error" not in result
157
+ else {"upcoming_30d": [], "flags": [], "available": False}
158
+ )
159
+
160
+
161
+ def _fetch_lockup(symbol: str) -> dict:
162
+ result = {"upcoming_30d": [], "flags": [], "available": False}
149
163
  try:
150
164
  import akshare as ak
151
165
 
152
166
  df = ak.stock_restricted_release_queue_em(symbol=symbol)
153
- if df is None or df.empty:
167
+ if df is None:
168
+ return result
169
+ result["available"] = True
170
+ if df.empty:
154
171
  return result
155
172
 
156
- now = datetime.now()
173
+ now = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
157
174
  cutoff = now + timedelta(days=30)
158
175
 
159
176
  date_col = None
@@ -180,7 +197,7 @@ def check_lockup(symbol: str) -> dict:
180
197
  }
181
198
  )
182
199
  except Exception:
183
- pass
200
+ result["available"] = False
184
201
  return result
185
202
 
186
203
 
@@ -195,7 +212,7 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
195
212
  "regulatory": f"{search_name} 处罚 违规 监管 立案",
196
213
  "industry": f"{search_name} 行业政策 监管 限制",
197
214
  }
198
- result = {"flags": []}
215
+ result = {"flags": [], "available": True}
199
216
  # four independent search_intel subprocesses — fan out concurrently (same
200
217
  # ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in
201
218
  # declaration order keeps result keys and flags stably ordered
@@ -209,8 +226,10 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
209
226
  items = []
210
227
  if isinstance(data, list):
211
228
  items = data
212
- elif isinstance(data, dict) and "results" in data:
229
+ elif isinstance(data, dict) and "error" not in data and isinstance(data.get("results"), list):
213
230
  items = data["results"]
231
+ else:
232
+ result["available"] = False
214
233
 
215
234
  result[cat] = items
216
235
  if items:
@@ -265,7 +284,7 @@ def screen_risk(symbol: str, name: str = "") -> dict:
265
284
  checks = {}
266
285
 
267
286
  val = check_valuation(symbol)
268
- checks["valuation"] = {"pe": val["pe"], "pb": val["pb"], "status": val["status"]}
287
+ checks["valuation"] = {k: val[k] for k in ("pe", "pb", "status", "available")}
269
288
  all_flags.extend(val["flags"])
270
289
 
271
290
  tech = check_technical(symbol)
@@ -273,11 +292,12 @@ def screen_risk(symbol: str, name: str = "") -> dict:
273
292
  "buy_signal": tech.get("buy_signal"),
274
293
  "signal_score": tech.get("signal_score"),
275
294
  "trend": tech.get("trend"),
295
+ "available": tech["available"],
276
296
  }
277
297
  all_flags.extend(tech["flags"])
278
298
 
279
299
  lockup = check_lockup(symbol)
280
- checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"]}
300
+ checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"], "available": lockup["available"]}
281
301
  all_flags.extend(lockup["flags"])
282
302
 
283
303
  news = check_news_risks(symbol, name)
@@ -285,12 +305,16 @@ def screen_risk(symbol: str, name: str = "") -> dict:
285
305
  all_flags.extend(news["flags"])
286
306
 
287
307
  risk = compute_risk(all_flags)
308
+ missing = [key for key, value in checks.items() if not value.get("available")]
309
+ complete = not missing
288
310
  return {
289
311
  "symbol": symbol,
290
312
  "name": name,
291
- "risk_level": risk["risk_level"],
292
- "risk_score": risk["risk_score"],
293
- "veto_buy": risk["veto_buy"],
313
+ "risk_level": "unknown" if missing and risk["risk_level"] == "low" else risk["risk_level"],
314
+ "risk_score": risk["risk_score"] if all_flags or complete else None,
315
+ "veto_buy": risk["veto_buy"] if risk["veto_buy"] or complete else None,
316
+ "data_complete": complete,
317
+ "warnings": [f"{key} risk data unavailable or incomplete" for key in missing],
294
318
  "flags": all_flags,
295
319
  "checks": checks,
296
320
  }
@@ -303,6 +327,8 @@ def main():
303
327
  p_screen = sub.add_parser("screen")
304
328
  p_screen.add_argument("symbol")
305
329
  p_screen.add_argument("--name", default="")
330
+ p_lockup = sub.add_parser("lockup", help="Internal bounded lockup query")
331
+ p_lockup.add_argument("symbol")
306
332
 
307
333
  args = parser.parse_args()
308
334
  if not args.command:
@@ -312,6 +338,8 @@ def main():
312
338
  if args.command == "screen":
313
339
  result = screen_risk(args.symbol, args.name)
314
340
  print(json.dumps(result, ensure_ascii=False, default=str))
341
+ elif args.command == "lockup":
342
+ print(json.dumps(_fetch_lockup(args.symbol), ensure_ascii=False, default=str))
315
343
 
316
344
 
317
345
  if __name__ == "__main__":
package/tools/screener.py CHANGED
@@ -73,6 +73,13 @@ def merge_filters(config: dict | None) -> dict:
73
73
 
74
74
  def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
75
75
  conditions = []
76
+ for bound, op in [("dividend_yield_min", "min"), ("dividend_yield_max", "max")]:
77
+ if bound in filters:
78
+ if "dividend_yield" not in df.columns:
79
+ return df.iloc[0:0].copy()
80
+ conditions.append(
81
+ df["dividend_yield"] >= filters[bound] if op == "min" else df["dividend_yield"] <= filters[bound]
82
+ )
76
83
  if "pe" in df.columns:
77
84
  conditions.append(df["pe"] >= filters["pe_min"])
78
85
  conditions.append(df["pe"] <= filters["pe_max"])
@@ -121,7 +128,10 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
121
128
  value_parts.append(100 - _minmax(df["pe"]))
122
129
  if "pb" in df.columns:
123
130
  value_parts.append(100 - _minmax(df["pb"]))
124
- df["value_score"] = sum(value_parts) / max(len(value_parts), 1)
131
+ if "dividend_yield" in df.columns:
132
+ df["dividend_score"] = _minmax(df["dividend_yield"])
133
+ value_parts.append(df["dividend_score"])
134
+ df["value_score"] = pd.concat(value_parts, axis=1).mean(axis=1) if value_parts else 0.0
125
135
 
126
136
  # Momentum: higher change_pct and volume_ratio → higher score
127
137
  mom_parts = []
@@ -304,6 +314,21 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
304
314
 
305
315
 
306
316
  def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
317
+ if config is not None and (not isinstance(config, dict) or not isinstance(config.get("filters", {}), dict)):
318
+ return {"error": "config and filters must be objects", "market": market}
319
+ filters = merge_filters(config)
320
+ supported = set(DEFAULT_FILTERS) | {"dividend_yield_min", "dividend_yield_max"}
321
+ for key, value in filters.items():
322
+ if key not in supported:
323
+ return {"error": f"Unsupported filter: {key}", "market": market}
324
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value):
325
+ return {"error": f"{key} must be a finite number", "market": market}
326
+ dividend_requested = any(k.startswith("dividend_yield_") for k in filters) or (config or {}).get("sort_by") in (
327
+ "dividend_yield",
328
+ "dividend_score",
329
+ )
330
+ if dividend_requested and market not in ("A", "HK"):
331
+ return {"error": "dividend screening currently covers A/HK only", "market": market}
307
332
  raw = fetch_snapshot(market)
308
333
  if isinstance(raw, dict) and "error" in raw:
309
334
  return raw
@@ -330,7 +355,35 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
330
355
  if existing:
331
356
  df = df.dropna(subset=existing)
332
357
 
333
- filters = merge_filters(config)
358
+ dividend_meta = {}
359
+ if dividend_requested:
360
+ try:
361
+ from value_data import dividend_ranking
362
+
363
+ ranked = dividend_ranking(report_date=(config or {}).get("dividend_report_date", ""), market=market)
364
+
365
+ def dividend_key(symbol):
366
+ return symbol.split(".")[0].lstrip("0") if market == "HK" else symbol
367
+
368
+ yields = {dividend_key(r["symbol"]): r["dividend_yield"] for r in ranked["items"]}
369
+ df["dividend_yield"] = df["symbol"].map(dividend_key).map(yields)
370
+ dividend_meta = {
371
+ "dividend_factor": {
372
+ "report_date": ranked["report_date"],
373
+ "yield_basis": ranked.get("yield_basis", "provider report-period cash dividend yield, percent"),
374
+ "missing": "unknown; excluded by dividend filters",
375
+ }
376
+ }
377
+ except Exception:
378
+ return {
379
+ "error": "dividend data unavailable; requested dividend criterion was not applied",
380
+ "market": market,
381
+ }
382
+ explicit = (config or {}).get("filters") or {}
383
+ missing = [key for key in explicit if key.rsplit("_", 1)[0] not in df]
384
+ if missing:
385
+ return {"error": f"Requested filter data unavailable: {', '.join(missing)}", "market": market}
386
+ applied_filters = {key: value for key, value in filters.items() if key.rsplit("_", 1)[0] in df}
334
387
  df = apply_filters(df, filters)
335
388
  filtered_count = len(df)
336
389
 
@@ -340,10 +393,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
340
393
  "total_stocks": total,
341
394
  "filtered_count": 0,
342
395
  "returned_count": 0,
343
- "filters_applied": filters,
396
+ "filters_applied": applied_filters,
344
397
  "candidates": [],
345
398
  "market_sentiment": sentiment,
346
399
  "l2_enabled": l2_enabled,
400
+ **dividend_meta,
347
401
  }
348
402
 
349
403
  df = compute_scores(df)
@@ -374,6 +428,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
374
428
  "pb",
375
429
  "market_cap",
376
430
  "volume_ratio",
431
+ "dividend_yield",
377
432
  ]:
378
433
  v = _finite(row.get(field))
379
434
  if v is not None:
@@ -386,6 +441,8 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
386
441
  "composite": None if composite is None else round(composite, 1),
387
442
  "final": None if composite is None else round(composite * multiplier, 1),
388
443
  }
444
+ if "dividend_score" in row:
445
+ entry["scores"]["dividend"] = _finite(round(float(row["dividend_score"]), 1))
389
446
  candidates.append(entry)
390
447
 
391
448
  if l2_enabled:
@@ -399,10 +456,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
399
456
  "total_stocks": total,
400
457
  "filtered_count": filtered_count,
401
458
  "returned_count": len(candidates),
402
- "filters_applied": filters,
459
+ "filters_applied": applied_filters,
403
460
  "candidates": candidates,
404
461
  "market_sentiment": sentiment,
405
462
  "l2_enabled": l2_enabled,
463
+ **dividend_meta,
406
464
  }
407
465
 
408
466
 
@@ -426,6 +484,8 @@ def main():
426
484
  config = load_config(args.config) if args.config else None
427
485
  result = screen(args.market, args.top, config, l2=args.l2)
428
486
  print(json.dumps(result, ensure_ascii=False, default=str))
487
+ if "error" in result:
488
+ sys.exit(1)
429
489
 
430
490
 
431
491
  if __name__ == "__main__":