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,1115 @@
1
+ # -*- coding: utf-8 -*-
2
+ """CN daily radar report builder (`report.json`), announcement screening, and <1200-char IM card."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable, Sequence
7
+ from datetime import date, datetime, timezone
8
+ import json
9
+ from pathlib import Path
10
+ import re
11
+ from typing import Any
12
+ from zoneinfo import ZoneInfo
13
+
14
+ import pandas as pd
15
+
16
+ from alphasift.candidate_context import (
17
+ classify_announcement_categories,
18
+ classify_negative_events,
19
+ classify_negative_text,
20
+ collect_candidate_context,
21
+ )
22
+ from alphasift.config import Config
23
+ from alphasift.daily_brief import (
24
+ build_cross_strategy_synthesis,
25
+ generate_ai_daily_brief,
26
+ resolve_strategy_display_names,
27
+ )
28
+ from alphasift.market_news import fetch_cn_market_news
29
+ from alphasift.markets import get_market, latest_settled_close
30
+ from alphasift.models import ScreenResult
31
+ from alphasift.normalize import normalize_code
32
+ from alphasift.pack import DailyPack
33
+ from alphasift.patterns import PatternSpec, extract_mini_kline_bars, list_patterns, scan_patterns
34
+ from alphasift.result_schema import DAILY_REPORT_SCHEMA, DAILY_REPORT_SCHEMA_VERSION
35
+ from alphasift.source_guard import call_with_timeout
36
+ from alphasift.store import load_screen_result
37
+ from alphasift.timeutil import parse_timestamp
38
+
39
+ IM_CARD_MAX_CHARS = 1199
40
+ _ANNOUNCEMENT_TIMEOUT_SEC = 25.0
41
+ _MARKET_NEWS_TIMEOUT_SEC = 8.0
42
+ _STOCK_NEWS_TIMEOUT_SEC = 15.0
43
+ DEFAULT_DASHBOARD_URL = "https://alphasift.zhulinsen.tech/"
44
+ _FACTOR_CN_LABELS = {
45
+ "value": "估值",
46
+ "quality": "质量",
47
+ "dividend": "红利",
48
+ "momentum": "动量",
49
+ "reversal": "超跌反转",
50
+ "growth": "成长",
51
+ "low_volatility": "低波",
52
+ "volatility": "低波",
53
+ "stability": "低波稳健",
54
+ "size": "市值规模",
55
+ "activity": "活跃度",
56
+ "theme_heat": "板块热度",
57
+ "liquidity": "流动性",
58
+ "capital_flow": "资金",
59
+ "technical": "技术",
60
+ "trend": "趋势",
61
+ "sentiment": "情绪",
62
+ }
63
+ _RECENCY_RANK = {"recent": 0, "mid": 1, "unknown": 2, "old": 3}
64
+ _DATE_PREFIX_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})(?:[T\s]\d{2}:\d{2}(?::\d{2})?)?\s*")
65
+
66
+
67
+ def _collect_announcements_default(
68
+ df: pd.DataFrame,
69
+ *,
70
+ max_rows: int,
71
+ cache_dir: Path | None,
72
+ ) -> tuple[list[dict[str, object]], list[str]]:
73
+ return call_with_timeout(
74
+ collect_candidate_context,
75
+ df,
76
+ max_rows=max_rows,
77
+ providers=["announcement"],
78
+ announcement_limit=3,
79
+ cache_dir=cache_dir,
80
+ timeout_sec=_ANNOUNCEMENT_TIMEOUT_SEC,
81
+ label="announcement risk screening",
82
+ )
83
+
84
+
85
+ def _parse_announcement_match(
86
+ ann_text: str,
87
+ *,
88
+ trade_date: str | None = None,
89
+ ) -> tuple[str | None, int | None, str, str]:
90
+ """Isolate the specific triggering disclosure, its date, and recency relative to trade_date."""
91
+ items = [part.strip() for part in str(ann_text or "").split("|") if part.strip()]
92
+ matched_raw = ""
93
+ for item in items:
94
+ if classify_negative_text(item):
95
+ matched_raw = item
96
+ break
97
+ if not matched_raw and items:
98
+ matched_raw = items[0]
99
+ if not matched_raw:
100
+ return None, None, "unknown", ""
101
+
102
+ m = _DATE_PREFIX_RE.match(matched_raw)
103
+ ann_date = m.group(1) if m else None
104
+ days_ago: int | None = None
105
+ recency = "unknown"
106
+ if ann_date:
107
+ try:
108
+ ref_date = (
109
+ date.fromisoformat(str(trade_date).strip()[:10])
110
+ if trade_date and len(str(trade_date).strip()) >= 10
111
+ else datetime.now().date()
112
+ )
113
+ days_ago = max(0, (ref_date - date.fromisoformat(ann_date)).days)
114
+ if days_ago <= 7:
115
+ recency = "recent"
116
+ elif days_ago <= 21:
117
+ recency = "mid"
118
+ else:
119
+ recency = "old"
120
+ except ValueError:
121
+ days_ago = None
122
+ recency = "unknown"
123
+
124
+ cleaned = _clean_announcement_snippet(matched_raw, max_len=160)
125
+ return ann_date, days_ago, recency, cleaned
126
+
127
+
128
+ def screen_announcement_risks(
129
+ candidates: Sequence[dict[str, Any]],
130
+ *,
131
+ max_codes: int = 20,
132
+ cache_dir: Path | None = None,
133
+ collector: Callable[..., tuple[list[dict[str, object]], list[str]]] | None = None,
134
+ trade_date: str | None = None,
135
+ priority_counts: dict[str, int] | None = None,
136
+ ) -> dict[str, Any]:
137
+ """Best-effort announcement risk check over shortlisted CN candidates."""
138
+ deduped: list[dict[str, str]] = []
139
+ seen: set[str] = set()
140
+ limit = max(0, int(max_codes))
141
+ for item in candidates:
142
+ code = normalize_code(item.get("code"), allow_ticker=False)
143
+ if not code or code in seen:
144
+ continue
145
+ seen.add(code)
146
+ deduped.append({"code": code, "name": str(item.get("name") or "").strip()})
147
+ if len(deduped) >= limit:
148
+ break
149
+
150
+ if not deduped:
151
+ return {
152
+ "checked_count": 0,
153
+ "flagged_count": 0,
154
+ "by_code": {},
155
+ "flagged_items": [],
156
+ "errors": [],
157
+ }
158
+
159
+ df = pd.DataFrame(deduped)
160
+ errors: list[str] = []
161
+ rows: list[dict[str, object]] = []
162
+ try:
163
+ if collector is not None:
164
+ rows, coll_errors = collector(df, max_rows=len(deduped), cache_dir=cache_dir)
165
+ else:
166
+ rows, coll_errors = _collect_announcements_default(
167
+ df, max_rows=len(deduped), cache_dir=cache_dir
168
+ )
169
+ errors.extend(str(e) for e in (coll_errors or []))
170
+ except Exception as exc: # noqa: BLE001
171
+ errors.append(f"announcement screening skipped: {exc}")
172
+ rows = []
173
+
174
+ by_code: dict[str, dict[str, Any]] = {}
175
+ flagged_items: list[dict[str, Any]] = []
176
+ name_map = {item["code"]: item["name"] for item in deduped}
177
+ prio = priority_counts or {}
178
+
179
+ for row in rows or []:
180
+ code = normalize_code(row.get("code"), allow_ticker=False)
181
+ if not code:
182
+ continue
183
+ neg_flags = list(row.get("negative_event_flags") or classify_negative_events(row))
184
+ ann_cats = list(row.get("announcement_categories") or classify_announcement_categories(row))
185
+ ann_text = str(row.get("announcement") or row.get("announcements") or "").strip()
186
+ ann_date, days_ago, recency, matched_clean = _parse_announcement_match(
187
+ ann_text,
188
+ trade_date=trade_date,
189
+ )
190
+ info = {
191
+ "code": code,
192
+ "name": str(row.get("name") or name_map.get(code, "")),
193
+ "negative_event_flags": neg_flags,
194
+ "announcement_categories": ann_cats,
195
+ "announcement_summary": ann_text[:200],
196
+ "matched_announcement": matched_clean,
197
+ "announcement_date": ann_date,
198
+ "days_ago": days_ago,
199
+ "recency": recency,
200
+ "consensus_count": int(prio.get(code, 0)),
201
+ }
202
+ by_code[code] = info
203
+ if neg_flags:
204
+ flagged_items.append(info)
205
+
206
+ flagged_items.sort(
207
+ key=lambda x: (
208
+ _RECENCY_RANK.get(str(x.get("recency") or "unknown"), 2),
209
+ -int(x.get("consensus_count") or 0),
210
+ int(x["days_ago"]) if x.get("days_ago") is not None else 999,
211
+ str(x.get("code") or ""),
212
+ )
213
+ )
214
+
215
+ return {
216
+ "checked_count": len(deduped),
217
+ "flagged_count": len(flagged_items),
218
+ "by_code": by_code,
219
+ "flagged_items": flagged_items,
220
+ "errors": errors,
221
+ }
222
+
223
+
224
+ def _cn_run_session_date(created_at: str) -> str:
225
+ """Resolve the CN exchange session date (YYYY-MM-DD) for a run timestamp."""
226
+ parsed = parse_timestamp(created_at)
227
+ if parsed is None:
228
+ return str(created_at or "")[:10]
229
+ settled = latest_settled_close("cn", parsed)
230
+ if settled is not None:
231
+ return settled[0].isoformat()
232
+ return parsed.astimezone(ZoneInfo(get_market("cn").timezone)).date().isoformat()
233
+
234
+
235
+ def load_daily_report_runs(
236
+ config: Config,
237
+ *,
238
+ run_refs: Sequence[str] | None = None,
239
+ runs_dir: Path | None = None,
240
+ trade_date: str | None = None,
241
+ ) -> list[ScreenResult]:
242
+ """Unified run loader for CLI ``daily-report`` and HTTP ``/daily-report``."""
243
+ target_runs_dir = Path(runs_dir).expanduser() if runs_dir is not None else (config.data_dir / "runs")
244
+ loaded: list[ScreenResult] = []
245
+ seen_ids: set[str] = set()
246
+
247
+ for ref in run_refs or []:
248
+ if isinstance(ref, Path):
249
+ cand = ref
250
+ else:
251
+ direct = Path(ref)
252
+ in_runs = target_runs_dir / f"{ref}.json"
253
+ # When ref is a bare run_id (no path separators), prefer target_runs_dir over CWD.
254
+ if "/" not in str(ref) and "\\" not in str(ref) and in_runs.is_file():
255
+ cand = in_runs
256
+ else:
257
+ cand = direct if direct.is_file() else in_runs
258
+ sr = load_screen_result(cand, data_dir=config.data_dir)
259
+ key_id = sr.run_id or str(cand)
260
+ if key_id not in seen_ids:
261
+ seen_ids.add(key_id)
262
+ loaded.append(sr)
263
+
264
+ if (runs_dir is not None or not run_refs) and target_runs_dir.is_dir():
265
+ for path in sorted(target_runs_dir.glob("*.json")):
266
+ try:
267
+ sr = load_screen_result(path, data_dir=config.data_dir)
268
+ except Exception: # noqa: BLE001
269
+ continue
270
+ if (sr.market or "cn").lower() != "cn":
271
+ continue
272
+ if trade_date and sr.created_at and _cn_run_session_date(sr.created_at) != trade_date:
273
+ continue
274
+ key_id = sr.run_id or str(path)
275
+ if key_id not in seen_ids:
276
+ seen_ids.add(key_id)
277
+ loaded.append(sr)
278
+
279
+ loaded.sort(
280
+ key=lambda r: (
281
+ str(r.strategy),
282
+ 0 if (r.track or ("ai" if r.llm_ranked else "rules")) == "rules" else 1,
283
+ str(r.created_at or ""),
284
+ str(r.run_id or ""),
285
+ )
286
+ )
287
+ return loaded
288
+
289
+
290
+ def _derive_pick_reason(p: Any) -> str:
291
+ explicit = str(getattr(p, "ranking_reason", "") or "").strip()
292
+ if explicit:
293
+ return explicit[:120]
294
+ fscores = getattr(p, "factor_scores", None)
295
+ if isinstance(fscores, dict) and fscores:
296
+ ranked_f = sorted(
297
+ ((k, float(v)) for k, v in fscores.items() if v is not None),
298
+ key=lambda kv: -kv[1],
299
+ )
300
+ labels = [_FACTOR_CN_LABELS.get(k, k) for k, _ in ranked_f[:2]]
301
+ if labels:
302
+ return f"{'+'.join(labels)}因子靠前"
303
+ bits: list[str] = []
304
+ pe = getattr(p, "pe_ratio", None)
305
+ pb = getattr(p, "pb_ratio", None)
306
+ if pe is not None and float(pe) > 0:
307
+ bits.append(f"PE {float(pe):.1f}")
308
+ if pb is not None and float(pb) > 0:
309
+ bits.append(f"PB {float(pb):.2f}")
310
+ return " · ".join(bits)
311
+
312
+
313
+ def _format_strategy_entry(
314
+ run: ScreenResult,
315
+ *,
316
+ display_names: dict[str, str] | None = None,
317
+ ) -> dict[str, Any]:
318
+ track = run.track or ("ai" if run.llm_ranked else "rules")
319
+ names_map = display_names or resolve_strategy_display_names()
320
+ picks = []
321
+ for p in run.picks[:5]:
322
+ raw_price = getattr(p, "price", None)
323
+ price_val = round(float(raw_price), 2) if raw_price is not None and float(raw_price) > 0 else None
324
+ raw_pe = getattr(p, "pe_ratio", None)
325
+ pe_val = round(float(raw_pe), 1) if raw_pe is not None else None
326
+ raw_pb = getattr(p, "pb_ratio", None)
327
+ pb_val = round(float(raw_pb), 2) if raw_pb is not None else None
328
+ raw_mv = getattr(p, "total_mv", None)
329
+ mv_yi = (
330
+ round(float(raw_mv) / 1e8, 1)
331
+ if raw_mv is not None and float(raw_mv) >= 1e6
332
+ else None
333
+ )
334
+ picks.append({
335
+ "rank": int(p.rank),
336
+ "code": str(p.code),
337
+ "name": str(p.name),
338
+ "industry": str(p.industry),
339
+ "price": price_val,
340
+ "pe_ratio": pe_val,
341
+ "pb_ratio": pb_val,
342
+ "market_cap_yi": mv_yi,
343
+ "final_score": round(float(p.final_score), 2),
344
+ "screen_score": round(float(p.screen_score), 2),
345
+ "change_pct": round(float(p.change_pct), 2) if p.change_pct is not None else None,
346
+ "risk_level": str(p.risk_level),
347
+ "risk_flags": list(p.risk_flags),
348
+ "ranking_reason": _derive_pick_reason(p),
349
+ "announcement_risk_flags": [],
350
+ })
351
+ return {
352
+ "run_id": run.run_id,
353
+ "strategy": run.strategy,
354
+ "display_name": names_map.get(run.strategy, run.strategy),
355
+ "market": run.market,
356
+ "track": track,
357
+ "llm_ranked": bool(run.llm_ranked),
358
+ "llm_market_view": str(getattr(run, "llm_market_view", "") or "")[:160],
359
+ "created_at": run.created_at,
360
+ "pick_count": len(run.picks),
361
+ "degradation": list(run.degradation),
362
+ "picks": picks,
363
+ }
364
+
365
+
366
+ def _build_ai_highlights(strategy_runs: Sequence[ScreenResult]) -> list[dict[str, Any]]:
367
+ """Summarize same-strategy rules-vs-AI deltas and LLM rationale for DailyReport."""
368
+ by_strat: dict[str, dict[str, ScreenResult]] = {}
369
+ for run in strategy_runs:
370
+ tr = run.track or ("ai" if run.llm_ranked else "rules")
371
+ if tr not in {"rules", "ai"}:
372
+ continue
373
+ by_strat.setdefault(str(run.strategy), {})[tr] = run
374
+
375
+ highlights: list[dict[str, Any]] = []
376
+ for strategy in sorted(by_strat):
377
+ pair = by_strat[strategy]
378
+ ai_run = pair.get("ai")
379
+ if ai_run is None:
380
+ continue
381
+ rules_run = pair.get("rules")
382
+ ai_codes = {str(p.code) for p in ai_run.picks}
383
+ rules_codes = {str(p.code) for p in rules_run.picks} if rules_run is not None else set()
384
+ union_cnt = len(ai_codes | rules_codes)
385
+ overlap_pct = (
386
+ round((len(ai_codes & rules_codes) / union_cnt) * 100.0, 1)
387
+ if rules_run is not None and union_cnt > 0
388
+ else None
389
+ )
390
+ added = [
391
+ {
392
+ "code": str(p.code),
393
+ "name": str(p.name),
394
+ "final_score": round(float(p.final_score), 2),
395
+ "ranking_reason": str(getattr(p, "ranking_reason", "") or "")[:120],
396
+ }
397
+ for p in ai_run.picks
398
+ if rules_run is None or str(p.code) not in rules_codes
399
+ ]
400
+ dropped = (
401
+ [
402
+ {"code": str(p.code), "name": str(p.name)}
403
+ for p in rules_run.picks
404
+ if str(p.code) not in ai_codes
405
+ ]
406
+ if rules_run is not None
407
+ else []
408
+ )
409
+ highlights.append({
410
+ "strategy": strategy,
411
+ "run_id": ai_run.run_id,
412
+ "rules_pick_count": len(rules_run.picks) if rules_run is not None else 0,
413
+ "ai_pick_count": len(ai_run.picks),
414
+ "overlap_pct": overlap_pct,
415
+ "added_by_ai": added,
416
+ "dropped_by_ai": dropped,
417
+ "llm_market_view": str(getattr(ai_run, "llm_market_view", "") or "")[:200],
418
+ "llm_selection_logic": str(getattr(ai_run, "llm_selection_logic", "") or "")[:200],
419
+ "llm_portfolio_risk": str(getattr(ai_run, "llm_portfolio_risk", "") or "")[:200],
420
+ })
421
+ return highlights
422
+
423
+
424
+ def _extract_strategy_track_stats(
425
+ track_summary: dict[str, Any] | None,
426
+ ) -> dict[str, dict[str, Any]]:
427
+ if not isinstance(track_summary, dict):
428
+ return {}
429
+ out: dict[str, dict[str, Any]] = {}
430
+ for row in track_summary.get("scorecard") or []:
431
+ if not isinstance(row, dict) or str(row.get("market") or "").lower() != "cn":
432
+ continue
433
+ strat = str(row.get("strategy") or "").strip()
434
+ if not strat:
435
+ continue
436
+ track_name = str(row.get("track") or "rules")
437
+ w5 = ((row.get("windows") or {}).get("5") or {}) if isinstance(row.get("windows"), dict) else {}
438
+ matched = int(w5.get("matched") or 0)
439
+ ex = w5.get("average_excess_return_pct")
440
+ beat = w5.get("beat_rate")
441
+ if matched <= 0 and ex is None:
442
+ continue
443
+ # Prefer rules baseline row unless only ai track exists for that strategy
444
+ if strat in out and track_name != "rules":
445
+ continue
446
+ out[strat] = {
447
+ "track": track_name,
448
+ "t5_matched": matched,
449
+ "t5_avg_excess_pct": round(float(ex), 2) if ex is not None else None,
450
+ "t5_beat_rate_pct": round(float(beat) * 100.0, 1) if beat is not None else None,
451
+ }
452
+ return out
453
+
454
+
455
+ def _extract_pattern_replay_map(
456
+ pattern_replay: dict[str, Any] | None,
457
+ ) -> dict[str, dict[str, Any]]:
458
+ if not isinstance(pattern_replay, dict):
459
+ return {}
460
+ replay_obj = pattern_replay.get("replay") if isinstance(pattern_replay.get("replay"), dict) else pattern_replay
461
+ if not isinstance(replay_obj, dict):
462
+ return {}
463
+ items = replay_obj.get("patterns")
464
+ if isinstance(items, dict):
465
+ iter_items = [{"pattern": k, **(v if isinstance(v, dict) else {})} for k, v in items.items()]
466
+ elif isinstance(items, list):
467
+ iter_items = [x for x in items if isinstance(x, dict)]
468
+ else:
469
+ return {}
470
+ cost_pct = float(replay_obj.get("cost_bps") or 0.0) / 100.0
471
+ out: dict[str, dict[str, Any]] = {}
472
+ for p in iter_items:
473
+ pname = str(p.get("pattern") or "").strip()
474
+ if not pname:
475
+ continue
476
+ h5 = ((p.get("horizons") or {}).get("t5") or {}) if isinstance(p.get("horizons"), dict) else {}
477
+ grad = p.get("graduation") if isinstance(p.get("graduation"), dict) else {}
478
+ net_val = grad.get("t5_net_excess_mean_pct")
479
+ if net_val is None:
480
+ net_val = h5.get("net_excess_mean_pct")
481
+ if net_val is None:
482
+ gross_val = h5.get("gross_excess_mean_pct")
483
+ if gross_val is None:
484
+ gross_val = h5.get("excess_mean_pct")
485
+ if gross_val is not None:
486
+ net_val = float(gross_val) - cost_pct
487
+ win_val = h5.get("excess_win_rate_pct")
488
+ if win_val is None:
489
+ win_val = h5.get("win_rate_pct")
490
+ samples = h5.get("excess_scored")
491
+ if samples is None:
492
+ samples = h5.get("scored")
493
+ out[pname] = {
494
+ "replay_t5_net_excess_pct": round(float(net_val), 2) if net_val is not None else None,
495
+ "replay_t5_win_rate_pct": round(float(win_val), 1) if win_val is not None else None,
496
+ "replay_samples": int(samples) if samples is not None else None,
497
+ }
498
+ return out
499
+
500
+
501
+ def _collect_candidate_stock_news(
502
+ df: pd.DataFrame,
503
+ *,
504
+ cache_dir: Path | None,
505
+ ) -> tuple[list[dict[str, object]], list[str]]:
506
+ return call_with_timeout(
507
+ collect_candidate_context,
508
+ df,
509
+ max_rows=len(df),
510
+ providers=["news"],
511
+ news_limit=2,
512
+ cache_dir=cache_dir,
513
+ timeout_sec=_STOCK_NEWS_TIMEOUT_SEC,
514
+ label="candidate stock news",
515
+ )
516
+
517
+
518
+ def _parse_piped_stock_news(raw_text: str) -> list[dict[str, str]]:
519
+ out: list[dict[str, str]] = []
520
+ for chunk in str(raw_text or "").split("|"):
521
+ cleaned = " ".join(chunk.split()).strip()
522
+ if not cleaned:
523
+ continue
524
+ m = _DATE_PREFIX_RE.match(cleaned)
525
+ pub = m.group(1)[5:] if m else ""
526
+ title = _DATE_PREFIX_RE.sub("", cleaned, count=1).strip()
527
+ out.append({"title": title[:110], "published_at": pub})
528
+ return out[:2]
529
+
530
+
531
+ def build_daily_report(
532
+ daily_pack: DailyPack,
533
+ *,
534
+ trade_date: str | None = None,
535
+ expected_trade_date: str | None = None,
536
+ allow_stale_pack: bool = True,
537
+ detail_url: str | None = None,
538
+ strategy_runs: Sequence[ScreenResult] | None = None,
539
+ include_experimental_patterns: bool = True,
540
+ include_announcements: bool = True,
541
+ announcement_max_codes: int = 20,
542
+ announcement_cache_dir: Path | None = None,
543
+ announcement_collector: Callable[..., tuple[list[dict[str, object]], list[str]]] | None = None,
544
+ include_news: bool = False,
545
+ news_max_items: int = 6,
546
+ news_cache_dir: Path | None = None,
547
+ market_news_collector: Callable[..., tuple[list[dict[str, Any]], list[str], list[str]]] | None = None,
548
+ stock_news_collector: Callable[..., tuple[list[dict[str, object]], list[str]]] | None = None,
549
+ patterns_dir: Path | None = None,
550
+ max_card_chars: int = 1150,
551
+ max_signals_per_pattern: int = 10,
552
+ ai_brief_mode: str = "off",
553
+ config: Config | None = None,
554
+ track_comparison: Sequence[dict[str, Any]] | None = None,
555
+ track_summary: dict[str, Any] | None = None,
556
+ pattern_replay: dict[str, Any] | None = None,
557
+ warn_if_no_runs: bool = False,
558
+ llm_caller: Callable[..., str] | None = None,
559
+ ) -> dict[str, Any]:
560
+ """Build machine-readable CN ``DailyReport`` payload and <1200 char IM card."""
561
+ scan = scan_patterns(
562
+ daily_pack,
563
+ trade_date=trade_date,
564
+ include_experimental=include_experimental_patterns,
565
+ patterns_dir=patterns_dir,
566
+ )
567
+ expected = (expected_trade_date or "").strip() or None
568
+ pack_is_stale = bool(expected and str(scan.pack_trade_date) < expected)
569
+ stale_reason = (
570
+ f"pack_trade_date={scan.pack_trade_date} < expected_trade_date={expected}"
571
+ if pack_is_stale
572
+ else None
573
+ )
574
+ if pack_is_stale and not allow_stale_pack:
575
+ raise ValueError(
576
+ f"CN DailyPack is stale ({stale_reason}); pass allow_stale_pack=True for degraded display"
577
+ )
578
+ specs_by_name: dict[str, PatternSpec] = {
579
+ spec.name: spec
580
+ for spec in list_patterns(include_experimental=True, patterns_dir=patterns_dir)
581
+ }
582
+ replay_map = _extract_pattern_replay_map(pattern_replay)
583
+ summary_names = (
584
+ track_summary.get("strategy_names")
585
+ if isinstance(track_summary, dict) and isinstance(track_summary.get("strategy_names"), dict)
586
+ else None
587
+ )
588
+ display_names = resolve_strategy_display_names(
589
+ config.strategies_dir if config is not None else None,
590
+ overrides=summary_names,
591
+ )
592
+ track_stats = _extract_strategy_track_stats(track_summary)
593
+ effective_track_cmp = (
594
+ track_comparison
595
+ if track_comparison is not None
596
+ else (track_summary.get("track_comparison") if isinstance(track_summary, dict) else None)
597
+ )
598
+
599
+ active_patterns: list[dict[str, Any]] = []
600
+ experimental_patterns: list[dict[str, Any]] = []
601
+ for pat_name in scan.patterns_evaluated:
602
+ spec = specs_by_name.get(pat_name)
603
+ status = spec.status if spec is not None else "experimental"
604
+ display_name = spec.display_name if spec is not None else pat_name
605
+ family = spec.family if spec is not None else "unknown"
606
+ mode = spec.mode if spec is not None else "direct"
607
+ hits = scan.signals_by_pattern.get(pat_name, [])
608
+ rep_stats = replay_map.get(pat_name) or {}
609
+ net_ex = rep_stats.get("replay_t5_net_excess_pct")
610
+ if status == "active":
611
+ exp_tier = "active"
612
+ elif net_ex is not None:
613
+ exp_tier = "positive_watch" if float(net_ex) >= 0 else "negative_watch"
614
+ else:
615
+ exp_tier = "unrated"
616
+ entry: dict[str, Any] = {
617
+ "pattern": pat_name,
618
+ "display_name": display_name,
619
+ "family": family,
620
+ "mode": mode,
621
+ "status": status,
622
+ "expectancy_tier": exp_tier,
623
+ "aligned_strategy": spec.aligned_strategy if spec is not None else None,
624
+ "hit_count": len(hits),
625
+ "signals": [sig.to_dict() for sig in hits[: max(1, int(max_signals_per_pattern))]],
626
+ }
627
+ if rep_stats:
628
+ entry.update(rep_stats)
629
+ if status == "active":
630
+ active_patterns.append(entry)
631
+ else:
632
+ experimental_patterns.append(entry)
633
+
634
+ strategy_entries = [_format_strategy_entry(run, display_names=display_names) for run in (strategy_runs or [])]
635
+ ai_highlights = _build_ai_highlights(strategy_runs or [])
636
+
637
+ # Consensus-first candidate prioritization for announcement checks & stock news:
638
+ # 1) Multi-strategy consensus >= 2, 2) AI-added picks, 3) Round-robin picks rank 1..5 across all strategies,
639
+ # 4) Active patterns -> positive/unrated experimental patterns -> remaining patterns.
640
+ code_strats: dict[str, set[str]] = {}
641
+ code_scores: dict[str, list[float]] = {}
642
+ code_names: dict[str, str] = {}
643
+ for st in strategy_entries:
644
+ sname = str(st.get("strategy") or "")
645
+ for pk in st["picks"]:
646
+ norm_c = normalize_code(pk["code"], allow_ticker=False)
647
+ if not norm_c:
648
+ continue
649
+ code_strats.setdefault(norm_c, set()).add(sname)
650
+ if pk.get("final_score") is not None:
651
+ code_scores.setdefault(norm_c, []).append(float(pk["final_score"]))
652
+ if not code_names.get(norm_c) and pk.get("name"):
653
+ code_names[norm_c] = str(pk["name"]).strip()
654
+ priority_counts = {c: len(s) for c, s in code_strats.items()}
655
+ consensus_codes = sorted(
656
+ (c for c, cnt in priority_counts.items() if cnt >= 2),
657
+ key=lambda c: (
658
+ -priority_counts[c],
659
+ -(sum(code_scores[c]) / len(code_scores[c]) if code_scores.get(c) else 0.0),
660
+ c,
661
+ ),
662
+ )
663
+
664
+ ann_candidates: list[dict[str, str]] = [
665
+ {"code": c, "name": code_names.get(c, "")} for c in consensus_codes
666
+ ]
667
+ for hl in ai_highlights:
668
+ for item in hl.get("added_by_ai") or []:
669
+ c = normalize_code(item.get("code"), allow_ticker=False)
670
+ if c:
671
+ ann_candidates.append({"code": c, "name": str(item.get("name") or "")})
672
+ max_picks_len = max((len(st["picks"]) for st in strategy_entries), default=0)
673
+ for rank_idx in range(max_picks_len):
674
+ for st in strategy_entries:
675
+ if rank_idx < len(st["picks"]):
676
+ pk = st["picks"][rank_idx]
677
+ ann_candidates.append({"code": pk["code"], "name": pk["name"]})
678
+ for pat in active_patterns:
679
+ for sig in pat["signals"][:5]:
680
+ ann_candidates.append({"code": sig["code"], "name": sig["name"]})
681
+ ordered_exp = sorted(
682
+ experimental_patterns,
683
+ key=lambda p: 0 if p.get("expectancy_tier") != "negative_watch" else 1,
684
+ )
685
+ for pat in ordered_exp:
686
+ for sig in pat["signals"][:3]:
687
+ ann_candidates.append({"code": sig["code"], "name": sig["name"]})
688
+
689
+ degradation: list[str] = []
690
+ if warn_if_no_runs and not strategy_entries:
691
+ degradation.append(f"No CN strategy runs matched trade_date={scan.trade_date}")
692
+
693
+ if include_announcements:
694
+ ann_risks = screen_announcement_risks(
695
+ ann_candidates,
696
+ max_codes=announcement_max_codes,
697
+ cache_dir=announcement_cache_dir,
698
+ collector=announcement_collector,
699
+ trade_date=scan.trade_date,
700
+ priority_counts=priority_counts,
701
+ )
702
+ for err in ann_risks["errors"]:
703
+ degradation.append(f"Announcement screening: {err}")
704
+ else:
705
+ ann_risks = {
706
+ "checked_count": 0,
707
+ "flagged_count": 0,
708
+ "by_code": {},
709
+ "flagged_items": [],
710
+ "errors": [],
711
+ }
712
+
713
+ market_news_section: dict[str, Any] = {
714
+ "items": [],
715
+ "sources": [],
716
+ "candidate_news": {},
717
+ "errors": [],
718
+ }
719
+ if include_news:
720
+ try:
721
+ if market_news_collector is not None:
722
+ m_items, m_sources, m_errs = market_news_collector(
723
+ limit=news_max_items,
724
+ trade_date=scan.trade_date,
725
+ cache_dir=news_cache_dir or announcement_cache_dir,
726
+ )
727
+ else:
728
+ m_items, m_sources, m_errs = call_with_timeout(
729
+ fetch_cn_market_news,
730
+ limit=news_max_items,
731
+ trade_date=scan.trade_date,
732
+ cache_dir=news_cache_dir or announcement_cache_dir,
733
+ tavily_keys=config.tavily_api_keys if config is not None else None,
734
+ serpapi_keys=config.serpapi_api_keys if config is not None else None,
735
+ timeout_sec=_MARKET_NEWS_TIMEOUT_SEC,
736
+ label="cn market news",
737
+ )
738
+ market_news_section["items"] = list(m_items or [])
739
+ market_news_section["sources"] = list(m_sources or [])
740
+ market_news_section["errors"].extend(str(e) for e in (m_errs or []))
741
+ except Exception as exc: # noqa: BLE001
742
+ market_news_section["errors"].append(f"market news skipped: {exc}")
743
+
744
+ # Fetch catalyst news only for top 5 priority candidates (consensus first, then top strategy picks).
745
+ news_focus: list[dict[str, str]] = []
746
+ news_seen: set[str] = set()
747
+ for item in ann_candidates:
748
+ c = normalize_code(item.get("code"), allow_ticker=False)
749
+ if not c or c in news_seen:
750
+ continue
751
+ news_seen.add(c)
752
+ news_focus.append({"code": c, "name": str(item.get("name") or "")})
753
+ if len(news_focus) >= 5:
754
+ break
755
+ if news_focus:
756
+ try:
757
+ news_df = pd.DataFrame(news_focus)
758
+ if stock_news_collector is not None:
759
+ s_rows, s_errs = stock_news_collector(
760
+ news_df,
761
+ max_rows=len(news_focus),
762
+ cache_dir=announcement_cache_dir,
763
+ )
764
+ else:
765
+ s_rows, s_errs = _collect_candidate_stock_news(
766
+ news_df,
767
+ cache_dir=announcement_cache_dir,
768
+ )
769
+ for row in s_rows or []:
770
+ rc = normalize_code(row.get("code"), allow_ticker=False)
771
+ raw_n = str(row.get("news") or "").strip()
772
+ if rc and raw_n:
773
+ parsed_n = _parse_piped_stock_news(raw_n)
774
+ if parsed_n:
775
+ market_news_section["candidate_news"][rc] = parsed_n
776
+ for e in s_errs or []:
777
+ market_news_section["errors"].append(str(e))
778
+ except Exception as exc: # noqa: BLE001
779
+ market_news_section["errors"].append(f"candidate news skipped: {exc}")
780
+
781
+ if market_news_section["errors"] and not market_news_section["items"] and not market_news_section["candidate_news"]:
782
+ degradation.append(f"News enrichment: {market_news_section['errors'][0]}")
783
+
784
+ sig_codes: list[str] = []
785
+ seen_sig_codes: set[str] = set()
786
+ for group in (active_patterns, experimental_patterns):
787
+ for pat in group:
788
+ for sig in pat["signals"]:
789
+ c = str(sig.get("code") or "")
790
+ if c and c not in seen_sig_codes:
791
+ seen_sig_codes.add(c)
792
+ sig_codes.append(c)
793
+ kline_map = (
794
+ extract_mini_kline_bars(daily_pack, sig_codes, trade_date=scan.trade_date, bars=20)
795
+ if sig_codes
796
+ else {}
797
+ )
798
+
799
+ risk_map = ann_risks["by_code"]
800
+ for st in strategy_entries:
801
+ for pk in st["picks"]:
802
+ pk["announcement_risk_flags"] = list((risk_map.get(pk["code"]) or {}).get("negative_event_flags") or [])
803
+ for group in (active_patterns, experimental_patterns):
804
+ for pat in group:
805
+ for sig in pat["signals"]:
806
+ sig["announcement_risk_flags"] = list(
807
+ (risk_map.get(sig["code"]) or {}).get("negative_event_flags") or []
808
+ )
809
+ sig["kline"] = kline_map.get(str(sig.get("code") or ""), [])
810
+
811
+ if pack_is_stale and stale_reason:
812
+ degradation.append(f"Stale pack: {stale_reason}")
813
+ resolved_detail_url = (
814
+ DEFAULT_DASHBOARD_URL if detail_url is None else str(detail_url).strip()
815
+ )
816
+
817
+ report: dict[str, Any] = {
818
+ "schema_version": DAILY_REPORT_SCHEMA_VERSION,
819
+ "object": "DailyReport",
820
+ "trade_date": scan.trade_date,
821
+ "pack_trade_date": scan.pack_trade_date,
822
+ "expected_trade_date": expected,
823
+ "pack_is_stale": pack_is_stale,
824
+ "stale_reason": stale_reason,
825
+ "detail_url": resolved_detail_url,
826
+ "market": "cn",
827
+ "generated_at": datetime.now(timezone.utc).isoformat(),
828
+ "usage_policy": "cn_only_regime_slice_only",
829
+ "strategy_display_names": display_names,
830
+ "strategy_track_stats": track_stats,
831
+ "market_regime": scan.market_regime.to_dict(),
832
+ "strategies": strategy_entries,
833
+ "ai_highlights": ai_highlights,
834
+ "patterns": {
835
+ "active": active_patterns,
836
+ "experimental": experimental_patterns,
837
+ },
838
+ "announcement_risks": ann_risks,
839
+ "market_news": market_news_section,
840
+ "degradation": degradation,
841
+ "non_goals": list(DAILY_REPORT_SCHEMA["non_goals"]),
842
+ }
843
+
844
+ report["cross_strategy_synthesis"] = build_cross_strategy_synthesis(
845
+ report,
846
+ strategy_names=display_names,
847
+ )
848
+ report["ai_brief"] = generate_ai_daily_brief(
849
+ report,
850
+ config=config,
851
+ track_comparison=effective_track_cmp,
852
+ use_llm=ai_brief_mode,
853
+ llm_caller=llm_caller,
854
+ )
855
+ fb_reason = str((report["ai_brief"] or {}).get("fallback_reason") or "")
856
+ if ai_brief_mode in {"auto", "on"} and fb_reason.startswith("llm_error:"):
857
+ report["degradation"].append(f"AI brief fallback: {fb_reason}")
858
+
859
+ card = render_daily_im_card(report, max_chars=min(int(max_card_chars), IM_CARD_MAX_CHARS))
860
+ report["im_card_markdown"] = card
861
+ report["im_card_chars"] = len(card)
862
+ return report
863
+
864
+
865
+ def ensure_im_card_length(text: str, *, max_chars: int = IM_CARD_MAX_CHARS) -> str:
866
+ """Guarantee IM card fits strictly within ``max_chars`` (<= 1199), preserving alerts & links."""
867
+ limit = min(max(80, int(max_chars)), IM_CARD_MAX_CHARS)
868
+ cleaned = text.strip()
869
+ if len(cleaned) <= limit:
870
+ return cleaned
871
+ footer = "注:量化形态观测与回测基准,非投资建议。"
872
+ lines = [line for line in cleaned.splitlines() if line.strip() != footer]
873
+
874
+ head: list[str] = []
875
+ alerts: list[str] = []
876
+ links: list[str] = []
877
+ middle: list[str] = []
878
+
879
+ in_alerts = False
880
+ for idx, line in enumerate(lines):
881
+ if line.startswith("🔗") or ("http://" in line or "https://" in line):
882
+ in_alerts = False
883
+ links.append(line)
884
+ elif "公告预警" in line or "公告排雷" in line:
885
+ in_alerts = True
886
+ alerts.append(line)
887
+ elif in_alerts and line.startswith("- "):
888
+ alerts.append(line)
889
+ else:
890
+ in_alerts = False
891
+ if idx == 0 or (len(head) < 3 and ("旧包降级" in line or line.startswith("> "))):
892
+ head.append(line)
893
+ else:
894
+ middle.append(line)
895
+
896
+ essential: list[str] = [*head, *alerts]
897
+ tail_links: list[str] = [*links, footer]
898
+
899
+ reserved_tail = "\n".join(tail_links)
900
+ max_body = max(20, limit - len(reserved_tail) - 1)
901
+
902
+ kept_essential: list[str] = []
903
+ used = 0
904
+ for line in essential:
905
+ add_len = len(line) + (1 if kept_essential else 0)
906
+ if used + add_len <= max_body:
907
+ kept_essential.append(line)
908
+ used += add_len
909
+ elif not kept_essential:
910
+ kept_essential.append(line[: max(10, max_body - 3)] + "...")
911
+ used = len(kept_essential[0])
912
+ break
913
+
914
+ kept_middle: list[str] = []
915
+ for line in middle:
916
+ add_len = len(line) + (1 if (kept_essential or kept_middle) else 0)
917
+ if used + add_len <= max_body - 4:
918
+ kept_middle.append(line)
919
+ used += add_len
920
+ else:
921
+ break
922
+
923
+ assembled = [*kept_essential, *kept_middle]
924
+ if len(kept_middle) < len(middle):
925
+ ellipsis_len = 4 if assembled else 3
926
+ if used + ellipsis_len <= max_body:
927
+ assembled.append("...")
928
+
929
+ result = "\n".join([*assembled, *tail_links])
930
+ if len(result) > limit:
931
+ result = result[: limit - 3] + "..."
932
+ return result
933
+
934
+
935
+ _LEADING_TS_RE = re.compile(r"(?:^|(\|\s*))\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}(?::\d{2})?)?\s*")
936
+
937
+
938
+ def _clean_announcement_snippet(text: object, *, max_len: int = 44) -> str:
939
+ cleaned = re.sub(r"\s+", " ", str(text or "")).strip()
940
+ cleaned = _LEADING_TS_RE.sub(lambda m: " · " if m.group(1) else "", cleaned).strip(" ::-—·")
941
+ cleaned = re.sub(r"\s*\|\s*", " · ", cleaned)
942
+ if max_len > 0 and len(cleaned) > max_len:
943
+ return cleaned[: max(1, max_len - 1)].rstrip() + "…"
944
+ return cleaned
945
+
946
+
947
+ def render_daily_im_card(
948
+ report: dict[str, Any],
949
+ *,
950
+ max_chars: int = 1150,
951
+ ) -> str:
952
+ """Render alert-first concise <1200-char Markdown card directing details to the dashboard."""
953
+ reg = report.get("market_regime") or {}
954
+ seal = reg.get("seal_rate_pct")
955
+ seal_str = "-" if seal is None else f"{float(seal):.1f}%"
956
+ prev_ret = reg.get("prev_limit_up_avg_return_pct")
957
+ prev_str = "-" if prev_ret is None else f"{float(prev_ret):+.2f}%"
958
+ amt = reg.get("total_amount_yi")
959
+ amt_str = "-" if amt is None else f"{float(amt):,.0f}亿"
960
+ med = reg.get("median_return_pct")
961
+ med_part = "" if med is None else f" · 中位 {float(med):+.2f}%"
962
+
963
+ lines = [f"**AlphaSift A股盘后观察 ({report.get('trade_date', '-')})**"]
964
+ if report.get("pack_is_stale"):
965
+ lines.append(
966
+ f"> ⚠️ **旧包降级**:数据包日期 {report.get('pack_trade_date', '-')} 落后于目标交易日 "
967
+ f"{report.get('expected_trade_date', '-')},仅供参考"
968
+ )
969
+ lines.append(
970
+ f"> 盘面 **{reg.get('regime_stage_label', '-')}**|"
971
+ f"上涨 {float(reg.get('advance_ratio_pct', 0.0)):.1f}%{med_part}|"
972
+ f"涨跌停 {reg.get('non_st_limit_up_count', 0)}/{reg.get('non_st_limit_down_count', 0)}(封板 {seal_str})|"
973
+ f"最高 {reg.get('max_consecutive_limit_up', 0)}板 · 昨涨停 {prev_str} · 成交 {amt_str}"
974
+ )
975
+
976
+ # Alert-first block: announcement risks BEFORE strategies and patterns, with reserved budget.
977
+ ann = report.get("announcement_risks") or {}
978
+ flagged = ann.get("flagged_items") or []
979
+ checked = int(ann.get("checked_count") or 0)
980
+ if flagged:
981
+ lines.append(f"**⚠️ 公告排雷预警({checked}检/{len(flagged)}中)**")
982
+ bullet_budget = 340
983
+ used_ann = 0
984
+ shown = 0
985
+ for item in flagged[:5]:
986
+ flags = "/".join(str(x) for x in (item.get("negative_event_flags") or [])[:2])
987
+ date_tag = f"{str(item.get('announcement_date'))[5:]}·" if item.get("announcement_date") else ""
988
+ rec_tag = "旧·" if item.get("recency") == "old" else ""
989
+ bullet = f"- {item.get('code', '')} {str(item.get('name', ''))[:8]} [{date_tag}{rec_tag}{flags}]"
990
+ raw_ann = item.get("matched_announcement") or item.get("announcement_summary")
991
+ snip = _clean_announcement_snippet(raw_ann, max_len=34)
992
+ if snip and len(bullet) + len(snip) + 2 <= 82:
993
+ bullet += f": {snip}"
994
+ if shown > 0 and used_ann + len(bullet) + 1 > bullet_budget:
995
+ break
996
+ lines.append(bullet)
997
+ used_ann += len(bullet) + 1
998
+ shown += 1
999
+ if len(flagged) > shown:
1000
+ lines.append(f"- …其余 {len(flagged) - shown} 条高风险见网页详情")
1001
+ elif checked > 0 and ann.get("errors"):
1002
+ lines.append(f"**⚠️ 公告排雷**:抽检 {checked} 只(降级:{str(ann['errors'][0])[:40]})")
1003
+ elif checked > 0:
1004
+ lines.append(f"**✅ 公告排雷**:抽检 {checked} 只暂未见减持/立案/监管等负面关键词")
1005
+ else:
1006
+ lines.append("**ℹ️ 公告排雷**:未抽检或无候选")
1007
+
1008
+ # Compact strategy & AI overview (NO candidate stock lists on IM card).
1009
+ strategies = report.get("strategies") or []
1010
+ rules_runs = [s for s in strategies if not (s.get("track") == "ai" or s.get("llm_ranked"))]
1011
+ ai_runs = [s for s in strategies if (s.get("track") == "ai" or s.get("llm_ranked"))]
1012
+ rules_picks = sum(
1013
+ int(s["pick_count"]) if s.get("pick_count") is not None else len(s.get("picks") or [])
1014
+ for s in rules_runs
1015
+ )
1016
+ ai_picks = sum(
1017
+ int(s["pick_count"]) if s.get("pick_count") is not None else len(s.get("picks") or [])
1018
+ for s in ai_runs
1019
+ )
1020
+ ai_hl = report.get("ai_highlights") or []
1021
+ if ai_runs:
1022
+ added_n = sum(len(h.get("added_by_ai") or []) for h in ai_hl if isinstance(h, dict))
1023
+ dropped_n = sum(len(h.get("dropped_by_ai") or []) for h in ai_hl if isinstance(h, dict))
1024
+ delta_part = f",AI调仓 +{added_n}/-{dropped_n}" if ai_hl else ""
1025
+ views = [
1026
+ str(h.get("llm_market_view") or "").replace("\n", " ").strip()
1027
+ for h in ai_hl
1028
+ if isinstance(h, dict) and h.get("llm_market_view")
1029
+ ]
1030
+ view_part = f"({views[0][:42]})" if views else ""
1031
+ lines.append(
1032
+ f"**策略与 [AI]**:规则 {len(rules_runs)} 组({rules_picks}只) / "
1033
+ f"[AI] {len(ai_runs)} 组({ai_picks}只){delta_part}{view_part}"
1034
+ )
1035
+ elif rules_runs:
1036
+ lines.append(f"**策略概览**:规则 {len(rules_runs)} 组共 {rules_picks} 只候选")
1037
+ else:
1038
+ lines.append("**策略概览**:当日未附带 CN 策略选股(仅输出盘面与形态雷达)")
1039
+
1040
+ syn = report.get("cross_strategy_synthesis") or {}
1041
+ consensus = syn.get("consensus_picks") or []
1042
+ if consensus:
1043
+ top_c = "、".join(
1044
+ f"{c['code']} {str(c.get('name') or '')[:6]}({c['strategy_count']}策略)"
1045
+ for c in consensus[:4]
1046
+ )
1047
+ lines.append(f"**多策略共识({len(consensus)})**:{top_c}")
1048
+ brief = report.get("ai_brief") or {}
1049
+ if brief.get("mode") == "llm" and brief.get("headline"):
1050
+ lines.append(f"**[AI] 简评**:{str(brief['headline'])[:72]}")
1051
+ elif brief.get("headline"):
1052
+ lines.append(f"**盘后摘要**:{str(brief['headline'])[:72]}")
1053
+
1054
+ # Compact pattern radar summary: positive/active expectations first; collapse negative-expectancy patterns.
1055
+ pat_sec = report.get("patterns") or {}
1056
+ active = pat_sec.get("active") or []
1057
+ experimental = pat_sec.get("experimental") or []
1058
+ active_hits = sum(int(p.get("hit_count") or 0) for p in active)
1059
+ exp_hits = sum(int(p.get("hit_count") or 0) for p in experimental)
1060
+ top_hit_pats = [
1061
+ p for p in (*active, *experimental)
1062
+ if int(p.get("hit_count") or 0) > 0
1063
+ ]
1064
+ top_hit_pats.sort(
1065
+ key=lambda p: (
1066
+ 0 if p.get("status") == "active" else (1 if p.get("expectancy_tier") != "negative_watch" else 2),
1067
+ -int(p.get("hit_count") or 0),
1068
+ )
1069
+ )
1070
+ preferred_pats = [p for p in top_hit_pats if p.get("expectancy_tier") != "negative_watch"] or top_hit_pats
1071
+ if preferred_pats:
1072
+ pat_parts = []
1073
+ for p in preferred_pats[:3]:
1074
+ dname = str(p.get("display_name") or p.get("pattern") or "")
1075
+ sigs = "、".join(str(s.get("name") or s.get("code") or "")[:6] for s in (p.get("signals") or [])[:2])
1076
+ tag = "" if p.get("status") == "active" else "·观察期"
1077
+ sig_txt = f":{sigs}" if sigs else ""
1078
+ pat_parts.append(f"{dname}({int(p.get('hit_count') or 0)}只{tag}{sig_txt})")
1079
+ lines.append("**形态雷达**:" + ";".join(pat_parts))
1080
+ else:
1081
+ lines.append(
1082
+ f"**形态雷达**:active {len(active)} 组({active_hits}只) / "
1083
+ f"观察期 {len(experimental)} 组({exp_hits}只)"
1084
+ )
1085
+
1086
+ mnews_items = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1087
+ if mnews_items:
1088
+ top_title = str(mnews_items[0].get("title") or "").strip()[:48]
1089
+ if top_title:
1090
+ lines.append(f"**盘后要闻**:{top_title}")
1091
+
1092
+ detail_url = (
1093
+ DEFAULT_DASHBOARD_URL
1094
+ if report.get("detail_url") is None
1095
+ else str(report.get("detail_url") or "").strip()
1096
+ )
1097
+ if detail_url:
1098
+ lines.append(f"🔗 完整候选、AI归因与K线详情:{detail_url}")
1099
+
1100
+ lines.append("注:量化形态观测与回测基准,非投资建议。")
1101
+ return ensure_im_card_length("\n".join(lines), max_chars=max_chars)
1102
+
1103
+
1104
+ def write_daily_report(path: str | Path, report: dict[str, Any]) -> Path:
1105
+ output = Path(path)
1106
+ output.parent.mkdir(parents=True, exist_ok=True)
1107
+ output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
1108
+ return output
1109
+
1110
+
1111
+ def write_daily_card(path: str | Path, card_text: str) -> Path:
1112
+ output = Path(path)
1113
+ output.parent.mkdir(parents=True, exist_ok=True)
1114
+ output.write_text(ensure_im_card_length(card_text) + "\n", encoding="utf-8")
1115
+ return output