alphasift 0.3.1__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.
Files changed (86) hide show
  1. alphasift/__init__.py +52 -0
  2. alphasift/__main__.py +7 -0
  3. alphasift/audit.py +191 -0
  4. alphasift/candidate_context.py +738 -0
  5. alphasift/cli.py +2797 -0
  6. alphasift/config.py +705 -0
  7. alphasift/context.py +672 -0
  8. alphasift/daily.py +1256 -0
  9. alphasift/daily_brief.py +593 -0
  10. alphasift/daily_report.py +1115 -0
  11. alphasift/daily_report_html.py +1257 -0
  12. alphasift/doctor.py +1123 -0
  13. alphasift/dsa.py +302 -0
  14. alphasift/dsa_adapter.py +178 -0
  15. alphasift/dsa_provider.py +192 -0
  16. alphasift/evaluate.py +2418 -0
  17. alphasift/filter.py +517 -0
  18. alphasift/hotspot.py +1713 -0
  19. alphasift/industry.py +959 -0
  20. alphasift/llm_client.py +349 -0
  21. alphasift/market_digest.py +284 -0
  22. alphasift/market_news.py +446 -0
  23. alphasift/market_regime.py +578 -0
  24. alphasift/markets.py +160 -0
  25. alphasift/mcp.py +720 -0
  26. alphasift/models.py +315 -0
  27. alphasift/normalize.py +113 -0
  28. alphasift/notify.py +2608 -0
  29. alphasift/overview.py +225 -0
  30. alphasift/pack.py +1470 -0
  31. alphasift/pack_features.py +431 -0
  32. alphasift/pattern_replay.py +1449 -0
  33. alphasift/patterns/bottom_volume_yang.yaml +32 -0
  34. alphasift/patterns/box_breakout.yaml +36 -0
  35. alphasift/patterns/double_bottom_breakout.yaml +38 -0
  36. alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
  37. alphasift/patterns/shooting_star_confirm.yaml +49 -0
  38. alphasift/patterns/single_yang_hold.yaml +44 -0
  39. alphasift/patterns/steady_trend_breakout.yaml +39 -0
  40. alphasift/patterns/three_white_soldiers.yaml +72 -0
  41. alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
  42. alphasift/patterns.py +1233 -0
  43. alphasift/performance_history.py +297 -0
  44. alphasift/pipeline.py +1010 -0
  45. alphasift/post_analysis.py +337 -0
  46. alphasift/ranker.py +990 -0
  47. alphasift/report.py +379 -0
  48. alphasift/result_schema.py +179 -0
  49. alphasift/risk.py +452 -0
  50. alphasift/run_history.py +164 -0
  51. alphasift/scorer.py +597 -0
  52. alphasift/server.py +680 -0
  53. alphasift/snapshot.py +1025 -0
  54. alphasift/snapshot_us.py +280 -0
  55. alphasift/snapshot_yahoo.py +358 -0
  56. alphasift/source_guard.py +70 -0
  57. alphasift/source_history.py +306 -0
  58. alphasift/store.py +294 -0
  59. alphasift/strategies/balanced_alpha.yaml +76 -0
  60. alphasift/strategies/blue_chip_income.yaml +87 -0
  61. alphasift/strategies/capital_heat.yaml +74 -0
  62. alphasift/strategies/dual_low.yaml +80 -0
  63. alphasift/strategies/global_value.yaml +65 -0
  64. alphasift/strategies/low_volatility_quality.yaml +95 -0
  65. alphasift/strategies/momentum_quality.yaml +81 -0
  66. alphasift/strategies/oversold_reversal.yaml +75 -0
  67. alphasift/strategies/quality_value.yaml +80 -0
  68. alphasift/strategies/shrink_pullback.yaml +77 -0
  69. alphasift/strategies/us_momentum_quality.yaml +74 -0
  70. alphasift/strategies/volume_breakout.yaml +78 -0
  71. alphasift/strategy.py +1090 -0
  72. alphasift/strategy_cards.py +424 -0
  73. alphasift/strategy_templates.py +291 -0
  74. alphasift/timeutil.py +38 -0
  75. alphasift/valuation_kr.py +149 -0
  76. alphasift/workbench_ui.py +1051 -0
  77. alphasift-0.3.1.data/data/.env.example +151 -0
  78. alphasift-0.3.1.data/data/LICENSE +184 -0
  79. alphasift-0.3.1.data/data/SKILL.md +190 -0
  80. alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
  81. alphasift-0.3.1.dist-info/METADATA +312 -0
  82. alphasift-0.3.1.dist-info/RECORD +86 -0
  83. alphasift-0.3.1.dist-info/WHEEL +5 -0
  84. alphasift-0.3.1.dist-info/entry_points.txt +2 -0
  85. alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
  86. alphasift-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,738 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Optional Top-K candidate news, announcement and fund-flow context."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ from datetime import datetime, timedelta
8
+ import inspect
9
+ import json
10
+ from pathlib import Path
11
+ import re
12
+
13
+ import pandas as pd
14
+ import requests
15
+
16
+ from alphasift.source_guard import call_with_timeout
17
+
18
+ _NEGATIVE_EVENT_KEYWORDS = {
19
+ "减持": ("减持", "拟减持", "被动减持"),
20
+ "监管": ("处罚", "立案", "监管函", "问询函", "警示函", "调查"),
21
+ "业绩压力": ("预亏", "亏损", "业绩下滑", "业绩减少", "净利润下降"),
22
+ "财务风险": (
23
+ "债务违约",
24
+ "债务逾期",
25
+ "逾期",
26
+ "违约",
27
+ "债务危机",
28
+ "债务纠纷",
29
+ "重大债务",
30
+ "资不抵债",
31
+ "资金链断裂",
32
+ "无法清偿",
33
+ "商誉减值",
34
+ "资产减值",
35
+ ),
36
+ "退市风险": ("退市", "终止上市", "风险警示"),
37
+ "诉讼风险": ("诉讼", "涉诉", "仲裁"),
38
+ "质押冻结": ("冻结", "质押"),
39
+ }
40
+ _ITEM_SPLIT_RE = re.compile(r"\s*\|\s*|[;。\n]+")
41
+ _NEGATION_REDUCTION_RE = re.compile(
42
+ r"(?:承诺|决定|同意|提前)?(?:不|未|无|终止|取消|放弃)减持|提前终止减持(?:计划)?|减持时间届满且未减持"
43
+ )
44
+ _NEGATION_REGULATOR_RE = re.compile(
45
+ r"不予处罚|免于处罚|未被立案|无监管处罚|不存在(?:被)?处罚|解除警示"
46
+ )
47
+ _NEGATION_EARNINGS_RE = re.compile(
48
+ r"(?:不存在|无)(?:业绩下滑|亏损)|同比减亏|亏损收窄|扭亏为盈"
49
+ )
50
+ _BENIGN_FINANCE_RE = re.compile(
51
+ r"(?:非金融企业)?债务融资工具|发行(?:公司|科技)?债券|科技创新债券|偿还债务|债务豁免|可转债"
52
+ )
53
+ _ROUTINE_IMPAIRMENT_RE = re.compile(r"计提(?:各项|信用|资产|信用及资产)?减值准备")
54
+ _SEVERE_IMPAIRMENT_CUES = ("商誉减值", "大额", "巨额", "预亏", "亏损", "净利润下降", "重大", "大幅")
55
+ _ST_SYMBOL_RE = re.compile(r"(?<![A-Za-z0-9])\*?ST(?![A-Za-z0-9])")
56
+ _NEGATION_DELIST_RE = re.compile(
57
+ r"撤销(?:退市|其他)?风险警示|不存在退市风险|不触发退市|申请摘帽"
58
+ )
59
+ _NEGATION_PLEDGE_RE = re.compile(
60
+ r"(?:部分|全部)?(?:股份|股权)?(?:解除|解押)(?:部分|全部)?(?:股份|股权)?(?:质押|冻结)"
61
+ r"|(?:质押|冻结)(?:已)?解除|(?:银行)?账户(?:解除|解冻)|质押展期|已解押"
62
+ )
63
+ _NEGATION_LITIGATION_RE = re.compile(
64
+ r"(?:诉讼|涉诉|仲裁)(?:事项)?(?:进展)?[^,;|]{0,12}(?:胜诉|撤诉|结案|和解|终结|驳回)"
65
+ r"|(?:撤诉|胜诉|终结(?:执行)?|达成和解)[^,;|]{0,12}(?:诉讼|涉诉|仲裁)"
66
+ r"|(?:不涉及|无|不存在)(?:重大)?(?:诉讼|涉诉|仲裁)"
67
+ )
68
+ _POSITIVE_EVENT_KEYWORDS = {
69
+ "回购增持": ("回购", "增持"),
70
+ "订单经营": ("中标", "合同", "订单", "定点", "合作"),
71
+ "业绩改善": ("预增", "扭亏", "增长", "净利润增长"),
72
+ "股东回报": ("分红", "派息"),
73
+ "激励": ("股权激励", "员工持股"),
74
+ }
75
+ _ANNOUNCEMENT_CATEGORY_KEYWORDS = {
76
+ "业绩": ("业绩", "利润", "营收", "预增", "预亏", "扭亏", "年报", "季报"),
77
+ "回购增持": ("回购", "增持"),
78
+ "减持": ("减持", "被动减持"),
79
+ "监管问询": ("监管函", "问询函", "警示函", "立案", "调查", "处罚"),
80
+ "重大合同": ("中标", "合同", "订单", "定点", "合作协议"),
81
+ "分红融资": ("分红", "派息", "配股", "定增", "可转债", "融资"),
82
+ "诉讼担保": ("诉讼", "仲裁", "担保", "冻结", "质押"),
83
+ "股权激励": ("股权激励", "员工持股"),
84
+ }
85
+ _SOURCE_WEIGHTS = {
86
+ "announcement": 1.0,
87
+ "quote": 0.85,
88
+ "news": 0.65,
89
+ "fund_flow": 0.75,
90
+ }
91
+ _DEFAULT_MAX_WORKERS = 6
92
+
93
+
94
+ def collect_candidate_context(
95
+ candidate_df: pd.DataFrame,
96
+ *,
97
+ max_rows: int = 8,
98
+ providers: list[str] | None = None,
99
+ news_limit: int = 3,
100
+ announcement_limit: int = 3,
101
+ cache_dir: str | Path | None = None,
102
+ cache_ttl_hours: int = 24,
103
+ source_weights: dict[str, float] | None = None,
104
+ ) -> tuple[list[dict[str, object]], list[str]]:
105
+ """Collect candidate-level context rows keyed by stock code.
106
+
107
+ The function is optional and best-effort. It should never decide
108
+ eligibility; it only supplies LLM research material for already shortlisted
109
+ candidates.
110
+ """
111
+ if candidate_df.empty or "code" not in candidate_df.columns or max_rows <= 0:
112
+ return [], []
113
+
114
+ providers = _normalize_providers(providers or [])
115
+ tasks: list[dict[str, str]] = []
116
+ for _, candidate in candidate_df.head(max_rows).iterrows():
117
+ code = _normalize_code(candidate.get("code", ""))
118
+ if not code or code == "000000":
119
+ continue
120
+ tasks.append(
121
+ {
122
+ "code": code,
123
+ "name": str(candidate.get("name", "") or ""),
124
+ }
125
+ )
126
+
127
+ if not tasks:
128
+ return [], []
129
+
130
+ results: list[tuple[dict[str, object] | None, list[str]] | None] = [None] * len(tasks)
131
+ max_workers = min(_DEFAULT_MAX_WORKERS, len(tasks))
132
+ if max_workers <= 1:
133
+ for index, task in enumerate(tasks):
134
+ results[index] = _collect_candidate_context_row(
135
+ task,
136
+ providers=providers,
137
+ news_limit=news_limit,
138
+ announcement_limit=announcement_limit,
139
+ cache_dir=cache_dir,
140
+ cache_ttl_hours=cache_ttl_hours,
141
+ source_weights=source_weights,
142
+ )
143
+ else:
144
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
145
+ future_to_index = {
146
+ executor.submit(
147
+ _collect_candidate_context_row,
148
+ task,
149
+ providers=providers,
150
+ news_limit=news_limit,
151
+ announcement_limit=announcement_limit,
152
+ cache_dir=cache_dir,
153
+ cache_ttl_hours=cache_ttl_hours,
154
+ source_weights=source_weights,
155
+ ): index
156
+ for index, task in enumerate(tasks)
157
+ }
158
+ for future in as_completed(future_to_index):
159
+ index = future_to_index[future]
160
+ try:
161
+ results[index] = future.result()
162
+ except Exception as exc:
163
+ results[index] = (None, [f"{tasks[index]['code']} context: {exc}"])
164
+
165
+ rows: list[dict[str, object]] = []
166
+ errors: list[str] = []
167
+ for result in results:
168
+ if result is None:
169
+ continue
170
+ row, row_errors = result
171
+ errors.extend(row_errors)
172
+ if row is not None:
173
+ rows.append(row)
174
+ return rows, errors
175
+
176
+
177
+ def _collect_candidate_context_row(
178
+ candidate: dict[str, str],
179
+ *,
180
+ providers: list[str],
181
+ news_limit: int,
182
+ announcement_limit: int,
183
+ cache_dir: str | Path | None,
184
+ cache_ttl_hours: int,
185
+ source_weights: dict[str, float] | None,
186
+ ) -> tuple[dict[str, object] | None, list[str]]:
187
+ code = candidate["code"]
188
+ errors: list[str] = []
189
+ try:
190
+ cached = _read_cache(cache_dir, code, providers, cache_ttl_hours=cache_ttl_hours)
191
+ if cached is not None:
192
+ _ensure_context_row_enrichment(
193
+ cached,
194
+ requested_sources=providers,
195
+ source_weights=source_weights,
196
+ )
197
+ return cached, []
198
+ row: dict[str, object] = {
199
+ "code": code,
200
+ "name": candidate.get("name", ""),
201
+ }
202
+ successful_sources: list[str] = []
203
+ if "news" in providers:
204
+ try:
205
+ sig_params = inspect.signature(fetch_stock_news_summary).parameters
206
+ if "name" in sig_params:
207
+ row["news"] = fetch_stock_news_summary(code, limit=news_limit, name=candidate.get("name", ""))
208
+ else:
209
+ row["news"] = fetch_stock_news_summary(code, limit=news_limit)
210
+ if row["news"]:
211
+ successful_sources.append("news")
212
+ except Exception as exc:
213
+ errors.append(f"{code} news: {exc}")
214
+ if "announcement" in providers or "announcements" in providers:
215
+ try:
216
+ row["announcement"] = fetch_stock_announcement_summary(code, limit=announcement_limit)
217
+ if row["announcement"]:
218
+ successful_sources.append("announcement")
219
+ except Exception as exc:
220
+ errors.append(f"{code} announcement: {exc}")
221
+ if "fund_flow" in providers or "fundflow" in providers:
222
+ try:
223
+ row["fund_flow"] = fetch_stock_fund_flow_summary(code)
224
+ if row["fund_flow"]:
225
+ successful_sources.append("fund_flow")
226
+ except Exception as exc:
227
+ errors.append(f"{code} fund_flow: {exc}")
228
+ if "quote" in providers:
229
+ try:
230
+ row["quote"] = fetch_stock_quote_summary(code)
231
+ if row["quote"]:
232
+ successful_sources.append("quote")
233
+ except Exception as exc:
234
+ errors.append(f"{code} quote: {exc}")
235
+ if any(value for key, value in row.items() if key not in {"code", "name"}):
236
+ row["source_count"] = len(successful_sources)
237
+ row["source_confidence"] = _source_confidence(successful_sources, providers)
238
+ row["source_weight_score"] = _source_weight_score(
239
+ successful_sources,
240
+ providers,
241
+ source_weights=source_weights,
242
+ )
243
+ _ensure_context_row_enrichment(
244
+ row,
245
+ requested_sources=providers,
246
+ successful_sources=successful_sources,
247
+ source_weights=source_weights,
248
+ )
249
+ try:
250
+ _write_cache(cache_dir, code, providers, row)
251
+ except Exception as exc:
252
+ errors.append(f"{code} cache: {exc}")
253
+ return row, errors
254
+ return None, errors
255
+ except Exception as exc:
256
+ return None, [*errors, f"{code} context: {exc}"]
257
+
258
+
259
+ def _fetch_stock_news_search_fallback(code: str, *, limit: int = 3, name: str = "") -> str:
260
+ norm_code = str(code).zfill(6)
261
+ clean_name = str(name or "").strip()
262
+ query = f'"{clean_name}" {norm_code} 股票 最新新闻' if clean_name else f"{norm_code} 股票 最新新闻 公告"
263
+ try:
264
+ from alphasift.market_news import search_stock_news_via_web
265
+
266
+ items = search_stock_news_via_web(query, limit=max(limit * 2, 4))
267
+ except Exception: # noqa: BLE001
268
+ return ""
269
+ cur_year = datetime.now().year
270
+ stale_years = tuple(f"{y}年" for y in range(2020, cur_year))
271
+ lines: list[str] = []
272
+ for item in items:
273
+ title = str(item.get("title") or "").strip()
274
+ if not title:
275
+ continue
276
+ # Reject index/quote-page SEO boilerplate (e.g. 上证指数 000001 or stale historical snapshots)
277
+ if ("实时行情" in title and "股价" in title) or ("上证指数" in title and "银行" in clean_name):
278
+ continue
279
+ if any(sy in title for sy in stale_years):
280
+ continue
281
+ line = " ".join(x for x in (item.get("published_at"), item.get("source"), title) if x)
282
+ if line:
283
+ lines.append(line)
284
+ if len(lines) >= limit:
285
+ break
286
+ return _compress_text(" | ".join(_dedupe(lines)), max_len=520)
287
+
288
+
289
+ def fetch_stock_news_summary(code: str, *, limit: int = 3, name: str = "") -> str:
290
+ norm_code = str(code).zfill(6)
291
+ items: list[str] = []
292
+ try:
293
+ import akshare as ak
294
+
295
+ df = call_with_timeout(
296
+ ak.stock_news_em,
297
+ symbol=norm_code,
298
+ timeout_sec=4.0,
299
+ label=f"stock_news_em:{norm_code}",
300
+ )
301
+ if df is not None and not df.empty:
302
+ for _, row in df.head(max(limit, 1)).iterrows():
303
+ title = _first_value(row, ["新闻标题", "标题", "title"])
304
+ published_at = _first_value(row, ["发布时间", "时间", "date"])
305
+ source = _first_value(row, ["文章来源", "来源", "source"])
306
+ text = " ".join(item for item in [published_at, source, title] if item)
307
+ if text:
308
+ items.append(text)
309
+ except Exception: # noqa: BLE001
310
+ items = []
311
+
312
+ if not items:
313
+ fallback = _fetch_stock_news_search_fallback(norm_code, limit=limit, name=name)
314
+ if fallback:
315
+ return fallback
316
+ return ""
317
+ return _compress_text(" | ".join(_dedupe(items)), max_len=520)
318
+
319
+
320
+ def fetch_stock_announcement_summary(code: str, *, limit: int = 3) -> str:
321
+ import akshare as ak
322
+
323
+ end = datetime.now().strftime("%Y%m%d")
324
+ start = (datetime.now() - timedelta(days=45)).strftime("%Y%m%d")
325
+ df = ak.stock_zh_a_disclosure_report_cninfo(
326
+ symbol=str(code).zfill(6),
327
+ market="沪深京",
328
+ start_date=start,
329
+ end_date=end,
330
+ )
331
+ if df is None or df.empty:
332
+ return ""
333
+ dated_items: list[tuple[str, str]] = []
334
+ for _, row in df.iterrows():
335
+ title = _first_value(row, ["公告标题", "标题", "announcementTitle", "title"])
336
+ date = _first_value(row, ["公告时间", "公告日期", "date"])
337
+ if title:
338
+ dated_items.append((date, " ".join(item for item in [date, title] if item)))
339
+ # Ensure newest disclosures appear first before slicing to `limit`.
340
+ dated_items.sort(key=lambda pair: pair[0], reverse=True)
341
+ items = [text for _, text in dated_items[: max(limit, 1)]]
342
+ return _compress_text(" | ".join(_dedupe(items)), max_len=520)
343
+
344
+
345
+ def fetch_stock_fund_flow_summary(code: str) -> str:
346
+ import akshare as ak
347
+
348
+ market = _market_for_code(code)
349
+ if not market:
350
+ return ""
351
+ df = ak.stock_individual_fund_flow(stock=str(code).zfill(6), market=market)
352
+ if df is None or df.empty:
353
+ return ""
354
+ row = df.iloc[-1]
355
+ fields = []
356
+ for column in df.columns:
357
+ name = str(column)
358
+ if any(keyword in name for keyword in ["日期", "主力净流入", "超大单净流入", "大单净流入", "净占比"]):
359
+ value = _safe_text(row.get(column))
360
+ if value:
361
+ fields.append(f"{name}={value}")
362
+ return _compress_text(",".join(fields[:8]), max_len=420)
363
+
364
+
365
+ def fetch_stock_quote_summary(code: str) -> str:
366
+ """Fetch lightweight Tencent quote/fundamental context for one candidate."""
367
+ symbol = _tencent_symbol_for_code(code)
368
+ if not symbol:
369
+ return ""
370
+ resp = requests.get(
371
+ f"https://qt.gtimg.cn/q={symbol}",
372
+ headers={"User-Agent": "Mozilla/5.0"},
373
+ timeout=8,
374
+ )
375
+ resp.raise_for_status()
376
+ text = resp.text or ""
377
+ if "=\"" not in text:
378
+ return ""
379
+ body = text.split("=\"", 1)[1].split("\";", 1)[0]
380
+ parts = body.split("~")
381
+ if len(parts) < 46:
382
+ return ""
383
+ fields = [
384
+ ("名称", _part(parts, 1)),
385
+ ("现价", _part(parts, 3)),
386
+ ("涨跌幅", _part(parts, 32)),
387
+ ("最高", _part(parts, 33)),
388
+ ("最低", _part(parts, 34)),
389
+ ("成交额万元", _part(parts, 37)),
390
+ ("换手率", _part(parts, 38)),
391
+ ("市盈率", _part(parts, 39)),
392
+ ("总市值亿元", _part(parts, 45)),
393
+ ("流通市值亿元", _part(parts, 44)),
394
+ ]
395
+ return _compress_text(
396
+ ",".join(f"{name}={value}" for name, value in fields if value),
397
+ max_len=360,
398
+ )
399
+
400
+
401
+ def _classify_negative_clause(clause: str) -> list[str]:
402
+ flags: list[str] = []
403
+ if not clause:
404
+ return flags
405
+
406
+ red_text = _NEGATION_REDUCTION_RE.sub("", clause)
407
+ if any(kw in red_text for kw in _NEGATIVE_EVENT_KEYWORDS["减持"]):
408
+ flags.append("减持")
409
+
410
+ reg_text = _NEGATION_REGULATOR_RE.sub("", clause)
411
+ if any(kw in reg_text for kw in _NEGATIVE_EVENT_KEYWORDS["监管"]):
412
+ flags.append("监管")
413
+
414
+ earn_text = _NEGATION_EARNINGS_RE.sub("", clause)
415
+ if any(kw in earn_text for kw in _NEGATIVE_EVENT_KEYWORDS["业绩压力"]):
416
+ flags.append("业绩压力")
417
+
418
+ fin_text = _BENIGN_FINANCE_RE.sub("", clause)
419
+ if _ROUTINE_IMPAIRMENT_RE.search(fin_text) and not any(cue in fin_text for cue in _SEVERE_IMPAIRMENT_CUES):
420
+ fin_text = _ROUTINE_IMPAIRMENT_RE.sub("", fin_text)
421
+ if any(kw in fin_text for kw in _NEGATIVE_EVENT_KEYWORDS["财务风险"]):
422
+ flags.append("财务风险")
423
+
424
+ delist_text = _NEGATION_DELIST_RE.sub("", clause)
425
+ if any(kw in delist_text for kw in _NEGATIVE_EVENT_KEYWORDS["退市风险"]) or _ST_SYMBOL_RE.search(delist_text):
426
+ flags.append("退市风险")
427
+
428
+ lit_text = _NEGATION_LITIGATION_RE.sub("", clause)
429
+ if any(kw in lit_text for kw in _NEGATIVE_EVENT_KEYWORDS["诉讼风险"]):
430
+ flags.append("诉讼风险")
431
+
432
+ pledge_text = _NEGATION_PLEDGE_RE.sub("", clause)
433
+ if any(kw in pledge_text for kw in _NEGATIVE_EVENT_KEYWORDS["质押冻结"]):
434
+ flags.append("质押冻结")
435
+
436
+ return flags
437
+
438
+
439
+ def classify_negative_text(text: str) -> list[str]:
440
+ """Classify negative event flags across piped/punctuated clauses with negation disambiguation."""
441
+ flags: list[str] = []
442
+ for clause in _ITEM_SPLIT_RE.split(str(text or "")):
443
+ cleaned = clause.strip()
444
+ if cleaned:
445
+ flags.extend(_classify_negative_clause(cleaned))
446
+ return _dedupe(flags)
447
+
448
+
449
+ def classify_context_events(row: dict[str, object]) -> list[str]:
450
+ """Return coarse event tags from already collected candidate context."""
451
+ text = _row_text(row)
452
+ tags: list[str] = []
453
+ for label, keywords in _POSITIVE_EVENT_KEYWORDS.items():
454
+ if any(keyword in text for keyword in keywords):
455
+ tags.append(label)
456
+ for label in classify_negative_text(text):
457
+ tags.append(f"风险:{label}")
458
+ return _dedupe(tags)
459
+
460
+
461
+ def classify_negative_events(row: dict[str, object]) -> list[str]:
462
+ """Return negative event categories detected in candidate context."""
463
+ return classify_negative_text(_row_text(row))
464
+
465
+
466
+ def classify_announcement_categories(row: dict[str, object]) -> list[str]:
467
+ """Return coarse announcement categories from candidate context."""
468
+ text = " ".join(
469
+ str(row.get(key) or "")
470
+ for key in ("announcement", "announcements")
471
+ if row.get(key)
472
+ )
473
+ categories = [
474
+ label
475
+ for label, keywords in _ANNOUNCEMENT_CATEGORY_KEYWORDS.items()
476
+ if any(keyword in text for keyword in keywords)
477
+ ]
478
+ return _dedupe(categories)
479
+
480
+
481
+ def _ensure_context_row_enrichment(
482
+ row: dict[str, object],
483
+ *,
484
+ requested_sources: list[str] | None = None,
485
+ successful_sources: list[str] | None = None,
486
+ source_weights: dict[str, float] | None = None,
487
+ ) -> None:
488
+ successful_sources = successful_sources or _successful_sources_from_row(row)
489
+ requested_sources = requested_sources or successful_sources
490
+ if source_weights is not None or not isinstance(row.get("source_weight_score"), (int, float)):
491
+ row["source_weight_score"] = _source_weight_score(
492
+ successful_sources,
493
+ requested_sources,
494
+ source_weights=source_weights,
495
+ )
496
+ if not isinstance(row.get("announcement_categories"), list):
497
+ row["announcement_categories"] = classify_announcement_categories(row)
498
+ if not isinstance(row.get("event_tags"), list):
499
+ row["event_tags"] = classify_context_events(row)
500
+ if not isinstance(row.get("negative_event_flags"), list):
501
+ row["negative_event_flags"] = classify_negative_events(row)
502
+ summary = _safe_text(row.get("context_summary"), max_len=600)
503
+ needs_summary = not summary
504
+ if isinstance(row.get("event_tags"), list) and row["event_tags"] and "事件标签:" not in summary:
505
+ needs_summary = True
506
+ if (
507
+ isinstance(row.get("announcement_categories"), list)
508
+ and row["announcement_categories"]
509
+ and "公告类别:" not in summary
510
+ ):
511
+ needs_summary = True
512
+ if (
513
+ isinstance(row.get("negative_event_flags"), list)
514
+ and row["negative_event_flags"]
515
+ and "负面风险:" not in summary
516
+ ):
517
+ needs_summary = True
518
+ if needs_summary:
519
+ row["context_summary"] = _summarize_row_context(row)
520
+
521
+
522
+ def _market_for_code(code: str) -> str:
523
+ code = _normalize_code(code)
524
+ if code.startswith("6"):
525
+ return "sh"
526
+ if code.startswith(("0", "3")):
527
+ return "sz"
528
+ return ""
529
+
530
+
531
+ def _tencent_symbol_for_code(code: str) -> str:
532
+ code = _normalize_code(code)
533
+ if code.startswith(("6", "5", "9")):
534
+ return f"sh{code}"
535
+ if code.startswith(("0", "3")):
536
+ return f"sz{code}"
537
+ if code.startswith(("4", "8", "920")):
538
+ return f"bj{code}"
539
+ return ""
540
+
541
+
542
+ def _part(parts: list[str], index: int) -> str:
543
+ return _safe_text(parts[index] if index < len(parts) else "", max_len=80)
544
+
545
+
546
+ def _first_value(row: pd.Series, columns: list[str]) -> str:
547
+ for column in columns:
548
+ if column in row.index:
549
+ value = _safe_text(row.get(column))
550
+ if value:
551
+ return value
552
+ return ""
553
+
554
+
555
+ def _safe_text(value: object, *, max_len: int = 240) -> str:
556
+ if value is None:
557
+ return ""
558
+ text = str(value).strip()
559
+ if not text or text.lower() in {"nan", "none", "<na>"}:
560
+ return ""
561
+ return text[:max_len]
562
+
563
+
564
+ def _normalize_code(value: object) -> str:
565
+ text = _safe_text(value, max_len=80)
566
+ if not text:
567
+ return ""
568
+ if text.endswith(".0") and text[:-2].isdigit():
569
+ text = text[:-2]
570
+ if text.isdigit():
571
+ return text.zfill(6)[-6:]
572
+ match = re.search(r"(?<!\d)(\d{6})(?!\d)", text)
573
+ if match:
574
+ return match.group(1)
575
+ digits = "".join(ch for ch in text if ch.isdigit())
576
+ return digits.zfill(6)[-6:] if digits else ""
577
+
578
+
579
+ def _normalize_providers(providers: list[str]) -> list[str]:
580
+ aliases = {"announcements": "announcement", "fundflow": "fund_flow"}
581
+ result = []
582
+ seen = set()
583
+ for item in providers:
584
+ key = aliases.get(str(item).strip().lower(), str(item).strip().lower())
585
+ if key and key not in seen:
586
+ seen.add(key)
587
+ result.append(key)
588
+ return result
589
+
590
+
591
+ def _source_confidence(successful_sources: list[str], requested_sources: list[str]) -> float:
592
+ requested = set(requested_sources)
593
+ if not requested:
594
+ return 0.0
595
+ coverage = len(set(successful_sources)) / len(requested)
596
+ return round(min(1.0, max(0.0, coverage)), 4)
597
+
598
+
599
+ def _source_weight_score(
600
+ successful_sources: list[str],
601
+ requested_sources: list[str],
602
+ *,
603
+ source_weights: dict[str, float] | None = None,
604
+ ) -> float:
605
+ requested = _normalize_providers(requested_sources)
606
+ successful = set(_normalize_providers(successful_sources))
607
+ weights = _normalized_source_weights(source_weights)
608
+ total = sum(weights.get(source, 0.5) for source in requested)
609
+ if total <= 0:
610
+ return 0.0
611
+ score = sum(weights.get(source, 0.5) for source in successful if source in requested) / total
612
+ return round(min(1.0, max(0.0, score)), 4)
613
+
614
+
615
+ def _normalized_source_weights(source_weights: dict[str, float] | None) -> dict[str, float]:
616
+ result = dict(_SOURCE_WEIGHTS)
617
+ for key, value in (source_weights or {}).items():
618
+ normalized = _normalize_providers([str(key)])
619
+ if not normalized:
620
+ continue
621
+ try:
622
+ result[normalized[0]] = max(float(value), 0.0)
623
+ except (TypeError, ValueError):
624
+ continue
625
+ return result
626
+
627
+
628
+ def _summarize_row_context(row: dict[str, object]) -> str:
629
+ parts = []
630
+ for key, label in (
631
+ ("news", "新闻"),
632
+ ("announcement", "公告"),
633
+ ("fund_flow", "资金流"),
634
+ ("quote", "行情估值"),
635
+ ):
636
+ value = _compress_text(row.get(key), max_len=180)
637
+ if value:
638
+ parts.append(f"{label}:{value}")
639
+ event_tags = row.get("event_tags")
640
+ if isinstance(event_tags, list) and event_tags:
641
+ parts.append("事件标签:" + ",".join(str(item) for item in event_tags[:6]))
642
+ announcement_categories = row.get("announcement_categories")
643
+ if isinstance(announcement_categories, list) and announcement_categories:
644
+ parts.append("公告类别:" + ",".join(str(item) for item in announcement_categories[:6]))
645
+ negative_flags = row.get("negative_event_flags")
646
+ if isinstance(negative_flags, list) and negative_flags:
647
+ parts.append("负面风险:" + ",".join(str(item) for item in negative_flags[:6]))
648
+ return _compress_text(";".join(parts), max_len=520)
649
+
650
+
651
+ def _row_text(row: dict[str, object]) -> str:
652
+ fields = []
653
+ for key in ("news", "announcement", "announcements", "fund_flow", "quote", "summary", "context", "text"):
654
+ value = row.get(key)
655
+ if value:
656
+ fields.append(str(value))
657
+ return " ".join(fields)
658
+
659
+
660
+ def _successful_sources_from_row(row: dict[str, object]) -> list[str]:
661
+ sources = []
662
+ if row.get("news"):
663
+ sources.append("news")
664
+ if row.get("announcement") or row.get("announcements"):
665
+ sources.append("announcement")
666
+ if row.get("fund_flow") or row.get("fundflow"):
667
+ sources.append("fund_flow")
668
+ if row.get("quote"):
669
+ sources.append("quote")
670
+ return sources
671
+
672
+
673
+ def _compress_text(value: object, *, max_len: int) -> str:
674
+ text = _safe_text(value, max_len=max(max_len * 2, 240))
675
+ if not text:
676
+ return ""
677
+ text = " ".join(text.replace("\n", " ").split())
678
+ if len(text) <= max_len:
679
+ return text
680
+ cut = text[:max_len]
681
+ for delimiter in (" | ", ";", "。", ",", " "):
682
+ idx = cut.rfind(delimiter)
683
+ if idx >= max_len * 0.55:
684
+ return cut[:idx].rstrip() + "..."
685
+ return cut.rstrip() + "..."
686
+
687
+
688
+ def _cache_path(cache_dir: str | Path | None, code: str, providers: list[str]) -> Path | None:
689
+ if cache_dir is None:
690
+ return None
691
+ key = "_".join(providers) or "none"
692
+ return Path(cache_dir) / f"{str(code).zfill(6)}_{key}.json"
693
+
694
+
695
+ def _read_cache(
696
+ cache_dir: str | Path | None,
697
+ code: str,
698
+ providers: list[str],
699
+ *,
700
+ cache_ttl_hours: int,
701
+ ) -> dict[str, object] | None:
702
+ path = _cache_path(cache_dir, code, providers)
703
+ if path is None or not path.is_file() or cache_ttl_hours <= 0:
704
+ return None
705
+ try:
706
+ data = json.loads(path.read_text(encoding="utf-8"))
707
+ cached_at = datetime.fromisoformat(str(data.get("cached_at", "")))
708
+ if datetime.now() - cached_at > timedelta(hours=cache_ttl_hours):
709
+ return None
710
+ row = data.get("row")
711
+ return row if isinstance(row, dict) else None
712
+ except Exception:
713
+ return None
714
+
715
+
716
+ def _write_cache(
717
+ cache_dir: str | Path | None,
718
+ code: str,
719
+ providers: list[str],
720
+ row: dict[str, object],
721
+ ) -> None:
722
+ path = _cache_path(cache_dir, code, providers)
723
+ if path is None:
724
+ return
725
+ path.parent.mkdir(parents=True, exist_ok=True)
726
+ payload = {"cached_at": datetime.now().isoformat(), "row": row}
727
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
728
+
729
+
730
+ def _dedupe(items: list[str]) -> list[str]:
731
+ seen = set()
732
+ result = []
733
+ for item in items:
734
+ key = item.strip()
735
+ if key and key not in seen:
736
+ seen.add(key)
737
+ result.append(key)
738
+ return result