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
alphasift/notify.py ADDED
@@ -0,0 +1,2608 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Unified 1-line & per-channel idempotent notifications (12 native channels + optional Apprise)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ from collections.abc import Iterator, Sequence
8
+ from contextlib import contextmanager
9
+ from datetime import datetime, timezone
10
+ from email.message import EmailMessage
11
+ from email.utils import formataddr
12
+ import fcntl
13
+ import hashlib
14
+ import hmac
15
+ import html as html_lib
16
+ import importlib
17
+ import json
18
+ import os
19
+ from pathlib import Path
20
+ import re
21
+ import smtplib
22
+ import ssl
23
+ import threading
24
+ import time
25
+ from typing import Any
26
+ from urllib.parse import parse_qs, quote, quote_plus, unquote, urlencode, urlsplit, urlunsplit
27
+
28
+ import requests
29
+
30
+ from alphasift.config import Config
31
+ from alphasift.daily_brief import resolve_strategy_display_names
32
+ from alphasift.daily_report import (
33
+ DEFAULT_DASHBOARD_URL,
34
+ IM_CARD_MAX_CHARS,
35
+ _clean_announcement_snippet,
36
+ ensure_im_card_length,
37
+ render_daily_im_card,
38
+ )
39
+ from alphasift.timeutil import parse_timestamp
40
+
41
+ SUPPORTED_CHANNELS: tuple[str, ...] = (
42
+ "wecom",
43
+ "feishu",
44
+ "dingtalk",
45
+ "pushplus",
46
+ "serverchan",
47
+ "bark",
48
+ "email",
49
+ "telegram",
50
+ "discord",
51
+ "slack",
52
+ "ntfy",
53
+ "custom",
54
+ "apprise",
55
+ )
56
+ _PROCESS_LOCK = threading.Lock()
57
+ _PENDING_LEASE_SEC = 120.0
58
+ _SCTP_PATTERN = re.compile(r"^sctp(\d+)t", re.I)
59
+
60
+ _SMTP_DEFAULTS: dict[str, tuple[str, int, str]] = {
61
+ "qq.com": ("smtp.qq.com", 465, "ssl"),
62
+ "foxmail.com": ("smtp.qq.com", 465, "ssl"),
63
+ "163.com": ("smtp.163.com", 465, "ssl"),
64
+ "126.com": ("smtp.126.com", 465, "ssl"),
65
+ "yeah.net": ("smtp.yeah.net", 465, "ssl"),
66
+ "gmail.com": ("smtp.gmail.com", 465, "ssl"),
67
+ "googlemail.com": ("smtp.gmail.com", 465, "ssl"),
68
+ "outlook.com": ("smtp.office365.com", 587, "starttls"),
69
+ "hotmail.com": ("smtp.office365.com", 587, "starttls"),
70
+ "live.com": ("smtp.office365.com", 587, "starttls"),
71
+ "icloud.com": ("smtp.mail.me.com", 587, "starttls"),
72
+ "me.com": ("smtp.mail.me.com", 587, "starttls"),
73
+ "aliyun.com": ("smtp.aliyun.com", 465, "ssl"),
74
+ "sina.com": ("smtp.sina.com", 465, "ssl"),
75
+ }
76
+
77
+
78
+ def _extract_url_secrets(url: str) -> list[str]:
79
+ text = str(url or "").strip()
80
+ if "://" not in text:
81
+ return []
82
+ parsed = urlsplit(text)
83
+ if parsed.scheme.lower() not in {"http", "https"}:
84
+ return []
85
+ segments: list[str] = []
86
+ for raw_seg in (parsed.path or "").split("/"):
87
+ seg = unquote(raw_seg).strip()
88
+ if len(seg) >= 6 and seg not in {"webhook", "services", "open-apis", "cgi-bin"}:
89
+ segments.append(seg)
90
+ return segments
91
+
92
+
93
+ def _valid_http_target(url: str) -> bool:
94
+ parsed = urlsplit(str(url or "").strip())
95
+ return (
96
+ parsed.scheme.lower() in {"http", "https"}
97
+ and bool(parsed.netloc)
98
+ and not any(ch.isspace() for ch in parsed.netloc)
99
+ )
100
+
101
+
102
+ def _strip_fragment_param(raw: str, key: str) -> tuple[str, str]:
103
+ parsed = urlsplit(raw)
104
+ secret = ""
105
+ kept_frag = parsed.fragment
106
+ kept_query = parsed.query
107
+ if parsed.fragment:
108
+ frag_qs = parse_qs(parsed.fragment, keep_blank_values=True)
109
+ if key in frag_qs:
110
+ secret = (frag_qs[key][0] or "").strip()
111
+ kept_pairs = [(k, v) for k, vals in frag_qs.items() if k != key for v in vals]
112
+ kept_frag = urlencode(kept_pairs, doseq=True)
113
+ if not secret and parsed.query:
114
+ qs = parse_qs(parsed.query, keep_blank_values=True)
115
+ if key in qs:
116
+ secret = (qs[key][0] or "").strip()
117
+ kept_q_pairs = [(k, v) for k, vals in qs.items() if k != key for v in vals]
118
+ kept_query = urlencode(kept_q_pairs, doseq=True)
119
+ clean_url = urlunsplit((parsed.scheme, parsed.netloc, parsed.path, kept_query, kept_frag))
120
+ return clean_url, secret
121
+
122
+
123
+ def _parse_mailto_uri(raw: str) -> dict[str, Any]:
124
+ rest = raw[len("mailto://") :]
125
+ if "?" in rest:
126
+ authority, query = rest.split("?", 1)
127
+ else:
128
+ authority, query = rest, ""
129
+ if "@" not in authority:
130
+ raise ValueError("Invalid mailto:// notification URI: missing '@' before host")
131
+ creds, hostport = authority.rsplit("@", 1)
132
+ if ":" in creds:
133
+ sender_raw, pass_raw = creds.split(":", 1)
134
+ else:
135
+ sender_raw, pass_raw = creds, ""
136
+ sender = unquote(sender_raw).strip()
137
+ password = unquote(pass_raw).strip()
138
+ smtp_host = ""
139
+ smtp_port = 0
140
+ if hostport and hostport.lower() != "auto":
141
+ if ":" in hostport:
142
+ h, p = hostport.rsplit(":", 1)
143
+ smtp_host = h.strip()
144
+ smtp_port = int(p) if p.isdigit() else 0
145
+ else:
146
+ smtp_host = hostport.strip()
147
+ if smtp_host and not smtp_host.startswith("smtp.") and smtp_host.lower() in _SMTP_DEFAULTS:
148
+ smtp_host = _SMTP_DEFAULTS[smtp_host.lower()][0]
149
+ qs = parse_qs(query)
150
+ to_vals = [addr.strip() for item in qs.get("to", []) for addr in item.split(",") if addr.strip()]
151
+ receivers = to_vals or ([sender] if sender else [])
152
+ return {
153
+ "channel": "email",
154
+ "target": sender,
155
+ "secret": password,
156
+ "token": "",
157
+ "extra": {
158
+ "sender": sender,
159
+ "password": password,
160
+ "receivers": receivers,
161
+ "smtp_host": smtp_host,
162
+ "smtp_port": smtp_port,
163
+ },
164
+ "secrets": [s for s in (raw, password, sender) if s],
165
+ }
166
+
167
+
168
+ def _parse_notify_url(raw: str) -> dict[str, Any] | None:
169
+ cleaned = raw.strip()
170
+ if not cleaned:
171
+ return None
172
+ if cleaned.lower().startswith("mailto://"):
173
+ return _parse_mailto_uri(cleaned)
174
+
175
+ parsed = urlsplit(cleaned)
176
+ scheme = (parsed.scheme or "").lower()
177
+ host = (parsed.hostname or "").lower()
178
+ path = parsed.path or ""
179
+
180
+ if scheme in {"pushplus"}:
181
+ token = unquote(parsed.netloc or "").strip()
182
+ topic = unquote(path.strip("/")).strip()
183
+ return {
184
+ "channel": "pushplus",
185
+ "target": token,
186
+ "secret": "",
187
+ "token": "",
188
+ "extra": {"topic": topic},
189
+ "secrets": [s for s in (cleaned, token) if s],
190
+ }
191
+ if scheme in {"sct", "serverchan", "ftqq"}:
192
+ sendkey = unquote((parsed.netloc + path).strip("/")).strip()
193
+ return {
194
+ "channel": "serverchan",
195
+ "target": sendkey,
196
+ "secret": "",
197
+ "token": "",
198
+ "extra": {},
199
+ "secrets": [s for s in (cleaned, sendkey) if s],
200
+ }
201
+ if scheme == "bark":
202
+ key_or_host = parsed.netloc.strip()
203
+ clean_path = path.lstrip("/")
204
+ if clean_path:
205
+ target = f"https://{key_or_host}/{clean_path}"
206
+ elif "." in key_or_host:
207
+ target = f"https://{key_or_host}"
208
+ else:
209
+ target = f"https://api.day.app/{key_or_host}"
210
+ if not _valid_http_target(target):
211
+ return None
212
+ return {
213
+ "channel": "bark",
214
+ "target": target,
215
+ "secret": "",
216
+ "token": "",
217
+ "extra": {},
218
+ "secrets": [s for s in (cleaned, target, key_or_host, *_extract_url_secrets(target)) if s],
219
+ }
220
+ if scheme in {"tgram", "tg"}:
221
+ bot_token = unquote(parsed.netloc or "").strip()
222
+ chat_id = unquote(path.strip("/").split("/", 1)[0]).strip()
223
+ return {
224
+ "channel": "telegram",
225
+ "target": bot_token,
226
+ "secret": "",
227
+ "token": "",
228
+ "extra": {"chat_id": chat_id},
229
+ "secrets": [s for s in (cleaned, bot_token, chat_id) if s],
230
+ }
231
+ if scheme == "ntfy":
232
+ if path.strip("/"):
233
+ target = f"https://{parsed.netloc.strip()}/{path.lstrip('/')}"
234
+ else:
235
+ target = f"https://ntfy.sh/{parsed.netloc.strip()}"
236
+ if not _valid_http_target(target):
237
+ return None
238
+ return {
239
+ "channel": "ntfy",
240
+ "target": target,
241
+ "secret": "",
242
+ "token": "",
243
+ "extra": {},
244
+ "secrets": [s for s in (cleaned, target, *_extract_url_secrets(target)) if s],
245
+ }
246
+ if scheme == "wecom":
247
+ raw_rest = cleaned.split("://", 1)[1].strip()
248
+ if not raw_rest:
249
+ return None
250
+ if raw_rest.lower().startswith(("http://", "https://")):
251
+ if not _valid_http_target(raw_rest):
252
+ return None
253
+ target = raw_rest
254
+ token_val = ""
255
+ else:
256
+ token_val = unquote(raw_rest.strip("/")).strip()
257
+ if not token_val:
258
+ return None
259
+ target = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={token_val}"
260
+ return {
261
+ "channel": "wecom",
262
+ "target": target,
263
+ "secret": "",
264
+ "token": "",
265
+ "extra": {},
266
+ "secrets": [s for s in (cleaned, target, token_val, *_extract_url_secrets(target)) if s],
267
+ }
268
+ if scheme in {"feishu", "lark"}:
269
+ raw_rest = cleaned.split("://", 1)[1].strip()
270
+ if not raw_rest:
271
+ return None
272
+ if raw_rest.lower().startswith(("http://", "https://")):
273
+ target, secret = _strip_fragment_param(raw_rest, "secret")
274
+ if not _valid_http_target(target):
275
+ return None
276
+ token_val = ""
277
+ else:
278
+ without_sec, secret = _strip_fragment_param(cleaned, "secret")
279
+ p2 = urlsplit(without_sec)
280
+ token_val = unquote((p2.netloc + p2.path).strip("/")).strip()
281
+ if not token_val:
282
+ return None
283
+ target = f"https://open.feishu.cn/open-apis/bot/v2/hook/{token_val}"
284
+ return {
285
+ "channel": "feishu",
286
+ "target": target,
287
+ "secret": secret,
288
+ "token": "",
289
+ "extra": {},
290
+ "secrets": [s for s in (cleaned, target, token_val, secret, *_extract_url_secrets(target)) if s],
291
+ }
292
+ if scheme == "dingtalk":
293
+ raw_rest = cleaned.split("://", 1)[1].strip()
294
+ if not raw_rest:
295
+ return None
296
+ if raw_rest.lower().startswith(("http://", "https://")):
297
+ target, secret = _strip_fragment_param(raw_rest, "secret")
298
+ if not _valid_http_target(target):
299
+ return None
300
+ token_val = ""
301
+ else:
302
+ without_sec, secret = _strip_fragment_param(cleaned, "secret")
303
+ p2 = urlsplit(without_sec)
304
+ token_val = unquote((p2.netloc + p2.path).strip("/")).strip()
305
+ if not token_val:
306
+ return None
307
+ target = f"https://oapi.dingtalk.com/robot/send?access_token={token_val}"
308
+ return {
309
+ "channel": "dingtalk",
310
+ "target": target,
311
+ "secret": secret,
312
+ "token": "",
313
+ "extra": {},
314
+ "secrets": [s for s in (cleaned, target, token_val, secret, *_extract_url_secrets(target)) if s],
315
+ }
316
+ if scheme == "discord":
317
+ raw_rest = cleaned.split("://", 1)[1].strip()
318
+ if not raw_rest:
319
+ return None
320
+ if raw_rest.lower().startswith(("http://", "https://")):
321
+ if not _valid_http_target(raw_rest):
322
+ return None
323
+ target = raw_rest
324
+ tail = ""
325
+ else:
326
+ tail = unquote(raw_rest.strip("/")).strip()
327
+ if not tail:
328
+ return None
329
+ target = f"https://discord.com/api/webhooks/{tail}"
330
+ return {
331
+ "channel": "discord",
332
+ "target": target,
333
+ "secret": "",
334
+ "token": "",
335
+ "extra": {},
336
+ "secrets": [s for s in (cleaned, target, tail, *tail.split("/"), *_extract_url_secrets(target)) if s],
337
+ }
338
+ if scheme == "slack":
339
+ raw_rest = cleaned.split("://", 1)[1].strip()
340
+ if not raw_rest:
341
+ return None
342
+ if raw_rest.lower().startswith(("http://", "https://")):
343
+ if not _valid_http_target(raw_rest):
344
+ return None
345
+ target = raw_rest
346
+ tail = ""
347
+ else:
348
+ tail = unquote(raw_rest.strip("/")).strip()
349
+ if not tail:
350
+ return None
351
+ target = f"https://hooks.slack.com/services/{tail}"
352
+ return {
353
+ "channel": "slack",
354
+ "target": target,
355
+ "secret": "",
356
+ "token": "",
357
+ "extra": {},
358
+ "secrets": [s for s in (cleaned, target, tail, *_extract_url_secrets(target)) if s],
359
+ }
360
+ if scheme == "custom":
361
+ inner = cleaned[len("custom://") :].strip()
362
+ if not inner:
363
+ return None
364
+ if not inner.lower().startswith(("http://", "https://")):
365
+ inner = f"https://{inner}"
366
+ target, token = _strip_fragment_param(inner, "token")
367
+ if not _valid_http_target(target):
368
+ return None
369
+ return {
370
+ "channel": "custom",
371
+ "target": target,
372
+ "secret": "",
373
+ "token": token,
374
+ "extra": {},
375
+ "secrets": [s for s in (cleaned, target, token, *_extract_url_secrets(target)) if s],
376
+ }
377
+
378
+ if scheme in {"http", "https"}:
379
+ if "qyapi.weixin.qq.com" in host:
380
+ return {"channel": "wecom", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
381
+ if "open.feishu.cn" in host or "open.larksuite.com" in host:
382
+ target, secret = _strip_fragment_param(cleaned, "secret")
383
+ return {
384
+ "channel": "feishu",
385
+ "target": target,
386
+ "secret": secret,
387
+ "token": "",
388
+ "extra": {},
389
+ "secrets": [s for s in (cleaned, target, secret, *_extract_url_secrets(target)) if s],
390
+ }
391
+ if "oapi.dingtalk.com" in host:
392
+ target, secret = _strip_fragment_param(cleaned, "secret")
393
+ return {
394
+ "channel": "dingtalk",
395
+ "target": target,
396
+ "secret": secret,
397
+ "token": "",
398
+ "extra": {},
399
+ "secrets": [s for s in (cleaned, target, secret, *_extract_url_secrets(target)) if s],
400
+ }
401
+ if "pushplus.plus" in host:
402
+ qs = parse_qs(parsed.query)
403
+ token = (qs.get("token") or [""])[0].strip() or path.strip("/").split("/")[-1]
404
+ topic = (qs.get("topic") or [""])[0].strip()
405
+ return {
406
+ "channel": "pushplus",
407
+ "target": token,
408
+ "secret": "",
409
+ "token": "",
410
+ "extra": {"topic": topic},
411
+ "secrets": [s for s in (cleaned, token) if s],
412
+ }
413
+ if "sctapi.ftqq.com" in host or "push.ft07.com" in host:
414
+ return {"channel": "serverchan", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
415
+ if "api.day.app" in host:
416
+ return {"channel": "bark", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
417
+ if "discord.com" in host or "discordapp.com" in host:
418
+ return {"channel": "discord", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
419
+ if "hooks.slack.com" in host:
420
+ return {"channel": "slack", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
421
+ if "ntfy.sh" in host:
422
+ return {"channel": "ntfy", "target": cleaned, "secret": "", "token": "", "extra": {}, "secrets": [cleaned, *_extract_url_secrets(cleaned)]}
423
+ target, token = _strip_fragment_param(cleaned, "token")
424
+ return {
425
+ "channel": "custom",
426
+ "target": target,
427
+ "secret": "",
428
+ "token": token,
429
+ "extra": {},
430
+ "secrets": [s for s in (cleaned, target, token, *_extract_url_secrets(target)) if s],
431
+ }
432
+
433
+ return {
434
+ "channel": "apprise",
435
+ "target": cleaned,
436
+ "secret": "",
437
+ "token": "",
438
+ "extra": {},
439
+ "secrets": [cleaned],
440
+ }
441
+
442
+
443
+ def resolve_notify_targets(config: Config) -> list[dict[str, Any]]:
444
+ """Resolve unified NOTIFY_URLS + legacy per-channel config entries in deterministic order."""
445
+ targets: list[dict[str, Any]] = []
446
+ seen: set[tuple[str, str, str]] = set()
447
+
448
+ def _add(entry: dict[str, Any] | None) -> None:
449
+ if not entry or not entry.get("target"):
450
+ return
451
+ extra = entry.get("extra") or {}
452
+ receivers_key = ",".join(
453
+ sorted(str(r).strip() for r in (extra.get("receivers") or []) if str(r).strip())
454
+ )
455
+ dedup_key = (
456
+ str(entry["channel"]),
457
+ str(entry["target"]),
458
+ str(extra.get("chat_id") or extra.get("topic") or receivers_key or ""),
459
+ )
460
+ if dedup_key in seen:
461
+ return
462
+ seen.add(dedup_key)
463
+ targets.append(entry)
464
+
465
+ # Legacy explicit config fields retain canonical channel ordering first.
466
+ if config.wecom_webhook_url:
467
+ _add({"channel": "wecom", "target": config.wecom_webhook_url, "secret": "", "token": "", "extra": {}, "secrets": [config.wecom_webhook_url, *_extract_url_secrets(config.wecom_webhook_url)]})
468
+ if config.feishu_webhook_url:
469
+ _add({"channel": "feishu", "target": config.feishu_webhook_url, "secret": config.feishu_webhook_secret, "token": "", "extra": {}, "secrets": [config.feishu_webhook_url, config.feishu_webhook_secret, *_extract_url_secrets(config.feishu_webhook_url)]})
470
+ if config.dingtalk_webhook_url:
471
+ _add({"channel": "dingtalk", "target": config.dingtalk_webhook_url, "secret": config.dingtalk_webhook_secret, "token": "", "extra": {}, "secrets": [config.dingtalk_webhook_url, config.dingtalk_webhook_secret, *_extract_url_secrets(config.dingtalk_webhook_url)]})
472
+ if config.pushplus_token:
473
+ _add({"channel": "pushplus", "target": config.pushplus_token, "secret": "", "token": "", "extra": {"topic": config.pushplus_topic}, "secrets": [config.pushplus_token]})
474
+ if config.serverchan_sendkey:
475
+ _add({"channel": "serverchan", "target": config.serverchan_sendkey, "secret": "", "token": "", "extra": {}, "secrets": [config.serverchan_sendkey]})
476
+ if config.bark_url:
477
+ norm_bark = _parse_notify_url(config.bark_url)
478
+ if norm_bark and norm_bark["channel"] == "bark":
479
+ _add(norm_bark)
480
+ else:
481
+ _add({"channel": "bark", "target": config.bark_url, "secret": "", "token": "", "extra": {}, "secrets": [config.bark_url, *_extract_url_secrets(config.bark_url)]})
482
+ if config.email_sender and config.email_password:
483
+ receivers = [r.strip() for r in (config.email_receivers or "").split(",") if r.strip()] or [config.email_sender]
484
+ _add({
485
+ "channel": "email",
486
+ "target": config.email_sender,
487
+ "secret": config.email_password,
488
+ "token": "",
489
+ "extra": {
490
+ "sender": config.email_sender,
491
+ "password": config.email_password,
492
+ "receivers": receivers,
493
+ "smtp_host": config.email_smtp_host,
494
+ "smtp_port": config.email_smtp_port,
495
+ },
496
+ "secrets": [config.email_sender, config.email_password],
497
+ })
498
+ if config.telegram_bot_token and config.telegram_chat_id:
499
+ _add({"channel": "telegram", "target": config.telegram_bot_token, "secret": "", "token": "", "extra": {"chat_id": config.telegram_chat_id}, "secrets": [config.telegram_bot_token, config.telegram_chat_id]})
500
+ if config.discord_webhook_url:
501
+ _add({"channel": "discord", "target": config.discord_webhook_url, "secret": "", "token": "", "extra": {}, "secrets": [config.discord_webhook_url, *_extract_url_secrets(config.discord_webhook_url)]})
502
+ if config.slack_webhook_url:
503
+ _add({"channel": "slack", "target": config.slack_webhook_url, "secret": "", "token": "", "extra": {}, "secrets": [config.slack_webhook_url, *_extract_url_secrets(config.slack_webhook_url)]})
504
+ if config.ntfy_url:
505
+ norm_ntfy = _parse_notify_url(config.ntfy_url)
506
+ if norm_ntfy and norm_ntfy["channel"] == "ntfy":
507
+ _add(norm_ntfy)
508
+ else:
509
+ _add({"channel": "ntfy", "target": config.ntfy_url, "secret": "", "token": "", "extra": {}, "secrets": [config.ntfy_url, *_extract_url_secrets(config.ntfy_url)]})
510
+ if config.custom_webhook_url:
511
+ _add({"channel": "custom", "target": config.custom_webhook_url, "secret": "", "token": config.custom_webhook_token, "extra": {}, "secrets": [config.custom_webhook_url, config.custom_webhook_token, *_extract_url_secrets(config.custom_webhook_url)]})
512
+
513
+ for raw in config.notify_urls:
514
+ _add(_parse_notify_url(raw))
515
+
516
+ order = {name: i for i, name in enumerate(SUPPORTED_CHANNELS)}
517
+ targets.sort(key=lambda t: order.get(t["channel"], len(SUPPORTED_CHANNELS)))
518
+ return targets
519
+
520
+
521
+ def configured_channels(config: Config) -> list[str]:
522
+ """Return distinct enabled notification channels in deterministic order."""
523
+ seen: list[str] = []
524
+ for t in resolve_notify_targets(config):
525
+ ch = t["channel"]
526
+ if ch not in seen:
527
+ seen.append(ch)
528
+ return seen
529
+
530
+
531
+ def notify_readiness(config: Config) -> dict[str, Any]:
532
+ """Return non-secret notification channel readiness metadata."""
533
+ targets = resolve_notify_targets(config)
534
+ channels = configured_channels(config)
535
+ return {
536
+ "supported_channels": list(SUPPORTED_CHANNELS),
537
+ "configured_channels": channels,
538
+ "notify_urls_count": len(config.notify_urls),
539
+ "target_count": len(targets),
540
+ "any_configured": bool(channels),
541
+ "wecom_configured": "wecom" in channels,
542
+ "feishu_configured": "feishu" in channels,
543
+ "feishu_signed": any(t["channel"] == "feishu" and bool(t.get("secret")) for t in targets),
544
+ "dingtalk_configured": "dingtalk" in channels,
545
+ "dingtalk_signed": any(t["channel"] == "dingtalk" and bool(t.get("secret")) for t in targets),
546
+ "pushplus_configured": "pushplus" in channels,
547
+ "serverchan_configured": "serverchan" in channels,
548
+ "bark_configured": "bark" in channels,
549
+ "email_configured": "email" in channels,
550
+ "telegram_configured": "telegram" in channels,
551
+ "discord_configured": "discord" in channels,
552
+ "slack_configured": "slack" in channels,
553
+ "ntfy_configured": "ntfy" in channels,
554
+ "custom_configured": "custom" in channels,
555
+ "custom_authenticated": any(t["channel"] == "custom" and bool(t.get("token")) for t in targets),
556
+ "apprise_configured": "apprise" in channels,
557
+ "state_path": str(config.notify_state_path),
558
+ }
559
+
560
+
561
+ def _feishu_sign(timestamp: int, secret: str) -> str:
562
+ string_to_sign = f"{timestamp}\n{secret}"
563
+ digest = hmac.new(
564
+ string_to_sign.encode("utf-8"),
565
+ msg=b"",
566
+ digestmod=hashlib.sha256,
567
+ ).digest()
568
+ return base64.b64encode(digest).decode("utf-8")
569
+
570
+
571
+ def _dingtalk_sign(timestamp_ms: int, secret: str) -> str:
572
+ string_to_sign = f"{timestamp_ms}\n{secret}"
573
+ digest = hmac.new(
574
+ secret.encode("utf-8"),
575
+ string_to_sign.encode("utf-8"),
576
+ digestmod=hashlib.sha256,
577
+ ).digest()
578
+ return quote_plus(base64.b64encode(digest))
579
+
580
+
581
+ _CRED_REDACT_RE = re.compile(
582
+ r'(?i)(["\']?(?:access_token|token|key|secret|password|sendkey)["\']?\s*[:=]\s*["\']?)([^\s&,\'"\}\]]+)'
583
+ r'|(bot\d+:)([A-Za-z0-9_-]+)'
584
+ r'|(Bearer\s+)([^\s,\'"\}\]]+)'
585
+ )
586
+ _TRANSIENT_HTTP_CODES = frozenset({429, 502, 503, 504, 520, 521, 522, 523, 524})
587
+ _NTFY_DATE_RE = re.compile(r"\(([^()]+)\)\s*$")
588
+
589
+
590
+ def _safe_json(resp: Any) -> dict[str, Any]:
591
+ try:
592
+ payload = resp.json()
593
+ except ValueError as exc:
594
+ preview = " ".join(str(getattr(resp, "text", "") or "").split())[:800]
595
+ raise RuntimeError(f"non-JSON response body: {preview or type(exc).__name__}") from exc
596
+ if not isinstance(payload, dict):
597
+ raise RuntimeError(f"unexpected JSON response type: {type(payload).__name__}")
598
+ return payload
599
+
600
+
601
+ def _retry_delay(resp: Any, default: float = 0.5) -> float:
602
+ if getattr(resp, "status_code", None) == 429:
603
+ headers = getattr(resp, "headers", None)
604
+ if hasattr(headers, "get"):
605
+ ra_raw = headers.get("Retry-After") or headers.get("retry-after")
606
+ if ra_raw is not None:
607
+ try:
608
+ return max(0.0, min(float(str(ra_raw).strip()), 5.0))
609
+ except ValueError:
610
+ pass
611
+ return default
612
+
613
+
614
+ def _post_with_retry(
615
+ post_fn: Any,
616
+ url: str,
617
+ *,
618
+ max_retries: int = 1,
619
+ sleep_fn: Any = None,
620
+ **kwargs: Any,
621
+ ) -> Any:
622
+ sleep = sleep_fn or time.sleep
623
+ attempts = max(0, int(max_retries)) + 1
624
+ for idx in range(attempts):
625
+ resp = post_fn(url, **kwargs)
626
+ code = getattr(resp, "status_code", None)
627
+ if idx < attempts - 1 and isinstance(code, int) and code in _TRANSIENT_HTTP_CODES:
628
+ sleep(_retry_delay(resp))
629
+ continue
630
+ try:
631
+ resp.raise_for_status()
632
+ return resp
633
+ except requests.HTTPError as exc:
634
+ err_resp = getattr(exc, "response", None)
635
+ err_code = getattr(err_resp, "status_code", code)
636
+ if idx < attempts - 1 and isinstance(err_code, int) and err_code in _TRANSIENT_HTTP_CODES:
637
+ sleep(_retry_delay(err_resp))
638
+ continue
639
+ raise
640
+ return resp # pragma: no cover
641
+
642
+
643
+ def _ntfy_ascii_title(title: str) -> str:
644
+ ascii_clean = " ".join(title.encode("ascii", "ignore").decode("ascii").split())
645
+ raw_clean = " ".join(title.split())
646
+ if ascii_clean and ascii_clean == raw_clean:
647
+ return ascii_clean
648
+ m = _NTFY_DATE_RE.search(raw_clean)
649
+ if m:
650
+ date_part = " ".join(m.group(1).encode("ascii", "ignore").decode("ascii").split())
651
+ if date_part:
652
+ return f"AlphaSift Daily Brief ({date_part})"
653
+ return "AlphaSift Daily Brief"
654
+
655
+
656
+ def _redact_error(exc: Exception, config: Config, extra_secrets: Sequence[str] = ()) -> str:
657
+ text = f"{type(exc).__name__}: {exc}"
658
+ raw_pool: list[str] = [
659
+ config.wecom_webhook_url,
660
+ config.feishu_webhook_url,
661
+ config.feishu_webhook_secret,
662
+ config.dingtalk_webhook_url,
663
+ config.dingtalk_webhook_secret,
664
+ config.pushplus_token,
665
+ config.serverchan_sendkey,
666
+ config.bark_url,
667
+ config.telegram_bot_token,
668
+ config.telegram_chat_id,
669
+ config.discord_webhook_url,
670
+ config.slack_webhook_url,
671
+ config.ntfy_url,
672
+ config.email_sender,
673
+ config.email_password,
674
+ config.custom_webhook_url,
675
+ config.custom_webhook_token,
676
+ *config.notify_urls,
677
+ *(getattr(config, "tavily_api_keys", ()) or ()),
678
+ *(getattr(config, "serpapi_api_keys", ()) or ()),
679
+ *extra_secrets,
680
+ ]
681
+ expanded: set[str] = set()
682
+ for secret in raw_pool:
683
+ if not secret:
684
+ continue
685
+ expanded.add(secret)
686
+ decoded = unquote(secret)
687
+ if decoded:
688
+ expanded.add(decoded)
689
+ encoded = quote(secret, safe="")
690
+ if encoded:
691
+ expanded.add(encoded)
692
+ for seg in _extract_url_secrets(secret):
693
+ expanded.add(seg)
694
+ for secret in sorted(expanded, key=len, reverse=True):
695
+ text = text.replace(secret, "***")
696
+ text = _CRED_REDACT_RE.sub(
697
+ lambda m: f"{m.group(1) or m.group(3) or m.group(5) or ''}***",
698
+ text,
699
+ )
700
+ return text[:240]
701
+
702
+
703
+ def _load_state(path: Path) -> dict[str, dict[str, Any]]:
704
+ if not path.is_file():
705
+ return {}
706
+ try:
707
+ raw = json.loads(path.read_text(encoding="utf-8"))
708
+ return raw if isinstance(raw, dict) else {}
709
+ except (OSError, ValueError):
710
+ return {}
711
+
712
+
713
+ def _save_state(path: Path, state: dict[str, dict[str, Any]]) -> None:
714
+ path.parent.mkdir(parents=True, exist_ok=True)
715
+ tmp = path.with_suffix(f"{path.suffix}.tmp.{os.getpid()}.{threading.get_ident()}")
716
+ tmp.write_text(json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
717
+ os.replace(tmp, path)
718
+
719
+
720
+ @contextmanager
721
+ def _ledger_lock(ledger_path: Path) -> Iterator[None]:
722
+ """Serialize push ledger access across threads and OS processes."""
723
+ lock_path = ledger_path.with_name(f".{ledger_path.name}.lock")
724
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
725
+ with _PROCESS_LOCK:
726
+ with open(lock_path, "a+", encoding="utf-8") as handle:
727
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
728
+ try:
729
+ yield
730
+ finally:
731
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
732
+
733
+
734
+ def _safe_http_link(raw: object) -> str:
735
+ cleaned = str(raw or "").strip()
736
+ if not cleaned or any(ch in cleaned for ch in '<>"\'\r\n\t\0'):
737
+ return ""
738
+ parsed = urlsplit(cleaned)
739
+ if parsed.scheme.lower() in {"http", "https"} and parsed.netloc:
740
+ return cleaned
741
+ return ""
742
+
743
+
744
+ def _has_rich_report(report: dict[str, Any] | None) -> bool:
745
+ return bool(
746
+ isinstance(report, dict)
747
+ and isinstance(report.get("market_regime"), dict)
748
+ and report.get("market_regime")
749
+ )
750
+
751
+
752
+ def _resolved_report_url(report: dict[str, Any]) -> str:
753
+ raw = DEFAULT_DASHBOARD_URL if report.get("detail_url") is None else report.get("detail_url")
754
+ return _safe_http_link(raw)
755
+
756
+
757
+ def _has_market_digest(report: dict[str, Any] | None) -> bool:
758
+ return bool(
759
+ isinstance(report, dict)
760
+ and report.get("object") == "MarketDigest"
761
+ and isinstance(report.get("market_sections"), list)
762
+ )
763
+
764
+
765
+ def _strategy_display_name(
766
+ report: dict[str, Any] | None,
767
+ key: object,
768
+ ) -> str:
769
+ raw = str(key or "").strip()
770
+ if not raw:
771
+ return ""
772
+ overrides = report.get("strategy_display_names") if isinstance(report, dict) else None
773
+ mapping = resolve_strategy_display_names(
774
+ overrides=overrides if isinstance(overrides, dict) else None
775
+ )
776
+ return mapping.get(raw, raw)
777
+
778
+
779
+ def _format_ann_meta(item: dict[str, Any]) -> tuple[str, str, str]:
780
+ """Return (flags_text, recency_date_tag, cleaned_snippet) for announcement risk item."""
781
+ flags = " / ".join(str(x) for x in (item.get("negative_event_flags") or [])[:2])
782
+ ann_date = str(item.get("announcement_date") or "").strip()
783
+ short_d = ann_date[5:] if len(ann_date) >= 10 else ann_date
784
+ recency = str(item.get("recency") or "").strip()
785
+ if short_d and recency == "old":
786
+ d_tag = f"{short_d}·历史进展"
787
+ elif short_d:
788
+ d_tag = short_d
789
+ elif recency == "old":
790
+ d_tag = "历史进展"
791
+ else:
792
+ d_tag = ""
793
+ raw_snip = item.get("matched_announcement") or item.get("announcement_summary")
794
+ snip = _clean_announcement_snippet(raw_snip, max_len=56)
795
+ return flags, d_tag, snip
796
+
797
+
798
+ def _build_report_title(report: dict[str, Any] | None, *, fallback_title: str) -> str:
799
+ if _has_rich_report(report):
800
+ assert report is not None
801
+ tdate = str(report.get("trade_date") or "").strip()
802
+ short_d = tdate[5:10] if len(tdate) >= 10 else (tdate or "-")
803
+ reg = report.get("market_regime") or {}
804
+ stage_lbl = str(reg.get("regime_stage_label") or "-")
805
+ adv = float(reg.get("advance_ratio_pct") or 0.0)
806
+ flagged_n = int((report.get("announcement_risks") or {}).get("flagged_count") or 0)
807
+ cons_n = len(((report.get("cross_strategy_synthesis") or {}).get("consensus_picks")) or [])
808
+ stale_tag = "[旧包]" if report.get("pack_is_stale") else ""
809
+ return f"AlphaSift A股日报{stale_tag} ({short_d})|{stage_lbl}·涨{adv:.0f}%·预警{flagged_n}·共识{cons_n}"
810
+ if _has_market_digest(report):
811
+ assert report is not None
812
+ tdate = str(report.get("trade_date") or "").strip()
813
+ short_d = tdate[5:10] if len(tdate) >= 10 else (tdate or "-")
814
+ mkts = "·".join(str(m).upper() for m in (report.get("markets") or [])) or "GLOBAL"
815
+ return f"AlphaSift 全球市场日报 ({short_d})|{mkts}"
816
+ return fallback_title
817
+
818
+
819
+ def _split_hit_patterns(report: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
820
+ """Return (primary_patterns, negative_watch_patterns) with non-zero hits."""
821
+ pat_sec = report.get("patterns") or {}
822
+ active = [p for p in (pat_sec.get("active") or []) if int(p.get("hit_count") or 0) > 0]
823
+ exp = [p for p in (pat_sec.get("experimental") or []) if int(p.get("hit_count") or 0) > 0]
824
+ active.sort(key=lambda p: -int(p.get("hit_count") or 0))
825
+ pos_exp = [p for p in exp if p.get("expectancy_tier") != "negative_watch"]
826
+ neg_exp = [p for p in exp if p.get("expectancy_tier") == "negative_watch"]
827
+ pos_exp.sort(
828
+ key=lambda p: (
829
+ 0 if p.get("expectancy_tier") == "positive_watch" else 1,
830
+ -int(p.get("hit_count") or 0),
831
+ )
832
+ )
833
+ neg_exp.sort(key=lambda p: -int(p.get("hit_count") or 0))
834
+ return [*active, *pos_exp], neg_exp
835
+
836
+
837
+ def _render_markdown_digest(
838
+ report: dict[str, Any] | None,
839
+ content: str,
840
+ *,
841
+ title: str,
842
+ wecom_colors: bool = False,
843
+ ) -> str:
844
+ """Rich Markdown digest shared across WeCom (with color tags), DingTalk, PushPlus & ServerChan."""
845
+ if _has_market_digest(report):
846
+ assert report is not None
847
+ lines = [f"### {title}"]
848
+ for sec in (report.get("market_sections") or [])[:6]:
849
+ m_name = sec.get("market_name") or str(sec.get("market") or "").upper()
850
+ lines.append(f"\n**{m_name}**({int(sec.get('strategy_count') or 0)} 组策略 · {sec.get('trade_date', '-')})")
851
+ top_picks = sec.get("top_picks") or []
852
+ if top_picks:
853
+ for p in top_picks[:4]:
854
+ px = f" ¥{float(p['price']):.2f}" if p.get("price") is not None else ""
855
+ chg = f" {_fmt_report_pct(p.get('change_pct'))}" if p.get("change_pct") is not None else ""
856
+ strats = "·".join((p.get("strategy_display_names") or p.get("strategies") or [])[:2])
857
+ lines.append(
858
+ f"- **{p.get('name') or p.get('code')}** `{p.get('code')}`{px}{chg} · "
859
+ f"{float(p.get('avg_final_score') or 0):.1f}分 ({strats})"
860
+ )
861
+ else:
862
+ lines.append("- 暂无入选标的")
863
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
864
+ if mnews:
865
+ lines.append("\n**市场热点快讯**")
866
+ for item in mnews[:3]:
867
+ lines.append(f"- {item.get('title', '')}")
868
+ detail_url = _resolved_report_url(report)
869
+ if detail_url:
870
+ lines.append(f"\n🔗 [查看完整看板]({detail_url})")
871
+ lines.append("\n> 注:量化观测与回测基准,非投资建议。")
872
+ out = "\n".join(lines)
873
+ if wecom_colors:
874
+ while len(out.encode("utf-8")) > 3950 and len(lines) > 4:
875
+ lines.pop(-3)
876
+ out = "\n".join(lines)
877
+ return out
878
+
879
+ if not _has_rich_report(report):
880
+ return content
881
+
882
+ assert report is not None
883
+ reg = report.get("market_regime") or {}
884
+ stage_lbl = str(reg.get("regime_stage_label") or "-")
885
+ adv = float(reg.get("advance_ratio_pct") or 0.0)
886
+ med_str = _fmt_report_pct(reg.get("median_return_pct"))
887
+ seal = reg.get("seal_rate_pct")
888
+ seal_str = "-" if seal is None else f"{float(seal):.1f}%"
889
+ amt = reg.get("total_amount_yi")
890
+ amt_str = "-" if amt is None else f"{float(amt):,.0f} 亿"
891
+ prev_str = _fmt_report_pct(reg.get("prev_limit_up_avg_return_pct"))
892
+ lu = int(reg.get("non_st_limit_up_count") or 0)
893
+ ld = int(reg.get("non_st_limit_down_count") or 0)
894
+ max_streak = int(reg.get("max_consecutive_limit_up") or 0)
895
+
896
+ if wecom_colors:
897
+ head_line = f'### {title}\n> 盘面:<font color="info">{stage_lbl}</font>|上涨 <font color="warning">{adv:.1f}%</font>(中位 {med_str})|涨跌停 {lu}/{ld}(封板 {seal_str})|最高 {max_streak}板 · 昨涨停 {prev_str} · 成交 {amt_str}'
898
+ else:
899
+ head_line = f"### {title}\n> 盘面 **{stage_lbl}**|上涨 {adv:.1f}%(中位 {med_str})|涨跌停 {lu}/{ld}(封板 {seal_str})|最高 {max_streak}板 · 昨涨停 {prev_str} · 成交 {amt_str}"
900
+ lines = [head_line]
901
+ if report.get("pack_is_stale"):
902
+ lines.append(f"> ⚠️ 旧包降级:包日期 {report.get('pack_trade_date', '-')} < {report.get('expected_trade_date', '-')}")
903
+
904
+ ann = report.get("announcement_risks") or {}
905
+ flagged = ann.get("flagged_items") or []
906
+ checked = int(ann.get("checked_count") or 0)
907
+ if flagged:
908
+ tag_open, tag_close = ('<font color="warning">', "</font>") if wecom_colors else ("", "")
909
+ lines.append(f"\n**{tag_open}⚠️ 公告排雷预警({checked}检/{len(flagged)}中){tag_close}**")
910
+ for item in flagged[:5]:
911
+ flags, d_tag, snip = _format_ann_meta(item)
912
+ meta = f"[{d_tag} · {flags}]" if d_tag else f"[{flags}]"
913
+ lines.append(f"- **{item.get('code', '')} {item.get('name', '')}** {meta}" + (f":{snip}" if snip else ""))
914
+ elif checked > 0:
915
+ lines.append(f"\n**✅ 公告排雷**:抽检 {checked} 只重点候选无异常")
916
+
917
+ brief = report.get("ai_brief") or {}
918
+ if brief.get("headline"):
919
+ lbl = "🤖 AI 盘后综述" if brief.get("mode") == "llm" else "📌 盘后盘面摘要"
920
+ lines.append(f"\n**{lbl}**:{str(brief['headline']).strip()}")
921
+ sub_b = str(brief.get("consensus_and_ai_edge") or brief.get("regime_interpretation") or "").strip()
922
+ if sub_b:
923
+ lines.append(sub_b[:220])
924
+
925
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
926
+ if mnews:
927
+ lines.append("\n**📰 市场热点快讯**")
928
+ for item in mnews[:4]:
929
+ t_str = f" ({item.get('published_at')})" if item.get("published_at") else ""
930
+ lines.append(f"- [{item.get('category') or '要闻'}] {item.get('title', '')}{t_str}")
931
+
932
+ syn = report.get("cross_strategy_synthesis") or {}
933
+ consensus = syn.get("consensus_picks") or []
934
+ if consensus:
935
+ lines.append(f"\n**🎯 跨策略共识精选(Top {min(6, len(consensus))}/{len(consensus)})**")
936
+ for idx, c in enumerate(consensus[:6], start=1):
937
+ strats = "·".join(_strategy_display_name(report, s) for s in (c.get("strategies") or [])[:3])
938
+ px = f" ¥{float(c['price']):.2f}" if c.get("price") is not None else ""
939
+ pe = f" PE {float(c['pe_ratio']):.1f}" if c.get("pe_ratio") is not None else ""
940
+ chg = f" {_fmt_report_pct(c.get('change_pct'))}" if c.get("change_pct") is not None else ""
941
+ lines.append(
942
+ f"{idx}. **{c.get('name', '')}** `{c.get('code', '')}`{px}{pe}{chg} · "
943
+ f"{int(c.get('strategy_count') or 0)}策略({strats})"
944
+ )
945
+
946
+ primary_pats, neg_pats = _split_hit_patterns(report)
947
+ if primary_pats or neg_pats:
948
+ lines.append("\n**📡 形态雷达触发**")
949
+ for p in (primary_pats or neg_pats)[:4]:
950
+ tag = "active" if p.get("status") == "active" else "观察期"
951
+ net_s = f" · T+5净{float(p['replay_t5_net_excess_pct']):+.2f}%" if p.get("replay_t5_net_excess_pct") is not None else ""
952
+ sigs = "、".join(
953
+ f"{s.get('name') or s.get('code')}({_fmt_report_pct(s.get('change_pct'))})"
954
+ for s in (p.get("signals") or [])[:3]
955
+ )
956
+ lines.append(f"- **{p.get('display_name') or p.get('pattern')}**({int(p.get('hit_count') or 0)}只 · {tag}{net_s}):{sigs}")
957
+ if primary_pats and neg_pats:
958
+ neg_txt = "、".join(f"{p.get('display_name')}({int(p.get('hit_count') or 0)})" for p in neg_pats)
959
+ lines.append(f"- 负期望形态(仅供参考):{neg_txt}")
960
+
961
+ detail_url = _resolved_report_url(report)
962
+ if detail_url:
963
+ lines.append(f"\n🔗 [打开在线交互看板(K线 & T+N实盘验证)]({detail_url})")
964
+ lines.append("\n> 注:量化形态观测与回测基准,非投资建议。")
965
+ out = "\n".join(lines)
966
+ if wecom_colors:
967
+ while len(out.encode("utf-8")) > 3950 and len(lines) > 5:
968
+ lines.pop(-2)
969
+ out = "\n".join(lines)
970
+ return out
971
+
972
+
973
+ def _send_wecom(
974
+ webhook_url: str,
975
+ content: str,
976
+ *,
977
+ title: str = "",
978
+ report: dict[str, Any] | None = None,
979
+ timeout_sec: float,
980
+ post_fn=requests.post,
981
+ ) -> None:
982
+ body_text = _render_markdown_digest(report, content, title=title or "AlphaSift 日报", wecom_colors=True)
983
+ resp = _post_with_retry(
984
+ post_fn,
985
+ webhook_url,
986
+ json={"msgtype": "markdown", "markdown": {"content": body_text}},
987
+ timeout=timeout_sec,
988
+ )
989
+ payload = _safe_json(resp)
990
+ if int(payload.get("errcode", -1)) != 0:
991
+ raise RuntimeError(f"wecom errcode={payload.get('errcode')} errmsg={payload.get('errmsg', '')}")
992
+
993
+
994
+ def _stage_palette(stage: str) -> tuple[str, str, str]:
995
+ """Return (bg, fg, feishu_template) for CN market regime stage."""
996
+ if stage in {"freezing", "ebb"}:
997
+ return "#FEF2F2", "#DC2626", "red"
998
+ if stage in {"startup", "main_up"}:
999
+ return "#ECFDF5", "#059669", "green"
1000
+ if stage == "divergence":
1001
+ return "#FFFBEB", "#D97706", "orange"
1002
+ return "#F1F5F9", "#475569", "blue"
1003
+
1004
+
1005
+ def _fmt_report_pct(val: object) -> str:
1006
+ if val is None:
1007
+ return "–"
1008
+ try:
1009
+ num = float(val)
1010
+ except (TypeError, ValueError):
1011
+ return "–"
1012
+ if num != num:
1013
+ return "–"
1014
+ return f"{num:+.2f}%"
1015
+
1016
+
1017
+ def _build_feishu_card(
1018
+ report: dict[str, Any] | None,
1019
+ content: str,
1020
+ *,
1021
+ title: str,
1022
+ ) -> dict[str, Any]:
1023
+ if _has_market_digest(report):
1024
+ assert report is not None
1025
+ elements: list[dict[str, Any]] = []
1026
+ for sec in (report.get("market_sections") or [])[:6]:
1027
+ m_name = sec.get("market_name") or str(sec.get("market") or "").upper()
1028
+ lines = [f"**🌍 {m_name}**({int(sec.get('strategy_count') or 0)} 组策略 · {sec.get('trade_date', '-')})"]
1029
+ top_picks = sec.get("top_picks") or []
1030
+ if top_picks:
1031
+ for p in top_picks[:4]:
1032
+ px = f" · ¥{float(p['price']):.2f}" if p.get("price") is not None else ""
1033
+ chg = f" · {_fmt_report_pct(p.get('change_pct'))}" if p.get("change_pct") is not None else ""
1034
+ strats = "·".join((p.get("strategy_display_names") or p.get("strategies") or [])[:2])
1035
+ lines.append(
1036
+ f"- **{p.get('name') or p.get('code')}** `{p.get('code')}`{px}{chg} · "
1037
+ f"{float(p.get('avg_final_score') or 0):.1f}分({strats})"
1038
+ )
1039
+ else:
1040
+ lines.append("- 今日暂无入选标的")
1041
+ elements.append({"tag": "markdown", "content": "\n".join(lines)})
1042
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1043
+ if mnews:
1044
+ n_lines = ["**📰 市场热点快讯**", *(f"- {n.get('title', '')}" for n in mnews[:3])]
1045
+ elements.append({"tag": "markdown", "content": "\n".join(n_lines)})
1046
+ detail_url = _resolved_report_url(report)
1047
+ if detail_url:
1048
+ elements.append({
1049
+ "tag": "action",
1050
+ "actions": [{
1051
+ "tag": "button",
1052
+ "text": {"tag": "plain_text", "content": "打开在线交互看板与历史战绩"},
1053
+ "type": "primary",
1054
+ "url": detail_url,
1055
+ }],
1056
+ })
1057
+ return {
1058
+ "config": {"wide_screen_mode": True},
1059
+ "header": {"title": {"tag": "plain_text", "content": title}, "template": "blue"},
1060
+ "elements": elements,
1061
+ }
1062
+
1063
+ if not _has_rich_report(report):
1064
+ return {
1065
+ "config": {"wide_screen_mode": True},
1066
+ "header": {"title": {"tag": "plain_text", "content": title}, "template": "blue"},
1067
+ "elements": [{"tag": "markdown", "content": content}],
1068
+ }
1069
+
1070
+ assert report is not None
1071
+ reg = report.get("market_regime") or {}
1072
+ stage = str(reg.get("regime_stage") or "")
1073
+ stage_lbl = str(reg.get("regime_stage_label") or "-")
1074
+ _, _, tmpl = _stage_palette(stage)
1075
+ ann = report.get("announcement_risks") or {}
1076
+ flagged = ann.get("flagged_items") or []
1077
+ checked = int(ann.get("checked_count") or 0)
1078
+ if report.get("pack_is_stale"):
1079
+ tmpl = "orange"
1080
+ elif flagged:
1081
+ tmpl = "red"
1082
+
1083
+ seal = reg.get("seal_rate_pct")
1084
+ seal_str = "-" if seal is None else f"{float(seal):.1f}%"
1085
+ prev_ret = reg.get("prev_limit_up_avg_return_pct")
1086
+ prev_str = "-" if prev_ret is None else f"{float(prev_ret):+.2f}%"
1087
+ amt = reg.get("total_amount_yi")
1088
+ amt_str = "-" if amt is None else f"{float(amt):,.0f} 亿"
1089
+ med = reg.get("median_return_pct")
1090
+ med_str = "-" if med is None else f"{float(med):+.2f}%"
1091
+ adv_str = f"{float(reg.get('advance_ratio_pct', 0.0)):.1f}%"
1092
+
1093
+ elements: list[dict[str, Any]] = []
1094
+ if report.get("pack_is_stale"):
1095
+ elements.append({
1096
+ "tag": "markdown",
1097
+ "content": (
1098
+ f"⚠️ **旧包降级提示**:当前包日期 `{report.get('pack_trade_date', '-')}` "
1099
+ f"落后于目标交易日 `{report.get('expected_trade_date', '-')}`,仅供参考"
1100
+ ),
1101
+ })
1102
+
1103
+ elements.append({
1104
+ "tag": "div",
1105
+ "fields": [
1106
+ {
1107
+ "is_short": True,
1108
+ "text": {"tag": "lark_md", "content": f"**盘面温度({stage_lbl})**\n上涨 {adv_str} · 中位 {med_str}"},
1109
+ },
1110
+ {
1111
+ "is_short": True,
1112
+ "text": {
1113
+ "tag": "lark_md",
1114
+ "content": (
1115
+ f"**非ST涨跌停 / 封板**\n"
1116
+ f"{reg.get('non_st_limit_up_count', 0)} 涨停 / {reg.get('non_st_limit_down_count', 0)} 跌停 · {seal_str}"
1117
+ ),
1118
+ },
1119
+ },
1120
+ {
1121
+ "is_short": True,
1122
+ "text": {"tag": "lark_md", "content": f"**连板与昨涨停**\n最高 {reg.get('max_consecutive_limit_up', 0)} 板 · 昨涨停 {prev_str}"},
1123
+ },
1124
+ {
1125
+ "is_short": True,
1126
+ "text": {"tag": "lark_md", "content": f"**两市成交额**\n{amt_str}"},
1127
+ },
1128
+ ],
1129
+ })
1130
+ elements.append({"tag": "hr"})
1131
+
1132
+ # Alert-first Announcement risk block with date & recency
1133
+ if flagged:
1134
+ ann_lines = [f"**⚠️ 公告排雷预警(抽检 {checked} 只,命中 {len(flagged)} 只预警)**"]
1135
+ for item in flagged[:5]:
1136
+ flags, d_tag, snip = _format_ann_meta(item)
1137
+ meta = f"[{d_tag} · {flags}]" if d_tag else f"[{flags}]"
1138
+ line = f"- **{item.get('code', '')} {item.get('name', '')}** {meta}"
1139
+ if snip:
1140
+ line += f":{snip}"
1141
+ ann_lines.append(line)
1142
+ if len(flagged) > 5:
1143
+ ann_lines.append(f"- 其余 {len(flagged) - 5} 条请查看完整研报或看板")
1144
+ elements.append({"tag": "markdown", "content": "\n".join(ann_lines)})
1145
+ elif checked > 0 and ann.get("errors"):
1146
+ elements.append({"tag": "markdown", "content": f"**⚠️ 公告排雷降级**:抽检 {checked} 只({str(ann['errors'][0])[:60]})"})
1147
+ elif checked > 0:
1148
+ elements.append({"tag": "markdown", "content": f"**✅ 公告排雷通过**:抽检 {checked} 只重点候选,未检出高风险实质性负面公告"})
1149
+
1150
+ # Brief summary
1151
+ brief = report.get("ai_brief") or {}
1152
+ if brief.get("headline"):
1153
+ brief_lbl = f"🤖 AI 盘后综述 ({brief.get('model')})" if brief.get("mode") == "llm" and brief.get("model") else ("🤖 AI 盘后综述" if brief.get("mode") == "llm" else "📌 盘后盘面摘要")
1154
+ b_lines = [f"**{brief_lbl}**:{str(brief['headline']).strip()}"]
1155
+ if brief.get("consensus_and_ai_edge"):
1156
+ b_lines.append(str(brief["consensus_and_ai_edge"]).strip())
1157
+ elif brief.get("regime_interpretation"):
1158
+ b_lines.append(str(brief["regime_interpretation"]).strip())
1159
+ elements.append({"tag": "markdown", "content": "\n".join(b_lines)})
1160
+
1161
+ # Market News highlights
1162
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1163
+ if mnews:
1164
+ n_lines = ["**📰 市场热点与政策快讯**"]
1165
+ for item in mnews[:4]:
1166
+ pub = f"({item.get('published_at')})" if item.get("published_at") else ""
1167
+ n_lines.append(f"- **[{item.get('category') or '要闻'}]** {item.get('title', '')}{pub}")
1168
+ elements.append({"tag": "markdown", "content": "\n".join(n_lines)})
1169
+
1170
+ # Multi-strategy consensus table-like list with Chinese strategy names, valuation & reasons
1171
+ syn = report.get("cross_strategy_synthesis") or {}
1172
+ consensus = syn.get("consensus_picks") or []
1173
+ strategies = report.get("strategies") or []
1174
+ if consensus:
1175
+ c_lines = [f"**🎯 跨策略高共识精选(共 {len(consensus)} 只,展示 Top 5)**"]
1176
+ for idx, c in enumerate(consensus[:5], start=1):
1177
+ risk_tag = " ⚠️" if c.get("announcement_risk_flags") else ""
1178
+ chg = f" · {_fmt_report_pct(c.get('change_pct'))}" if c.get("change_pct") is not None else ""
1179
+ px = f" · ¥{float(c['price']):.2f}" if c.get("price") is not None else ""
1180
+ pe = f" · PE {float(c['pe_ratio']):.1f}" if c.get("pe_ratio") is not None else ""
1181
+ sc_txt = f" · 均分 {float(c['avg_final_score']):.1f}" if c.get("avg_final_score") is not None else ""
1182
+ ind = str(c.get("industry") or "-")
1183
+ strats_cn = "·".join(_strategy_display_name(report, s) for s in (c.get("strategies") or [])[:3])
1184
+ strat_part = f"({strats_cn})" if strats_cn else ""
1185
+ c_lines.append(
1186
+ f"{idx}. **{c.get('name', '')}** `{c.get('code', '')}`{risk_tag} · {ind}{px}{pe}{chg} · "
1187
+ f"**{c.get('strategy_count', 0)} 策略**{strat_part}{sc_txt}"
1188
+ )
1189
+ if c.get("reasons"):
1190
+ c_lines.append(f" 理由:{str(c['reasons'][0])[:48]}")
1191
+ elements.append({"tag": "markdown", "content": "\n".join(c_lines)})
1192
+ elif not strategies:
1193
+ elements.append({"tag": "markdown", "content": "**🎯 策略概览**:当日未附带 CN 策略选股运行,下方展示盘后形态扫描结果"})
1194
+
1195
+ # Pattern radar hits tiered by historical expectancy
1196
+ primary_pats, neg_pats = _split_hit_patterns(report)
1197
+ if primary_pats or neg_pats:
1198
+ p_lines = ["**📡 形态雷达触发**"]
1199
+ for p in (primary_pats or neg_pats)[:4]:
1200
+ tag = "active" if p.get("status") == "active" else "观察期"
1201
+ net_s = f" · T+5净{float(p['replay_t5_net_excess_pct']):+.2f}%" if p.get("replay_t5_net_excess_pct") is not None else ""
1202
+ sigs = "、".join(
1203
+ f"{s.get('name') or s.get('code')}({s.get('code')}, {_fmt_report_pct(s.get('change_pct'))})"
1204
+ for s in (p.get("signals") or [])[:3]
1205
+ )
1206
+ p_lines.append(
1207
+ f"- **{p.get('display_name') or p.get('pattern')}**({int(p.get('hit_count') or 0)} 只 · {tag}{net_s})"
1208
+ + (f":{sigs}" if sigs else "")
1209
+ )
1210
+ if primary_pats and neg_pats:
1211
+ neg_txt = "、".join(f"{p.get('display_name')}({int(p.get('hit_count') or 0)}只)" for p in neg_pats)
1212
+ p_lines.append(f"- 负期望形态仅供参考:{neg_txt}")
1213
+ elements.append({"tag": "markdown", "content": "\n".join(p_lines)})
1214
+
1215
+ elements.append({"tag": "hr"})
1216
+ detail_url = _resolved_report_url(report)
1217
+ if detail_url:
1218
+ elements.append({
1219
+ "tag": "action",
1220
+ "actions": [{
1221
+ "tag": "button",
1222
+ "text": {"tag": "plain_text", "content": "打开在线交互看板(20日K线 & T+N实盘验证)"},
1223
+ "type": "primary",
1224
+ "url": detail_url,
1225
+ }],
1226
+ })
1227
+ elements.append({
1228
+ "tag": "note",
1229
+ "elements": [{
1230
+ "tag": "plain_text",
1231
+ "content": "AlphaSift · 开源量化选股与 T+N 验证基准 · 历史统计不含分红,不构成投资建议",
1232
+ }],
1233
+ })
1234
+ return {
1235
+ "config": {"wide_screen_mode": True},
1236
+ "header": {"title": {"tag": "plain_text", "content": title}, "template": tmpl},
1237
+ "elements": elements,
1238
+ }
1239
+
1240
+
1241
+ def _render_telegram_html(
1242
+ report: dict[str, Any] | None,
1243
+ content: str,
1244
+ *,
1245
+ title: str,
1246
+ ) -> str:
1247
+ esc = html_lib.escape
1248
+ if _has_market_digest(report):
1249
+ assert report is not None
1250
+ parts: list[str] = [
1251
+ f"🌍 <b>{esc(title)}</b>",
1252
+ ]
1253
+ for sec in (report.get("market_sections") or [])[:6]:
1254
+ m_name = sec.get("market_name") or str(sec.get("market") or "").upper()
1255
+ lines = [f"\n<b>{esc(m_name)}</b>({int(sec.get('strategy_count') or 0)}组策略 · <code>{esc(str(sec.get('trade_date', '-')))}</code>)"]
1256
+ for p in (sec.get("top_picks") or [])[:4]:
1257
+ px = f" ¥{float(p['price']):.2f}" if p.get("price") is not None else ""
1258
+ chg = f" {_fmt_report_pct(p.get('change_pct'))}" if p.get("change_pct") is not None else ""
1259
+ strats = "·".join((p.get("strategy_display_names") or p.get("strategies") or [])[:2])
1260
+ lines.append(
1261
+ f"• <b>{esc(str(p.get('name') or p.get('code')))}</b> <code>{esc(str(p.get('code')))}</code>"
1262
+ f"{esc(px)}{esc(chg)} · {float(p.get('avg_final_score') or 0):.1f}分({esc(strats)})"
1263
+ )
1264
+ parts.append("\n".join(lines))
1265
+ detail_url = _resolved_report_url(report)
1266
+ tail = (
1267
+ f'\n🔗 <a href="{esc(detail_url, quote=True)}">查看完整看板</a>\n'
1268
+ if detail_url
1269
+ else "\n"
1270
+ ) + "<i>注:仅作量化观测与回测基准,不构成投资建议。</i>"
1271
+ out = "\n".join(parts) + tail
1272
+ return out[:3990] + ("…" if len(out) > 3990 else "")
1273
+
1274
+ if not _has_rich_report(report):
1275
+ lines = [f"<b>{esc(title)}</b>"]
1276
+ for raw_line in content.splitlines():
1277
+ s = raw_line.strip()
1278
+ if not s:
1279
+ continue
1280
+ s_esc = esc(s)
1281
+ s_esc = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", s_esc)
1282
+ if s_esc.startswith("&gt; "):
1283
+ lines.append(f"<blockquote>{s_esc[5:]}</blockquote>")
1284
+ else:
1285
+ lines.append(s_esc)
1286
+ out = "\n".join(lines)
1287
+ return out[:3990] + ("…" if len(out) > 3990 else "")
1288
+
1289
+ assert report is not None
1290
+ reg = report.get("market_regime") or {}
1291
+ seal = reg.get("seal_rate_pct")
1292
+ seal_str = "-" if seal is None else f"{float(seal):.1f}%"
1293
+ prev_ret = reg.get("prev_limit_up_avg_return_pct")
1294
+ prev_str = "-" if prev_ret is None else f"{float(prev_ret):+.2f}%"
1295
+ amt = reg.get("total_amount_yi")
1296
+ amt_str = "-" if amt is None else f"{float(amt):,.0f} 亿"
1297
+ med = reg.get("median_return_pct")
1298
+ med_str = "-" if med is None else f"{float(med):+.2f}%"
1299
+
1300
+ parts = [
1301
+ f"📊 <b>AlphaSift · A 股盘后观察</b> <code>{esc(str(report.get('trade_date', '-')))}</code>",
1302
+ ]
1303
+ if report.get("pack_is_stale"):
1304
+ parts.append(
1305
+ f"⚠️ <b>旧包降级</b>:包日期 <code>{esc(str(report.get('pack_trade_date', '-')))}</code> "
1306
+ f"&lt; 目标 <code>{esc(str(report.get('expected_trade_date', '-')))}</code>"
1307
+ )
1308
+ parts.append(
1309
+ "<blockquote>"
1310
+ f"<b>盘面 · {esc(str(reg.get('regime_stage_label', '-')))}</b>|上涨 <b>{float(reg.get('advance_ratio_pct', 0.0)):.1f}%</b>(中位 {esc(med_str)})\n"
1311
+ f"涨跌停 <b>{int(reg.get('non_st_limit_up_count', 0))}/{int(reg.get('non_st_limit_down_count', 0))}</b>(封板 {esc(seal_str)})|"
1312
+ f"最高 {int(reg.get('max_consecutive_limit_up', 0))}板 · 昨涨停 {esc(prev_str)} · 成交 {esc(amt_str)}"
1313
+ "</blockquote>"
1314
+ )
1315
+
1316
+ ann = report.get("announcement_risks") or {}
1317
+ flagged = ann.get("flagged_items") or []
1318
+ checked = int(ann.get("checked_count") or 0)
1319
+ if flagged:
1320
+ ann_lines = [f"\n⚠️ <b>公告排雷预警</b>({checked}检 / {len(flagged)}中)"]
1321
+ for item in flagged[:4]:
1322
+ flags, d_tag, snip = _format_ann_meta(item)
1323
+ meta = f"[{d_tag} · {flags}]" if d_tag else f"[{flags}]"
1324
+ ann_lines.append(
1325
+ f"• <code>{esc(str(item.get('code', '')))}</code> <b>{esc(str(item.get('name', '')))}</b> "
1326
+ f"{esc(meta)}" + (f":{esc(snip)}" if snip else "")
1327
+ )
1328
+ parts.append("\n".join(ann_lines))
1329
+ elif checked > 0:
1330
+ parts.append(f"\n✅ <b>公告排雷</b>:抽检 {checked} 只重点候选无实质风险")
1331
+
1332
+ brief = report.get("ai_brief") or {}
1333
+ if brief.get("headline"):
1334
+ lbl = "🤖 AI 盘后综述" if brief.get("mode") == "llm" else "📌 盘后盘面摘要"
1335
+ b_txt = f"\n<b>{lbl}</b>\n{esc(str(brief['headline']).strip())}"
1336
+ summary_line = str(brief.get("consensus_and_ai_edge") or brief.get("regime_interpretation") or brief.get("market_summary") or "").strip()
1337
+ if summary_line:
1338
+ b_txt += f"\n{esc(summary_line[:180])}"
1339
+ parts.append(b_txt)
1340
+
1341
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1342
+ if mnews:
1343
+ n_lines = ["\n📰 <b>市场热点快讯</b>"]
1344
+ for item in mnews[:3]:
1345
+ n_lines.append(f"• [{esc(str(item.get('category') or '要闻'))}] {esc(str(item.get('title') or ''))}")
1346
+ parts.append("\n".join(n_lines))
1347
+
1348
+ syn = report.get("cross_strategy_synthesis") or {}
1349
+ consensus = syn.get("consensus_picks") or []
1350
+ if consensus:
1351
+ c_lines = [f"\n🎯 <b>跨策略高共识精选(Top {min(5, len(consensus))}/{len(consensus)})</b>"]
1352
+ for idx, c in enumerate(consensus[:5], start=1):
1353
+ risk_mark = " ⚠️" if c.get("announcement_risk_flags") else ""
1354
+ px = f" ¥{float(c['price']):.2f}" if c.get("price") is not None else ""
1355
+ chg = f" · {_fmt_report_pct(c.get('change_pct'))}" if c.get("change_pct") is not None else ""
1356
+ sc_txt = f" · {float(c['avg_final_score']):.1f}分" if c.get("avg_final_score") is not None else ""
1357
+ strats_cn = "·".join(_strategy_display_name(report, s) for s in (c.get("strategies") or [])[:2])
1358
+ c_lines.append(
1359
+ f"{idx}. <b>{esc(str(c.get('name', '')))}</b> <code>{esc(str(c.get('code', '')))}</code>{risk_mark}{esc(px)} · "
1360
+ f"{esc(str(c.get('industry') or '-'))} · <b>{int(c.get('strategy_count', 0))}策略</b>"
1361
+ + (f"({esc(strats_cn)})" if strats_cn else "")
1362
+ + f"{esc(sc_txt)}{esc(chg)}"
1363
+ )
1364
+ parts.append("\n".join(c_lines))
1365
+
1366
+ primary_pats, neg_pats = _split_hit_patterns(report)
1367
+ if primary_pats or neg_pats:
1368
+ p_lines = ["\n📡 <b>形态雷达触发</b>"]
1369
+ for p in (primary_pats or neg_pats)[:4]:
1370
+ tag = "active" if p.get("status") == "active" else "观察期"
1371
+ sigs = "、".join(
1372
+ f"{esc(str(s.get('name') or s.get('code')))} {esc(_fmt_report_pct(s.get('change_pct')))}"
1373
+ for s in (p.get("signals") or [])[:3]
1374
+ )
1375
+ p_lines.append(
1376
+ f"• <b>{esc(str(p.get('display_name') or p.get('pattern')))}</b>"
1377
+ f"({int(p.get('hit_count') or 0)}只 · {tag})" + (f":{sigs}" if sigs else "")
1378
+ )
1379
+ parts.append("\n".join(p_lines))
1380
+
1381
+ detail_url = _resolved_report_url(report)
1382
+ footer_lines: list[str] = []
1383
+ if detail_url:
1384
+ footer_lines.append(
1385
+ f'\n🔗 <a href="{esc(detail_url, quote=True)}">打开在线交互看板(20日K线 &amp; T+N验证)</a>'
1386
+ )
1387
+ footer_lines.append("<i>注:仅作量化形态观测与回测基准,不构成投资建议。</i>")
1388
+ tail = "\n".join(footer_lines)
1389
+
1390
+ body = "\n".join(parts)
1391
+ max_body = 4000 - len(tail) - 1
1392
+ if len(body) > max_body:
1393
+ kept: list[str] = []
1394
+ used = 0
1395
+ for block in parts:
1396
+ add = len(block) + (1 if kept else 0)
1397
+ if used + add <= max_body - 16:
1398
+ kept.append(block)
1399
+ used += add
1400
+ else:
1401
+ break
1402
+ body = "\n".join(kept) if kept else esc(str(report.get("trade_date", "")))
1403
+ return f"{body}\n{tail}"
1404
+
1405
+
1406
+ def _render_email_html(
1407
+ report: dict[str, Any] | None,
1408
+ content: str,
1409
+ *,
1410
+ title: str,
1411
+ ) -> str:
1412
+ esc = html_lib.escape
1413
+ font_stack = "-apple-system,BlinkMacSystemFont,'PingFang SC','Microsoft YaHei','Segoe UI',Roboto,Helvetica,Arial,sans-serif"
1414
+ mono_stack = "'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace"
1415
+
1416
+ if _has_market_digest(report):
1417
+ assert report is not None
1418
+ sections_m: list[str] = []
1419
+ for sec in (report.get("market_sections") or [])[:7]:
1420
+ m_name = str(sec.get("market_name") or str(sec.get("market") or "").upper())
1421
+ bench = str(sec.get("benchmark") or "")
1422
+ m_date = str(sec.get("trade_date") or "-")
1423
+ top_picks = sec.get("top_picks") or []
1424
+ if top_picks:
1425
+ rows_html = []
1426
+ for idx, p in enumerate(top_picks[:6], start=1):
1427
+ px_s = f"¥{float(p['price']):.2f}" if (sec.get("market") == "cn" and p.get("price") is not None) else (f"{float(p['price']):.2f}" if p.get("price") is not None else "–")
1428
+ cv = p.get("change_pct")
1429
+ ccol = "#DC2626" if (cv is not None and float(cv) > 0) else ("#059669" if (cv is not None and float(cv) < 0) else "#475569")
1430
+ strats = " · ".join(str(x) for x in (p.get("strategy_display_names") or p.get("strategies") or [])[:3])
1431
+ rows_html.append(
1432
+ f'<tr style="border-bottom:1px solid #F1F5F9;">'
1433
+ f'<td style="padding:7px 8px;font-size:12px;color:#64748B;font-family:{mono_stack};">{idx}</td>'
1434
+ f'<td style="padding:7px 8px;font-size:13px;color:#0F172A;"><strong>{esc(str(p.get("name") or p.get("code")))}</strong> '
1435
+ f'<code style="font-size:11px;color:#64748B;font-family:{mono_stack};">{esc(str(p.get("code", "")))}</code>'
1436
+ f'<div style="font-size:11px;color:#64748B;">{esc(str(p.get("industry") or "-"))} · {esc(strats)}</div></td>'
1437
+ f'<td style="padding:7px 8px;text-align:right;font-size:12px;font-family:{mono_stack};color:#0F172A;">{esc(px_s)}</td>'
1438
+ f'<td style="padding:7px 8px;text-align:right;font-size:12px;font-family:{mono_stack};color:#0F172A;">{float(p.get("avg_final_score") or 0):.1f}</td>'
1439
+ f'<td style="padding:7px 8px;text-align:right;font-size:12px;font-weight:700;font-family:{mono_stack};color:{ccol};">{esc(_fmt_report_pct(cv))}</td></tr>'
1440
+ )
1441
+ tbl = (
1442
+ '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">'
1443
+ '<thead><tr style="background:#F8FAFC;"><th style="padding:6px 8px;text-align:left;font-size:11px;color:#64748B;">#</th>'
1444
+ '<th style="padding:6px 8px;text-align:left;font-size:11px;color:#64748B;">标的 / 行业 / 策略</th>'
1445
+ '<th style="padding:6px 8px;text-align:right;font-size:11px;color:#64748B;">现价</th>'
1446
+ '<th style="padding:6px 8px;text-align:right;font-size:11px;color:#64748B;">得分</th>'
1447
+ '<th style="padding:6px 8px;text-align:right;font-size:11px;color:#64748B;">涨跌</th></tr></thead>'
1448
+ f'<tbody>{"".join(rows_html)}</tbody></table>'
1449
+ )
1450
+ else:
1451
+ tbl = '<div style="padding:12px;color:#64748B;font-size:12px;">今日该市场暂无入选候选。</div>'
1452
+ sections_m.append(
1453
+ f'<div style="border:1px solid #E2E8F0;border-radius:8px;overflow:hidden;margin-bottom:14px;">'
1454
+ f'<div style="padding:10px 14px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-size:13px;font-weight:700;color:#0F172A;">'
1455
+ f'🌍 {esc(m_name)} <span style="font-weight:500;font-size:12px;color:#64748B;">· {esc(bench)} · {esc(m_date)} · {int(sec.get("strategy_count") or 0)} 组策略</span></div>'
1456
+ f'{tbl}</div>'
1457
+ )
1458
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1459
+ if mnews:
1460
+ n_items = "".join(f'<li style="margin:4px 0;font-size:13px;color:#334155;">{esc(str(n.get("title") or ""))}</li>' for n in mnews[:5])
1461
+ sections_m.append(
1462
+ f'<div style="background:#F8FAFC;border:1px solid #E2E8F0;border-radius:8px;padding:12px 16px;margin-bottom:14px;">'
1463
+ f'<div style="font-size:13px;font-weight:700;color:#0F172A;margin-bottom:6px;">📰 市场热点快讯</div>'
1464
+ f'<ul style="margin:0;padding-left:18px;">{n_items}</ul></div>'
1465
+ )
1466
+ detail_url = _resolved_report_url(report)
1467
+ cta = (
1468
+ f'<div style="text-align:center;margin:18px 0 6px 0;"><a href="{esc(detail_url, quote=True)}" target="_blank" rel="noopener" '
1469
+ f'style="display:inline-block;background:#2563EB;color:#FFFFFF;text-decoration:none;font-size:14px;font-weight:700;padding:10px 22px;border-radius:8px;">打开在线交互看板与历史战绩</a></div>'
1470
+ if detail_url
1471
+ else ""
1472
+ )
1473
+ return (
1474
+ f'<!doctype html><html><body style="margin:0;padding:24px 12px;background:#F1F5F9;font-family:{font_stack};">'
1475
+ f'<div style="max-width:680px;margin:0 auto;background:#FFFFFF;border:1px solid #E2E8F0;border-radius:12px;overflow:hidden;">'
1476
+ f'<div style="background:#0F172A;color:#F8FAFC;padding:18px 24px;">'
1477
+ f'<div style="font-size:11px;letter-spacing:0.06em;color:#93C5FD;font-weight:700;">ALPHASIFT GLOBAL</div>'
1478
+ f'<div style="font-size:19px;font-weight:700;margin-top:4px;">{esc(title)}</div></div>'
1479
+ f'<div style="padding:20px 24px;">{"".join(sections_m)}{cta}</div>'
1480
+ f'<div style="padding:12px 24px;background:#F8FAFC;border-top:1px solid #E2E8F0;font-size:11px;color:#64748B;">AlphaSift · 开源量化选股与回测基准 · 非投资建议</div>'
1481
+ f'</div></body></html>'
1482
+ )
1483
+
1484
+ if not _has_rich_report(report):
1485
+ body_rows: list[str] = []
1486
+ for raw_line in content.splitlines():
1487
+ s = raw_line.strip()
1488
+ if not s:
1489
+ continue
1490
+ s_esc = esc(s)
1491
+ s_esc = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", s_esc)
1492
+ if s_esc.startswith("&gt; "):
1493
+ body_rows.append(
1494
+ f'<div style="background:#F8FAFC;border-left:3px solid #2563EB;padding:10px 14px;'
1495
+ f'margin:8px 0;border-radius:0 6px 6px 0;color:#334155;font-size:14px;line-height:1.6;">{s_esc[5:]}</div>'
1496
+ )
1497
+ else:
1498
+ body_rows.append(f'<p style="margin:6px 0;color:#1E293B;font-size:14px;line-height:1.65;">{s_esc}</p>')
1499
+ inner = "".join(body_rows) or f'<p style="margin:0;color:#334155;">{esc(content)}</p>'
1500
+ return (
1501
+ f'<!doctype html><html><body style="margin:0;padding:24px 12px;background:#F1F5F9;font-family:{font_stack};">'
1502
+ f'<div style="max-width:660px;margin:0 auto;background:#FFFFFF;border:1px solid #E2E8F0;border-radius:12px;overflow:hidden;">'
1503
+ f'<div style="background:#0F172A;color:#F8FAFC;padding:18px 24px;">'
1504
+ f'<div style="font-size:11px;letter-spacing:0.08em;color:#93C5FD;font-weight:700;text-transform:uppercase;">AlphaSift</div>'
1505
+ f'<div style="font-size:19px;font-weight:700;margin-top:4px;">{esc(title)}</div></div>'
1506
+ f'<div style="padding:20px 24px;">{inner}</div></div></body></html>'
1507
+ )
1508
+
1509
+ assert report is not None
1510
+ reg = report.get("market_regime") or {}
1511
+ stage = str(reg.get("regime_stage") or "")
1512
+ stage_lbl = str(reg.get("regime_stage_label") or "-")
1513
+ st_bg, st_fg, _ = _stage_palette(stage)
1514
+ adv = float(reg.get("advance_ratio_pct") or 0.0)
1515
+ adv_color = "#DC2626" if adv >= 50.0 else "#059669"
1516
+ med = reg.get("median_return_pct")
1517
+ med_str = _fmt_report_pct(med)
1518
+ seal = reg.get("seal_rate_pct")
1519
+ seal_str = "–" if seal is None else f"{float(seal):.1f}%"
1520
+ prev_ret = reg.get("prev_limit_up_avg_return_pct")
1521
+ prev_str = _fmt_report_pct(prev_ret)
1522
+ amt = reg.get("total_amount_yi")
1523
+ amt_str = "–" if amt is None else f"{float(amt):,.0f} 亿"
1524
+ dist = reg.get("return_distribution") or {}
1525
+ up_cnt = int(reg.get("up_count") or sum(int(dist.get(k) or 0) for k in ("pos0_3", "pos3_7", "ge_pos7")))
1526
+ flat_cnt = int(reg.get("flat_count") or int(dist.get("flat") or 0))
1527
+ down_cnt = int(reg.get("down_count") or sum(int(dist.get(k) or 0) for k in ("le_neg7", "neg7_neg3", "neg3_0")))
1528
+ lu_cnt = int(reg.get("non_st_limit_up_count") or 0)
1529
+ ld_cnt = int(reg.get("non_st_limit_down_count") or 0)
1530
+ max_streak = int(reg.get("max_consecutive_limit_up") or 0)
1531
+
1532
+ sections: list[str] = []
1533
+ if report.get("pack_is_stale"):
1534
+ sections.append(
1535
+ f'<div style="background:#FFFBEB;border:1px solid #FDE68A;border-left:4px solid #D97706;'
1536
+ f'border-radius:8px;padding:10px 14px;margin-bottom:16px;color:#92400E;font-size:13px;">'
1537
+ f'<strong>旧包降级提示:</strong>当前数据包日期 <code>{esc(str(report.get("pack_trade_date", "-")))}</code> '
1538
+ f'落后于目标交易日 <code>{esc(str(report.get("expected_trade_date", "-")))}</code>,仅供参考。</div>'
1539
+ )
1540
+
1541
+ # 4-card KPI grid
1542
+ kpi_cell = 'style="width:25%;padding:12px 10px;background:#F8FAFC;border:1px solid #E2E8F0;border-radius:8px;vertical-align:top;"'
1543
+ kpi_lbl = 'style="font-size:11px;color:#64748B;margin-bottom:4px;font-weight:600;"'
1544
+ kpi_sub = 'style="font-size:11px;color:#64748B;margin-top:4px;"'
1545
+ sections.append(
1546
+ '<table role="presentation" width="100%" cellspacing="6" cellpadding="0" style="border-collapse:separate;margin:0 -6px 14px -6px;"><tr>'
1547
+ f'<td {kpi_cell}><div {kpi_lbl}>上涨家数占比</div>'
1548
+ f'<div style="font-size:20px;font-weight:700;color:{adv_color};font-family:{mono_stack};">{adv:.1f}%</div>'
1549
+ f'<div {kpi_sub}>中位数 {esc(med_str)}</div></td>'
1550
+ f'<td {kpi_cell}><div {kpi_lbl}>非 ST 涨跌停</div>'
1551
+ f'<div style="font-size:20px;font-weight:700;color:#0F172A;font-family:{mono_stack};">'
1552
+ f'<span style="color:#DC2626;">{lu_cnt}</span> / <span style="color:#059669;">{ld_cnt}</span></div>'
1553
+ f'<div {kpi_sub}>封板率 {esc(seal_str)}</div></td>'
1554
+ f'<td {kpi_cell}><div {kpi_lbl}>连板高度</div>'
1555
+ f'<div style="font-size:20px;font-weight:700;color:#0F172A;font-family:{mono_stack};">{max_streak} 板</div>'
1556
+ f'<div {kpi_sub}>昨涨停 {esc(prev_str)}</div></td>'
1557
+ f'<td {kpi_cell}><div {kpi_lbl}>两市成交额</div>'
1558
+ f'<div style="font-size:19px;font-weight:700;color:#0F172A;font-family:{mono_stack};">{esc(amt_str)}</div>'
1559
+ f'<div {kpi_sub}>涨 {up_cnt:,} / 平 {flat_cnt:,} / 跌 {down_cnt:,}</div></td>'
1560
+ '</tr></table>'
1561
+ )
1562
+
1563
+ # 7-bucket return distribution + compact consecutive board ladder
1564
+ buckets = (
1565
+ ("le_neg7", "≤-7%", "#059669"),
1566
+ ("neg7_neg3", "-7~-3%", "#10B981"),
1567
+ ("neg3_0", "-3~0%", "#6EE7B7"),
1568
+ ("flat", "平", "#94A3B8"),
1569
+ ("pos0_3", "0~3%", "#FCA5A5"),
1570
+ ("pos3_7", "3~7%", "#F87171"),
1571
+ ("ge_pos7", "≥7%", "#DC2626"),
1572
+ )
1573
+ counts = [int(dist.get(k) or 0) for k, _, _ in buckets]
1574
+ max_b = max(1, *counts)
1575
+ b_cells = []
1576
+ for idx, (_, blbl, bcol) in enumerate(buckets):
1577
+ cnt = counts[idx]
1578
+ bh = max(3, int(round((cnt / max_b) * 34))) if cnt > 0 else 2
1579
+ b_cells.append(
1580
+ f'<td style="width:14.28%;text-align:center;vertical-align:bottom;padding:4px 2px;">'
1581
+ f'<div style="font-size:10px;color:#475569;font-family:{mono_stack};margin-bottom:3px;">{cnt}</div>'
1582
+ f'<div style="height:{bh}px;background:{bcol};border-radius:3px 3px 0 0;margin:0 6px;"></div>'
1583
+ f'<div style="font-size:10px;color:#64748B;border-top:1px solid #CBD5E1;padding-top:3px;">{blbl}</div>'
1584
+ f'</td>'
1585
+ )
1586
+ ladder_map = reg.get("consecutive_board_ladder") or {}
1587
+ ladder_items = (
1588
+ sorted(((int(k), int(v)) for k, v in ladder_map.items() if int(v or 0) > 0), reverse=True)
1589
+ if isinstance(ladder_map, dict)
1590
+ else []
1591
+ )
1592
+ ladder_html = ""
1593
+ if ladder_items:
1594
+ chips = " ".join(
1595
+ f'<span style="display:inline-block;background:#FFFFFF;border:1px solid #E2E8F0;border-radius:5px;'
1596
+ f'padding:2px 7px;margin:2px 4px 2px 0;font-size:11px;color:#334155;font-family:{mono_stack};">'
1597
+ f'<strong style="color:#DC2626;">{b}板</strong> {cnt}只</span>'
1598
+ for b, cnt in ladder_items[:6]
1599
+ )
1600
+ ladder_html = f'<div style="margin-top:8px;padding-top:7px;border-top:1px dashed #CBD5E1;font-size:11px;color:#475569;">连板梯队:{chips}</div>'
1601
+ sections.append(
1602
+ '<div style="background:#F8FAFC;border:1px solid #E2E8F0;border-radius:8px;padding:10px 12px;margin-bottom:16px;">'
1603
+ '<div style="font-size:12px;font-weight:700;color:#334155;margin-bottom:6px;">全 A 股涨跌分布(7 档)与连板梯队</div>'
1604
+ f'<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr>{"".join(b_cells)}</tr></table>'
1605
+ f'{ladder_html}</div>'
1606
+ )
1607
+
1608
+ # Alert-first Announcement Risk section with date & recency
1609
+ ann = report.get("announcement_risks") or {}
1610
+ flagged = ann.get("flagged_items") or []
1611
+ checked = int(ann.get("checked_count") or 0)
1612
+ if flagged:
1613
+ ann_rows = []
1614
+ for item in flagged[:6]:
1615
+ flags, d_tag, snip = _format_ann_meta(item)
1616
+ date_badge = (
1617
+ f'<span style="display:inline-block;background:#FFFFFF;border:1px solid #FCA5A5;color:#7F1D1D;'
1618
+ f'font-size:10px;padding:1px 5px;border-radius:4px;margin-left:4px;font-family:{mono_stack};">{esc(d_tag)}</span>'
1619
+ if d_tag
1620
+ else ""
1621
+ )
1622
+ ann_rows.append(
1623
+ f'<li style="margin:5px 0;font-size:13px;color:#7F1D1D;line-height:1.5;">'
1624
+ f'<strong>{esc(str(item.get("name", "")))}</strong> '
1625
+ f'<code style="font-family:{mono_stack};color:#991B1B;">{esc(str(item.get("code", "")))}</code>'
1626
+ f'{date_badge}'
1627
+ f'<span style="display:inline-block;background:#FEE2E2;color:#B91C1C;font-size:11px;font-weight:700;'
1628
+ f'padding:1px 6px;border-radius:4px;margin:0 5px;">{esc(flags)}</span>'
1629
+ + (f'<span style="color:#450A0A;">{esc(snip)}</span>' if snip else "")
1630
+ + '</li>'
1631
+ )
1632
+ sections.append(
1633
+ f'<div style="background:#FEF2F2;border:1px solid #FECACA;border-left:4px solid #DC2626;'
1634
+ f'border-radius:8px;padding:12px 16px;margin-bottom:16px;">'
1635
+ f'<div style="font-size:13px;font-weight:700;color:#991B1B;margin-bottom:6px;">'
1636
+ f'⚠️ 公告排雷预警(抽检 {checked} 只重点标的 · 命中 {len(flagged)} 只预警)</div>'
1637
+ f'<ul style="margin:0;padding-left:18px;">{"".join(ann_rows)}</ul></div>'
1638
+ )
1639
+ elif checked > 0:
1640
+ sections.append(
1641
+ f'<div style="background:#ECFDF5;border:1px solid #A7F3D0;border-left:4px solid #059669;'
1642
+ f'border-radius:8px;padding:10px 14px;margin-bottom:16px;color:#065F46;font-size:13px;">'
1643
+ f'<strong>✓ 公告排雷通过:</strong>已抽检 {checked} 只重点候选,未检出减持 / 立案 / 退市等实质性负面公告。</div>'
1644
+ )
1645
+
1646
+ # Post-Close Brief
1647
+ brief = report.get("ai_brief") or {}
1648
+ if brief.get("headline"):
1649
+ is_ai = brief.get("mode") == "llm"
1650
+ mod_txt = f" · {esc(str(brief.get('model')))}" if is_ai and brief.get("model") else ""
1651
+ lbl = f"🤖 AI 盘后综述{mod_txt}" if is_ai else "📌 盘后盘面摘要"
1652
+ accent = "#2563EB" if is_ai else "#475569"
1653
+ extra_paras = []
1654
+ for k in ("market_summary", "consensus_and_ai_edge", "regime_interpretation", "risk_focus"):
1655
+ val = str(brief.get(k) or "").strip()
1656
+ if val:
1657
+ extra_paras.append(f'<p style="margin:5px 0 0 0;font-size:13px;color:#334155;line-height:1.6;">{esc(val)}</p>')
1658
+ watch = [str(w).strip() for w in (brief.get("watch_points") or []) if str(w).strip()][:3]
1659
+ if watch:
1660
+ w_items = "".join(f'<li style="margin:2px 0;">{esc(w)}</li>' for w in watch)
1661
+ extra_paras.append(
1662
+ f'<ul style="margin:6px 0 0 0;padding-left:18px;font-size:12px;color:#475569;line-height:1.55;">{w_items}</ul>'
1663
+ )
1664
+ sections.append(
1665
+ f'<div style="background:#F8FAFC;border:1px solid #E2E8F0;border-left:4px solid {accent};'
1666
+ f'border-radius:8px;padding:12px 16px;margin-bottom:16px;">'
1667
+ f'<div style="font-size:12px;font-weight:700;color:{accent};margin-bottom:4px;">{lbl}</div>'
1668
+ f'<div style="font-size:14px;font-weight:700;color:#0F172A;line-height:1.5;">{esc(str(brief["headline"]).strip())}</div>'
1669
+ f'{"".join(extra_paras)}</div>'
1670
+ )
1671
+
1672
+ # Market News section
1673
+ mnews = ((report.get("market_news") or {}).get("items") or []) if isinstance(report.get("market_news"), dict) else []
1674
+ if mnews:
1675
+ nsrc = " · ".join(str(s) for s in ((report.get("market_news") or {}).get("sources") or []) if s)
1676
+ n_rows = []
1677
+ for item in mnews[:5]:
1678
+ cat = str(item.get("category") or "要闻")
1679
+ pub = str(item.get("published_at") or "")
1680
+ src = str(item.get("source") or "")
1681
+ n_rows.append(
1682
+ f'<li style="margin:5px 0;font-size:13px;color:#1E293B;line-height:1.5;">'
1683
+ f'<span style="display:inline-block;background:#E0F2FE;color:#0369A1;font-size:10px;font-weight:700;'
1684
+ f'padding:1px 6px;border-radius:4px;margin-right:6px;">{esc(cat)}</span>'
1685
+ f'{esc(str(item.get("title") or ""))}'
1686
+ f'<span style="font-size:11px;color:#64748B;margin-left:6px;">{esc(src)} {esc(pub)}</span></li>'
1687
+ )
1688
+ sections.append(
1689
+ '<div style="border:1px solid #E2E8F0;border-radius:8px;padding:12px 16px;margin-bottom:16px;background:#FFFFFF;">'
1690
+ '<div style="font-size:13px;font-weight:700;color:#0F172A;margin-bottom:6px;">'
1691
+ '📰 市场热点与政策快讯'
1692
+ + (f' <span style="font-size:11px;font-weight:500;color:#64748B;">· {esc(nsrc)}</span>' if nsrc else "")
1693
+ + f'</div><ul style="margin:0;padding-left:18px;">{"".join(n_rows)}</ul></div>'
1694
+ )
1695
+
1696
+ # Multi-Strategy Consensus Table with Chinese names, valuation, and reasons/news
1697
+ syn = report.get("cross_strategy_synthesis") or {}
1698
+ consensus = syn.get("consensus_picks") or []
1699
+ track_stats = report.get("strategy_track_stats") if isinstance(report.get("strategy_track_stats"), dict) else {}
1700
+ if consensus:
1701
+ th_css = 'style="padding:8px;text-align:left;font-size:11px;color:#64748B;border-bottom:1px solid #E2E8F0;background:#F8FAFC;"'
1702
+ th_r = 'style="padding:8px 6px;text-align:right;font-size:11px;color:#64748B;border-bottom:1px solid #E2E8F0;background:#F8FAFC;white-space:nowrap;"'
1703
+ c_rows = []
1704
+ for idx, c in enumerate(consensus[:6], start=1):
1705
+ chg_v = c.get("change_pct")
1706
+ chg_col = "#DC2626" if (chg_v is not None and float(chg_v) > 0) else ("#059669" if (chg_v is not None and float(chg_v) < 0) else "#475569")
1707
+ sc_v = "–" if c.get("avg_final_score") is None else f"{float(c['avg_final_score']):.1f}"
1708
+ px_v = "–" if c.get("price") is None else f"¥{float(c['price']):.2f}"
1709
+ strats_cn = " · ".join(_strategy_display_name(report, x) for x in (c.get("strategies") or [])[:3])
1710
+ val_bits = []
1711
+ if c.get("pe_ratio") is not None:
1712
+ val_bits.append(f"PE {float(c['pe_ratio']):.1f}")
1713
+ if c.get("pb_ratio") is not None:
1714
+ val_bits.append(f"PB {float(c['pb_ratio']):.2f}")
1715
+ if c.get("market_cap_yi") is not None:
1716
+ val_bits.append(f"{float(c['market_cap_yi']):.0f}亿")
1717
+ val_txt = f" · {' · '.join(val_bits)}" if val_bits else ""
1718
+ extra_sub = ""
1719
+ if c.get("reasons"):
1720
+ extra_sub += f'<div style="font-size:11px;color:#475569;margin-top:2px;">理由:{esc(str(c["reasons"][0])[:64])}</div>'
1721
+ if c.get("news_headline"):
1722
+ extra_sub += f'<div style="font-size:11px;color:#0369A1;margin-top:1px;">动态:{esc(str(c["news_headline"])[:56])}</div>'
1723
+ risk_badge = ' <span style="background:#FEE2E2;color:#DC2626;font-size:10px;padding:1px 4px;border-radius:3px;">公告预警</span>' if c.get("announcement_risk_flags") else ""
1724
+ c_rows.append(
1725
+ f'<tr style="border-bottom:1px solid #F1F5F9;">'
1726
+ f'<td style="padding:8px;font-size:12px;color:#64748B;font-family:{mono_stack};vertical-align:top;">{idx}</td>'
1727
+ f'<td style="padding:8px;font-size:13px;color:#0F172A;vertical-align:top;"><strong>{esc(str(c.get("name", "")))}</strong> '
1728
+ f'<code style="font-size:11px;color:#64748B;font-family:{mono_stack};">{esc(str(c.get("code", "")))}</code>{risk_badge}'
1729
+ f'<div style="font-size:11px;color:#64748B;margin-top:2px;">{esc(str(c.get("industry") or "-"))}{esc(val_txt)} · {esc(strats_cn)}</div>{extra_sub}</td>'
1730
+ f'<td style="padding:8px 6px;text-align:right;font-size:12px;font-family:{mono_stack};color:#0F172A;vertical-align:top;white-space:nowrap;">{px_v}</td>'
1731
+ f'<td style="padding:8px 6px;text-align:right;font-size:12px;vertical-align:top;white-space:nowrap;"><span style="display:inline-block;background:#EFF6FF;color:#1D4ED8;font-weight:700;padding:2px 7px;border-radius:999px;white-space:nowrap;">{int(c.get("strategy_count", 0))} 策略</span></td>'
1732
+ f'<td style="padding:8px 6px;text-align:right;font-size:12px;font-family:{mono_stack};color:#0F172A;vertical-align:top;white-space:nowrap;">{sc_v}</td>'
1733
+ f'<td style="padding:8px 6px;text-align:right;font-size:12px;font-weight:700;font-family:{mono_stack};color:{chg_col};vertical-align:top;white-space:nowrap;">{esc(_fmt_report_pct(chg_v))}</td>'
1734
+ f'</tr>'
1735
+ )
1736
+ sections.append(
1737
+ f'<div style="border:1px solid #E2E8F0;border-radius:8px;overflow:hidden;margin-bottom:16px;">'
1738
+ f'<div style="padding:10px 14px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-size:13px;font-weight:700;color:#0F172A;">'
1739
+ f'🎯 跨策略高共识精选(共 {len(consensus)} 只,展示 Top {min(6, len(consensus))})</div>'
1740
+ f'<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">'
1741
+ f'<thead><tr><th {th_css}>#</th><th {th_css}>标的 / 估值 / 命中策略与理由</th><th {th_r}>现价</th><th {th_r}>共振度</th><th {th_r}>均分</th><th {th_r}>今日涨跌</th></tr></thead>'
1742
+ f'<tbody>{"".join(c_rows)}</tbody></table></div>'
1743
+ )
1744
+
1745
+ # Compact Strategy Picks Grid with Chinese names + historical T+5 track record
1746
+ strategies_list = [s for s in (report.get("strategies") or []) if isinstance(s, dict) and (s.get("picks") or [])]
1747
+ if strategies_list:
1748
+ s_cards: list[str] = []
1749
+ for st in strategies_list[:10]:
1750
+ skey = str(st.get("strategy") or "")
1751
+ sname = _strategy_display_name(report, skey)
1752
+ tr_badge = '<span style="background:#EFF6FF;color:#1D4ED8;font-size:10px;padding:1px 5px;border-radius:4px;margin-left:5px;">AI</span>' if (st.get("track") == "ai" or st.get("llm_ranked")) else ""
1753
+ ts = track_stats.get(skey) or {}
1754
+ ts_badge = (
1755
+ f'<span style="font-size:11px;color:#475569;float:right;font-family:{mono_stack};">T+5 {float(ts["t5_avg_excess_pct"]):+.2f}%</span>'
1756
+ if ts.get("t5_avg_excess_pct") is not None
1757
+ else ""
1758
+ )
1759
+ top2 = " · ".join(
1760
+ f"<strong>{esc(str(pk.get('name') or pk.get('code')))}</strong> "
1761
+ f"<span style=\"color:#64748B;font-size:11px;font-family:{mono_stack};\">{esc(str(pk.get('code') or ''))}</span> "
1762
+ f"<span style=\"color:#475569;font-size:11px;font-family:{mono_stack};\">{esc(_fmt_report_pct(pk.get('change_pct')))}</span>"
1763
+ for pk in (st.get("picks") or [])[:3]
1764
+ )
1765
+ s_cards.append(
1766
+ f'<div style="padding:7px 12px;border-bottom:1px solid #F1F5F9;font-size:12px;">'
1767
+ f'<div style="font-weight:700;color:#0F172A;margin-bottom:2px;">{esc(sname)}{tr_badge}{ts_badge}</div>'
1768
+ f'<div style="color:#334155;">{top2}</div></div>'
1769
+ )
1770
+ sections.append(
1771
+ f'<div style="border:1px solid #E2E8F0;border-radius:8px;overflow:hidden;margin-bottom:16px;">'
1772
+ f'<div style="padding:9px 14px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-size:13px;font-weight:700;color:#0F172A;">'
1773
+ f'🧭 今日策略精选速览({len(strategies_list)} 组)</div>'
1774
+ f'{"".join(s_cards)}</div>'
1775
+ )
1776
+
1777
+ # Pattern Radar Cards tiered by replay expectancy
1778
+ primary_pats, neg_pats = _split_hit_patterns(report)
1779
+ shown_pats = primary_pats or neg_pats
1780
+ if shown_pats:
1781
+ pat_blocks = []
1782
+ for p in shown_pats[:5]:
1783
+ is_act = p.get("status") == "active"
1784
+ badge_bg, badge_fg, badge_txt = ("#ECFDF5", "#059669", "active") if is_act else ("#FFFBEB", "#B45309", "观察期")
1785
+ net_ex = p.get("replay_t5_net_excess_pct")
1786
+ net_txt = f" · T+5净超额 {float(net_ex):+.2f}%" if net_ex is not None else ""
1787
+ sig_rows = []
1788
+ for s in (p.get("signals") or [])[:4]:
1789
+ cv = s.get("change_pct")
1790
+ ccol = "#DC2626" if (cv is not None and float(cv) > 0) else ("#059669" if (cv is not None and float(cv) < 0) else "#475569")
1791
+ ov = "–" if s.get("overhead_supply_10pct") is None else f"{float(s['overhead_supply_10pct']):.0f}%"
1792
+ sig_rows.append(
1793
+ f'<tr><td style="width:46%;padding:6px 12px;font-size:12px;color:#0F172A;"><strong>{esc(str(s.get("name") or s.get("code")))}</strong> '
1794
+ f'<code style="color:#64748B;font-size:11px;font-family:{mono_stack};">{esc(str(s.get("code", "")))}</code></td>'
1795
+ f'<td style="width:24%;padding:6px 10px;text-align:right;font-size:12px;font-family:{mono_stack};color:{ccol};font-weight:600;">{esc(_fmt_report_pct(cv))}</td>'
1796
+ f'<td style="width:30%;padding:6px 12px;text-align:right;font-size:12px;font-family:{mono_stack};color:#64748B;">上方筹码 {esc(ov)}</td></tr>'
1797
+ )
1798
+ pat_blocks.append(
1799
+ f'<div style="border:1px solid #E2E8F0;border-radius:8px;margin-bottom:10px;overflow:hidden;">'
1800
+ f'<div style="padding:8px 12px;background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-size:13px;">'
1801
+ f'<strong style="color:#0F172A;">{esc(str(p.get("display_name") or p.get("pattern")))}</strong> '
1802
+ f'<span style="display:inline-block;background:{badge_bg};color:{badge_fg};font-size:11px;font-weight:700;padding:1px 7px;border-radius:999px;margin-left:6px;">{badge_txt} · {int(p.get("hit_count") or 0)}只{esc(net_txt)}</span>'
1803
+ f'</div>'
1804
+ f'<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">{"".join(sig_rows)}</table></div>'
1805
+ )
1806
+ neg_note = ""
1807
+ if primary_pats and neg_pats:
1808
+ neg_desc = "、".join(
1809
+ f"{p.get('display_name') or p.get('pattern')}({int(p.get('hit_count') or 0)}只, {float(p['replay_t5_net_excess_pct']):+.2f}%)"
1810
+ if p.get("replay_t5_net_excess_pct") is not None
1811
+ else f"{p.get('display_name') or p.get('pattern')}({int(p.get('hit_count') or 0)}只)"
1812
+ for p in neg_pats
1813
+ )
1814
+ neg_note = f'<div style="font-size:11px;color:#64748B;margin-top:4px;">历史回放负期望观察期触发(仅作对照):{esc(neg_desc)}</div>'
1815
+ sections.append(
1816
+ '<div style="margin-bottom:16px;">'
1817
+ '<div style="font-size:13px;font-weight:700;color:#0F172A;margin-bottom:8px;">'
1818
+ '📡 A 股无状态形态雷达(按 25bp/NW 实证期望分层)</div>'
1819
+ f'{"".join(pat_blocks)}{neg_note}</div>'
1820
+ )
1821
+
1822
+ detail_url = _resolved_report_url(report)
1823
+ cta_html = (
1824
+ f'<div style="text-align:center;margin:20px 0 8px 0;">'
1825
+ f'<a href="{esc(detail_url, quote=True)}" target="_blank" rel="noopener" '
1826
+ f'style="display:inline-block;background:#2563EB;color:#FFFFFF;text-decoration:none;'
1827
+ f'font-size:14px;font-weight:700;padding:11px 24px;border-radius:8px;">'
1828
+ f'打开在线交互看板(20日K线 &amp; T+N 实盘验证)</a></div>'
1829
+ if detail_url
1830
+ else ""
1831
+ )
1832
+
1833
+ return (
1834
+ f'<!doctype html><html><body style="margin:0;padding:24px 12px;background:#F1F5F9;font-family:{font_stack};">'
1835
+ f'<div style="max-width:660px;margin:0 auto;background:#FFFFFF;border:1px solid #E2E8F0;border-radius:12px;overflow:hidden;">'
1836
+ f'<div style="background:#0F172A;color:#F8FAFC;padding:20px 24px;">'
1837
+ f'<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr>'
1838
+ f'<td><span style="display:inline-block;background:#1E293B;color:#93C5FD;font-size:11px;font-weight:700;'
1839
+ f'letter-spacing:0.06em;padding:3px 9px;border-radius:999px;">ALPHASIFT</span>'
1840
+ f'<div style="font-size:20px;font-weight:700;margin-top:8px;">A 股盘后定量观测日报</div>'
1841
+ f'<div style="font-size:12px;color:#94A3B8;margin-top:3px;">交易日 {esc(str(report.get("trade_date", "-")))} · 规则筛选 + 公告排雷 + 快讯催化 + 形态雷达</div></td>'
1842
+ f'<td style="text-align:right;vertical-align:top;"><span style="display:inline-block;background:{st_bg};color:{st_fg};'
1843
+ f'font-size:12px;font-weight:700;padding:5px 12px;border-radius:999px;">盘面 · {esc(stage_lbl)}</span></td>'
1844
+ f'</tr></table></div>'
1845
+ f'<div style="padding:20px 24px;">{"".join(sections)}{cta_html}</div>'
1846
+ f'<div style="padding:12px 24px;background:#F8FAFC;border-top:1px solid #E2E8F0;font-size:11px;color:#64748B;line-height:1.5;">'
1847
+ f'<strong>AlphaSift</strong> · 开源量化形态观测与 T+N 回测基准(Apache-2.0)· 历史统计不含分红,不构成投资建议。</div>'
1848
+ f'</div></body></html>'
1849
+ )
1850
+
1851
+
1852
+ def _send_feishu(
1853
+ webhook_url: str,
1854
+ content: str,
1855
+ *,
1856
+ title: str,
1857
+ secret: str = "",
1858
+ report: dict[str, Any] | None = None,
1859
+ timeout_sec: float,
1860
+ post_fn=requests.post,
1861
+ ) -> None:
1862
+ body: dict[str, Any] = {
1863
+ "msg_type": "interactive",
1864
+ "card": _build_feishu_card(report, content, title=title),
1865
+ }
1866
+ if secret:
1867
+ ts = int(time.time())
1868
+ body["timestamp"] = str(ts)
1869
+ body["sign"] = _feishu_sign(ts, secret)
1870
+ resp = _post_with_retry(post_fn, webhook_url, json=body, timeout=timeout_sec)
1871
+ payload = _safe_json(resp)
1872
+ code = payload.get("code", payload.get("StatusCode", -1))
1873
+ if int(code) != 0:
1874
+ raise RuntimeError(f"feishu code={code} msg={payload.get('msg', payload.get('StatusMessage', ''))}")
1875
+
1876
+
1877
+ def _send_dingtalk(
1878
+ webhook_url: str,
1879
+ content: str,
1880
+ *,
1881
+ title: str,
1882
+ secret: str = "",
1883
+ report: dict[str, Any] | None = None,
1884
+ timeout_sec: float,
1885
+ post_fn=requests.post,
1886
+ ) -> None:
1887
+ target = webhook_url
1888
+ if secret:
1889
+ ts_ms = int(time.time() * 1000)
1890
+ sep = "&" if "?" in webhook_url else "?"
1891
+ target = f"{webhook_url}{sep}timestamp={ts_ms}&sign={_dingtalk_sign(ts_ms, secret)}"
1892
+ md_text = _render_markdown_digest(report, content, title=title, wecom_colors=False)
1893
+ resp = _post_with_retry(
1894
+ post_fn,
1895
+ target,
1896
+ json={"msgtype": "markdown", "markdown": {"title": title, "text": md_text}},
1897
+ timeout=timeout_sec,
1898
+ )
1899
+ payload = _safe_json(resp)
1900
+ if int(payload.get("errcode", -1)) != 0:
1901
+ raise RuntimeError(f"dingtalk errcode={payload.get('errcode')} errmsg={payload.get('errmsg', '')}")
1902
+
1903
+
1904
+ def _send_pushplus(
1905
+ token: str,
1906
+ content: str,
1907
+ *,
1908
+ title: str,
1909
+ topic: str = "",
1910
+ report: dict[str, Any] | None = None,
1911
+ timeout_sec: float,
1912
+ post_fn=requests.post,
1913
+ ) -> None:
1914
+ md_text = _render_markdown_digest(report, content, title=title, wecom_colors=False)
1915
+ body: dict[str, Any] = {
1916
+ "token": token,
1917
+ "title": title[:100],
1918
+ "content": md_text,
1919
+ "template": "markdown",
1920
+ }
1921
+ if topic:
1922
+ body["topic"] = topic
1923
+ resp = _post_with_retry(post_fn, "https://www.pushplus.plus/send", json=body, timeout=timeout_sec)
1924
+ payload = _safe_json(resp)
1925
+ if int(payload.get("code", -1)) != 200:
1926
+ raise RuntimeError(f"pushplus code={payload.get('code')} msg={payload.get('msg', '')}")
1927
+
1928
+
1929
+ def _send_serverchan(
1930
+ sendkey_or_url: str,
1931
+ content: str,
1932
+ *,
1933
+ title: str,
1934
+ report: dict[str, Any] | None = None,
1935
+ timeout_sec: float,
1936
+ post_fn=requests.post,
1937
+ ) -> None:
1938
+ if sendkey_or_url.startswith(("http://", "https://")):
1939
+ url = sendkey_or_url
1940
+ else:
1941
+ match = _SCTP_PATTERN.match(sendkey_or_url)
1942
+ if match:
1943
+ url = f"https://{match.group(1)}.push.ft07.com/send/{sendkey_or_url}.send"
1944
+ else:
1945
+ url = f"https://sctapi.ftqq.com/{sendkey_or_url}.send"
1946
+ md_text = _render_markdown_digest(report, content, title=title, wecom_colors=False)
1947
+ resp = _post_with_retry(
1948
+ post_fn,
1949
+ url,
1950
+ json={"title": title[:32], "desp": md_text},
1951
+ timeout=timeout_sec,
1952
+ )
1953
+ payload = _safe_json(resp)
1954
+ if int(payload.get("code", -1)) != 0:
1955
+ raise RuntimeError(f"serverchan code={payload.get('code')} msg={payload.get('message', payload.get('info', ''))}")
1956
+
1957
+
1958
+ def _send_bark(
1959
+ bark_url: str,
1960
+ content: str,
1961
+ *,
1962
+ title: str,
1963
+ detail_url: str = "",
1964
+ timeout_sec: float,
1965
+ post_fn=requests.post,
1966
+ ) -> None:
1967
+ target = bark_url if bark_url.startswith(("http://", "https://")) else f"https://api.day.app/{bark_url.strip('/')}"
1968
+ body: dict[str, Any] = {"title": title[:120], "body": content, "group": "AlphaSift"}
1969
+ if detail_url:
1970
+ body["url"] = detail_url
1971
+ resp = _post_with_retry(post_fn, target, json=body, timeout=timeout_sec)
1972
+ payload = _safe_json(resp)
1973
+ if int(payload.get("code", 200)) != 200:
1974
+ raise RuntimeError(f"bark code={payload.get('code')} msg={payload.get('message', '')}")
1975
+
1976
+
1977
+ def _send_telegram(
1978
+ bot_token: str,
1979
+ chat_id: str,
1980
+ content: str,
1981
+ *,
1982
+ title: str = "",
1983
+ report: dict[str, Any] | None = None,
1984
+ timeout_sec: float,
1985
+ post_fn=requests.post,
1986
+ ) -> None:
1987
+ url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
1988
+ html_text = _render_telegram_html(report, content, title=title or "AlphaSift")
1989
+ resp = _post_with_retry(
1990
+ post_fn,
1991
+ url,
1992
+ json={
1993
+ "chat_id": chat_id,
1994
+ "text": html_text,
1995
+ "parse_mode": "HTML",
1996
+ "disable_web_page_preview": True,
1997
+ },
1998
+ timeout=timeout_sec,
1999
+ )
2000
+ payload = _safe_json(resp)
2001
+ if payload.get("ok") is not True:
2002
+ desc = str(payload.get("description") or "")
2003
+ if "parse" in desc.lower() or "entity" in desc.lower() or "entities" in desc.lower():
2004
+ resp2 = _post_with_retry(
2005
+ post_fn,
2006
+ url,
2007
+ json={"chat_id": chat_id, "text": content, "disable_web_page_preview": True},
2008
+ timeout=timeout_sec,
2009
+ )
2010
+ payload2 = _safe_json(resp2)
2011
+ if payload2.get("ok") is True:
2012
+ return
2013
+ raise RuntimeError(f"telegram error={payload2.get('description', 'unknown')}")
2014
+ raise RuntimeError(f"telegram error={desc or 'unknown'}")
2015
+
2016
+
2017
+ def _build_discord_embed(
2018
+ report: dict[str, Any] | None,
2019
+ content: str,
2020
+ *,
2021
+ title: str,
2022
+ detail_url: str = "",
2023
+ ) -> dict[str, Any]:
2024
+ if not _has_rich_report(report) and not _has_market_digest(report):
2025
+ embed: dict[str, Any] = {"title": title[:256], "description": content[:4096], "color": 3899638}
2026
+ if detail_url:
2027
+ embed["url"] = detail_url
2028
+ return embed
2029
+
2030
+ assert report is not None
2031
+ fields: list[dict[str, Any]] = []
2032
+ if _has_rich_report(report):
2033
+ reg = report.get("market_regime") or {}
2034
+ stage = str(reg.get("regime_stage") or "")
2035
+ color = 14431557 if stage in {"freezing", "ebb"} else (380259 if stage in {"startup", "main_up"} else 14251526)
2036
+ fields.append({
2037
+ "name": f"盘面 · {reg.get('regime_stage_label', '-')}",
2038
+ "value": (
2039
+ f"上涨 {float(reg.get('advance_ratio_pct') or 0):.1f}% · 中位 {_fmt_report_pct(reg.get('median_return_pct'))}\n"
2040
+ f"涨跌停 {int(reg.get('non_st_limit_up_count') or 0)}/{int(reg.get('non_st_limit_down_count') or 0)} · 最高 {int(reg.get('max_consecutive_limit_up') or 0)}板"
2041
+ ),
2042
+ "inline": False,
2043
+ })
2044
+ flagged = ((report.get("announcement_risks") or {}).get("flagged_items")) or []
2045
+ if flagged:
2046
+ color = 14431557
2047
+ ann_txt = "\n".join(
2048
+ f"• `{x.get('code')}` {x.get('name')} [{_format_ann_meta(x)[0]}]"
2049
+ for x in flagged[:4]
2050
+ )
2051
+ fields.append({"name": f"⚠️ 公告排雷 ({len(flagged)})", "value": ann_txt[:1024], "inline": False})
2052
+ syn = report.get("cross_strategy_synthesis") or {}
2053
+ consensus = syn.get("consensus_picks") or []
2054
+ if consensus:
2055
+ c_txt = "\n".join(
2056
+ f"• **{c.get('name')}** `{c.get('code')}` ({c.get('strategy_count')}策略 · {_fmt_report_pct(c.get('change_pct'))})"
2057
+ for c in consensus[:5]
2058
+ )
2059
+ fields.append({"name": "🎯 跨策略共识", "value": c_txt[:1024], "inline": False})
2060
+ desc = str(((report.get("ai_brief") or {}).get("headline")) or content[:300])[:4096]
2061
+ else:
2062
+ color = 2461419
2063
+ desc = f"Global Digest · {report.get('trade_date', '-')}"
2064
+ for sec in (report.get("market_sections") or [])[:5]:
2065
+ top = ", ".join(f"{p.get('code')}({p.get('avg_final_score'):.0f})" for p in (sec.get("top_picks") or [])[:3])
2066
+ fields.append({"name": str(sec.get("market_name") or sec.get("market")), "value": top or "暂无候选", "inline": True})
2067
+
2068
+ embed = {
2069
+ "title": title[:256],
2070
+ "description": desc,
2071
+ "color": color,
2072
+ "fields": fields[:6],
2073
+ "footer": {"text": "AlphaSift · Quantitative Discovery & Benchmark"},
2074
+ }
2075
+ if detail_url:
2076
+ embed["url"] = detail_url
2077
+ return embed
2078
+
2079
+
2080
+ def _send_discord(
2081
+ webhook_url: str,
2082
+ content: str,
2083
+ *,
2084
+ title: str,
2085
+ detail_url: str = "",
2086
+ report: dict[str, Any] | None = None,
2087
+ timeout_sec: float,
2088
+ post_fn=requests.post,
2089
+ ) -> None:
2090
+ embed = _build_discord_embed(report, content, title=title, detail_url=detail_url)
2091
+ _post_with_retry(post_fn, webhook_url, json={"content": "", "embeds": [embed]}, timeout=timeout_sec)
2092
+
2093
+
2094
+ def _send_slack(
2095
+ webhook_url: str,
2096
+ content: str,
2097
+ *,
2098
+ title: str,
2099
+ report: dict[str, Any] | None = None,
2100
+ timeout_sec: float,
2101
+ post_fn=requests.post,
2102
+ ) -> None:
2103
+ if not _has_rich_report(report) and not _has_market_digest(report):
2104
+ _post_with_retry(post_fn, webhook_url, json={"text": f"*{title}*\n{content}"}, timeout=timeout_sec)
2105
+ return
2106
+ md_text = _render_markdown_digest(report, content, title=title, wecom_colors=False)
2107
+ blocks: list[dict[str, Any]] = [
2108
+ {"type": "header", "text": {"type": "plain_text", "text": title[:150]}},
2109
+ {"type": "section", "text": {"type": "mrkdwn", "text": md_text[:2950]}},
2110
+ ]
2111
+ assert report is not None
2112
+ detail_url = _resolved_report_url(report)
2113
+ if detail_url:
2114
+ blocks.append({
2115
+ "type": "actions",
2116
+ "elements": [{
2117
+ "type": "button",
2118
+ "text": {"type": "plain_text", "text": "Open Dashboard"},
2119
+ "url": detail_url,
2120
+ }],
2121
+ })
2122
+ _post_with_retry(post_fn, webhook_url, json={"text": f"*{title}*\n{content}", "blocks": blocks}, timeout=timeout_sec)
2123
+
2124
+
2125
+ def _send_ntfy(
2126
+ ntfy_url: str,
2127
+ content: str,
2128
+ *,
2129
+ title: str,
2130
+ detail_url: str = "",
2131
+ timeout_sec: float,
2132
+ post_fn=requests.post,
2133
+ ) -> None:
2134
+ headers = {"Title": _ntfy_ascii_title(title)}
2135
+ if detail_url:
2136
+ headers["Click"] = detail_url
2137
+ _post_with_retry(post_fn, ntfy_url, data=content.encode("utf-8"), headers=headers, timeout=timeout_sec)
2138
+
2139
+
2140
+ def _resolve_smtp_settings(sender: str, smtp_host: str = "", smtp_port: int = 0) -> tuple[str, int, str]:
2141
+ domain = sender.rsplit("@", 1)[-1].lower().strip() if "@" in sender else ""
2142
+ default_host, default_port, default_mode = _SMTP_DEFAULTS.get(
2143
+ domain,
2144
+ (f"smtp.{domain}" if domain else "", 465, "ssl"),
2145
+ )
2146
+ host = smtp_host or default_host
2147
+ if not host:
2148
+ raise ValueError("Email SMTP host could not be inferred; set EMAIL_SMTP_HOST or mailto://user:pass@smtp.example.com")
2149
+ port = smtp_port or default_port
2150
+ mode = "starttls" if port == 587 else ("ssl" if port == 465 else default_mode)
2151
+ return host, port, mode
2152
+
2153
+
2154
+ def _send_email(
2155
+ sender: str,
2156
+ password: str,
2157
+ receivers: Sequence[str],
2158
+ content: str,
2159
+ *,
2160
+ title: str,
2161
+ report: dict[str, Any] | None = None,
2162
+ smtp_host: str = "",
2163
+ smtp_port: int = 0,
2164
+ timeout_sec: float = 10.0,
2165
+ smtp_factory=None,
2166
+ ) -> None:
2167
+ host, port, mode = _resolve_smtp_settings(sender, smtp_host, smtp_port)
2168
+ recips = [r.strip() for r in receivers if r.strip()] or [sender]
2169
+ msg = EmailMessage()
2170
+ msg["Subject"] = title
2171
+ msg["From"] = sender if "<" in sender else formataddr(("AlphaSift 量化日报", sender))
2172
+ msg["To"] = ", ".join(recips)
2173
+ msg.set_content(content, charset="utf-8")
2174
+ html_body = _render_email_html(report, content, title=title)
2175
+ msg.add_alternative(html_body, subtype="html", charset="utf-8")
2176
+
2177
+ if smtp_factory is not None:
2178
+ client = smtp_factory(host, port, mode=mode, timeout=timeout_sec)
2179
+ try:
2180
+ if hasattr(client, "login"):
2181
+ client.login(sender, password)
2182
+ client.send_message(msg)
2183
+ finally:
2184
+ if hasattr(client, "quit"):
2185
+ client.quit()
2186
+ return
2187
+
2188
+ if mode == "starttls":
2189
+ with smtplib.SMTP(host, port, timeout=timeout_sec) as server:
2190
+ server.ehlo()
2191
+ server.starttls(context=ssl.create_default_context())
2192
+ server.ehlo()
2193
+ server.login(sender, password)
2194
+ server.send_message(msg)
2195
+ else:
2196
+ with smtplib.SMTP_SSL(host, port, timeout=timeout_sec, context=ssl.create_default_context()) as server:
2197
+ server.login(sender, password)
2198
+ server.send_message(msg)
2199
+
2200
+
2201
+ def _send_custom_webhook(
2202
+ webhook_url: str,
2203
+ *,
2204
+ report: dict[str, Any],
2205
+ content: str,
2206
+ title: str,
2207
+ token: str = "",
2208
+ timeout_sec: float,
2209
+ post_fn=requests.post,
2210
+ ) -> None:
2211
+ syn = report.get("cross_strategy_synthesis") or {}
2212
+ ann = report.get("announcement_risks") or {}
2213
+ payload: dict[str, Any] = {
2214
+ "event": str(report.get("event") or "alphasift.daily_report"),
2215
+ "trade_date": report.get("trade_date"),
2216
+ "title": title,
2217
+ "markdown": content,
2218
+ "dashboard_url": str(report.get("detail_url") or ""),
2219
+ "pack_is_stale": bool(report.get("pack_is_stale")),
2220
+ "summary": {
2221
+ "consensus_count": len(syn.get("consensus_picks") or []),
2222
+ "flagged_announcements": int(ann.get("flagged_count") or 0),
2223
+ },
2224
+ }
2225
+ kwargs: dict[str, Any] = {"json": payload, "timeout": timeout_sec}
2226
+ if token:
2227
+ kwargs["headers"] = {"Authorization": f"Bearer {token}"}
2228
+ _post_with_retry(post_fn, webhook_url, **kwargs)
2229
+
2230
+
2231
+ def _send_apprise(uri: str, content: str, *, title: str) -> None:
2232
+ try:
2233
+ apprise_mod = importlib.import_module("apprise")
2234
+ except ImportError as exc:
2235
+ raise RuntimeError(
2236
+ "URI scheme requires optional 'apprise' package (pip install apprise)"
2237
+ ) from exc
2238
+ app = apprise_mod.Apprise()
2239
+ if not app.add(uri):
2240
+ raise RuntimeError("apprise rejected notification URI")
2241
+ if not app.notify(title=title, body=content):
2242
+ raise RuntimeError("apprise notification failed")
2243
+
2244
+
2245
+ def _select_targets(
2246
+ cfg: Config,
2247
+ channels: Sequence[str] | None,
2248
+ ) -> tuple[list[str], list[dict[str, Any]]]:
2249
+ all_targets = resolve_notify_targets(cfg)
2250
+ available = configured_channels(cfg)
2251
+ if channels is None:
2252
+ return available, all_targets
2253
+ requested = [c.strip().lower() for c in channels if c.strip()]
2254
+ invalid = [c for c in requested if c not in SUPPORTED_CHANNELS]
2255
+ if invalid:
2256
+ raise ValueError(f"Unsupported notification channels: {', '.join(invalid)}")
2257
+ requested_set = set(requested)
2258
+ return available, [t for t in all_targets if t["channel"] in requested_set]
2259
+
2260
+
2261
+ def _dispatch_target(
2262
+ target_spec: dict[str, Any],
2263
+ cfg: Config,
2264
+ *,
2265
+ report: dict[str, Any],
2266
+ content: str,
2267
+ title: str,
2268
+ post_fn=requests.post,
2269
+ smtp_factory=None,
2270
+ ) -> None:
2271
+ ch = target_spec["channel"]
2272
+ target = str(target_spec["target"])
2273
+ secret = str(target_spec.get("secret") or "")
2274
+ token = str(target_spec.get("token") or "")
2275
+ extra = target_spec.get("extra") or {}
2276
+ timeout = cfg.notify_timeout_sec
2277
+
2278
+ if ch == "wecom":
2279
+ _send_wecom(target, content, title=title, report=report, timeout_sec=timeout, post_fn=post_fn)
2280
+ elif ch == "feishu":
2281
+ _send_feishu(
2282
+ target,
2283
+ content,
2284
+ title=title,
2285
+ secret=secret,
2286
+ report=report,
2287
+ timeout_sec=timeout,
2288
+ post_fn=post_fn,
2289
+ )
2290
+ elif ch == "dingtalk":
2291
+ _send_dingtalk(target, content, title=title, secret=secret, report=report, timeout_sec=timeout, post_fn=post_fn)
2292
+ elif ch == "pushplus":
2293
+ _send_pushplus(target, content, title=title, topic=str(extra.get("topic") or ""), report=report, timeout_sec=timeout, post_fn=post_fn)
2294
+ elif ch == "serverchan":
2295
+ _send_serverchan(target, content, title=title, report=report, timeout_sec=timeout, post_fn=post_fn)
2296
+ elif ch == "bark":
2297
+ _send_bark(target, content, title=title, detail_url=_resolved_report_url(report), timeout_sec=timeout, post_fn=post_fn)
2298
+ elif ch == "email":
2299
+ _send_email(
2300
+ str(extra.get("sender") or target),
2301
+ secret or str(extra.get("password") or ""),
2302
+ extra.get("receivers") or [target],
2303
+ content,
2304
+ title=title,
2305
+ report=report,
2306
+ smtp_host=str(extra.get("smtp_host") or ""),
2307
+ smtp_port=int(extra.get("smtp_port") or 0),
2308
+ timeout_sec=timeout,
2309
+ smtp_factory=smtp_factory,
2310
+ )
2311
+ elif ch == "telegram":
2312
+ _send_telegram(
2313
+ target,
2314
+ str(extra.get("chat_id") or ""),
2315
+ content,
2316
+ title=title,
2317
+ report=report,
2318
+ timeout_sec=timeout,
2319
+ post_fn=post_fn,
2320
+ )
2321
+ elif ch == "discord":
2322
+ _send_discord(target, content, title=title, detail_url=_resolved_report_url(report), report=report, timeout_sec=timeout, post_fn=post_fn)
2323
+ elif ch == "slack":
2324
+ _send_slack(target, content, title=title, report=report, timeout_sec=timeout, post_fn=post_fn)
2325
+ elif ch == "ntfy":
2326
+ _send_ntfy(target, content, title=title, detail_url=_resolved_report_url(report), timeout_sec=timeout, post_fn=post_fn)
2327
+ elif ch == "custom":
2328
+ _send_custom_webhook(target, report=report, content=content, title=title, token=token, timeout_sec=timeout, post_fn=post_fn)
2329
+ elif ch == "apprise":
2330
+ _send_apprise(target, content, title=title)
2331
+
2332
+
2333
+ def send_test_notification(
2334
+ *,
2335
+ config: Config | None = None,
2336
+ channels: Sequence[str] | None = None,
2337
+ dry_run: bool = False,
2338
+ post_fn=requests.post,
2339
+ smtp_factory=None,
2340
+ ) -> dict[str, Any]:
2341
+ """Dispatch a non-persistent connectivity test message to configured targets."""
2342
+ cfg = config or Config.from_env()
2343
+ available, target_specs = _select_targets(cfg, channels)
2344
+ target_channels: list[str] = []
2345
+ for spec in target_specs:
2346
+ if spec["channel"] not in target_channels:
2347
+ target_channels.append(spec["channel"])
2348
+
2349
+ if not target_specs:
2350
+ return {
2351
+ "status": "skipped_no_channels",
2352
+ "configured_channels": available,
2353
+ "target_channels": [],
2354
+ "sent": [],
2355
+ "skipped": [],
2356
+ "errors": [],
2357
+ }
2358
+
2359
+ title = "AlphaSift Push Connectivity Test"
2360
+ content = (
2361
+ f"**{title}**\n"
2362
+ f"> Channel connectivity verification from AlphaSift CLI (`dry_run={dry_run}`). "
2363
+ "This test does not write to the daily idempotency ledger.\n"
2364
+ f"🔗 {cfg.dashboard_url}"
2365
+ )
2366
+ test_report: dict[str, Any] = {
2367
+ "event": "alphasift.notify_test",
2368
+ "trade_date": "TEST",
2369
+ "detail_url": cfg.dashboard_url,
2370
+ "pack_is_stale": False,
2371
+ "cross_strategy_synthesis": {"consensus_picks": []},
2372
+ "announcement_risks": {"flagged_count": 0},
2373
+ }
2374
+
2375
+ sent: list[str] = []
2376
+ skipped: list[dict[str, str]] = []
2377
+ errors: list[dict[str, str]] = []
2378
+ for spec in target_specs:
2379
+ ch = spec["channel"]
2380
+ if dry_run:
2381
+ skipped.append({"channel": ch, "reason": "dry_run"})
2382
+ continue
2383
+ try:
2384
+ _dispatch_target(
2385
+ spec,
2386
+ cfg,
2387
+ report=test_report,
2388
+ content=content,
2389
+ title=title,
2390
+ post_fn=post_fn,
2391
+ smtp_factory=smtp_factory,
2392
+ )
2393
+ sent.append(ch)
2394
+ except Exception as exc: # noqa: BLE001
2395
+ errors.append({"channel": ch, "error": _redact_error(exc, cfg, spec.get("secrets") or ())})
2396
+
2397
+ if errors and sent:
2398
+ status = "partial"
2399
+ elif errors and not sent:
2400
+ status = "error"
2401
+ elif sent:
2402
+ status = "ok"
2403
+ else:
2404
+ status = "dry_run"
2405
+
2406
+ return {
2407
+ "status": status,
2408
+ "configured_channels": available,
2409
+ "target_channels": target_channels,
2410
+ "sent": sent,
2411
+ "skipped": skipped,
2412
+ "errors": errors,
2413
+ }
2414
+
2415
+
2416
+ def push_daily_report(
2417
+ report: dict[str, Any],
2418
+ *,
2419
+ config: Config | None = None,
2420
+ channels: Sequence[str] | None = None,
2421
+ state_path: Path | None = None,
2422
+ force: bool = False,
2423
+ dry_run: bool = False,
2424
+ post_fn=requests.post,
2425
+ smtp_factory=None,
2426
+ ) -> dict[str, Any]:
2427
+ """Push rendered <1200-char card to configured targets idempotently by (trade_date, target)."""
2428
+ cfg = config or Config.from_env()
2429
+ trade_date = str(report.get("trade_date") or "").strip()
2430
+ if not trade_date:
2431
+ raise ValueError("Daily report is missing trade_date")
2432
+
2433
+ card = ensure_im_card_length(
2434
+ str(report.get("im_card_markdown") or render_daily_im_card(report)),
2435
+ max_chars=IM_CARD_MAX_CHARS,
2436
+ )
2437
+ _, target_specs = _select_targets(cfg, channels)
2438
+
2439
+ if not target_specs:
2440
+ return {
2441
+ "status": "skipped_no_channels",
2442
+ "trade_date": trade_date,
2443
+ "card_chars": len(card),
2444
+ "sent": [],
2445
+ "skipped": [],
2446
+ "errors": [],
2447
+ }
2448
+
2449
+ if report.get("pack_is_stale") and not force:
2450
+ return {
2451
+ "status": "skipped_stale_pack",
2452
+ "trade_date": trade_date,
2453
+ "pack_trade_date": report.get("pack_trade_date"),
2454
+ "stale_reason": report.get("stale_reason"),
2455
+ "card_chars": len(card),
2456
+ "sent": [],
2457
+ "skipped": [{"channel": spec["channel"], "reason": "stale_pack"} for spec in target_specs],
2458
+ "errors": [],
2459
+ }
2460
+
2461
+ ledger_path = Path(state_path) if state_path is not None else cfg.notify_state_path
2462
+ content_hash = hashlib.sha256(card.encode("utf-8")).hexdigest()[:16]
2463
+ fallback_title = f"AlphaSift A股量化观测日报 ({trade_date})"
2464
+ title = _build_report_title(report, fallback_title=fallback_title)
2465
+ market_scope = str(report.get("market") or "cn").strip().lower()
2466
+ ledger_prefix = f"{trade_date}:{market_scope}:" if market_scope not in {"", "cn"} else f"{trade_date}:"
2467
+
2468
+ sent: list[str] = []
2469
+ skipped: list[dict[str, str]] = []
2470
+ errors: list[dict[str, str]] = []
2471
+ channel_totals: dict[str, int] = {}
2472
+ for spec in target_specs:
2473
+ ch_name = spec["channel"]
2474
+ channel_totals[ch_name] = channel_totals.get(ch_name, 0) + 1
2475
+
2476
+ for spec in target_specs:
2477
+ channel = spec["channel"]
2478
+ extra = spec.get("extra") or {}
2479
+ receivers_fp = ",".join(
2480
+ sorted(str(r).strip() for r in (extra.get("receivers") or []) if str(r).strip())
2481
+ )
2482
+ ident = f"{channel}\0{spec.get('target', '')}\0{extra.get('chat_id') or extra.get('topic') or receivers_fp or ''}"
2483
+ fp_full = hashlib.sha256(ident.encode("utf-8")).hexdigest()[:12]
2484
+ legacy_key = f"{ledger_prefix}{channel}"
2485
+ fp_key = f"{ledger_prefix}{channel}:{fp_full}"
2486
+ is_single = channel_totals.get(channel, 0) <= 1
2487
+ claim_record: dict[str, Any] | None = None
2488
+
2489
+ with _ledger_lock(ledger_path):
2490
+ state = _load_state(ledger_path)
2491
+ legacy_rec = state.get(legacy_key)
2492
+ fp_rec = state.get(fp_key)
2493
+ legacy_matches = isinstance(legacy_rec, dict) and legacy_rec.get("target_fp") in (None, fp_full)
2494
+
2495
+ if is_single:
2496
+ if isinstance(fp_rec, dict):
2497
+ key = fp_key
2498
+ existing = fp_rec
2499
+ elif legacy_matches:
2500
+ key = legacy_key
2501
+ existing = legacy_rec
2502
+ elif isinstance(legacy_rec, dict):
2503
+ key = fp_key
2504
+ existing = fp_rec
2505
+ else:
2506
+ key = legacy_key
2507
+ existing = None
2508
+ else:
2509
+ legacy_exact = isinstance(legacy_rec, dict) and legacy_rec.get("target_fp") == fp_full
2510
+ if isinstance(fp_rec, dict):
2511
+ key = fp_key
2512
+ existing = fp_rec
2513
+ elif legacy_exact:
2514
+ key = legacy_key
2515
+ existing = legacy_rec
2516
+ else:
2517
+ key = fp_key
2518
+ existing = None
2519
+
2520
+ if isinstance(existing, dict) and not force:
2521
+ existing_status = existing.get("status")
2522
+ if existing_status in (None, "sent"):
2523
+ skipped.append({"channel": channel, "reason": "duplicate_same_trade_date"})
2524
+ continue
2525
+ if existing_status == "pending":
2526
+ claimed_dt = parse_timestamp(existing.get("claimed_at"))
2527
+ if (
2528
+ claimed_dt is not None
2529
+ and (datetime.now(timezone.utc) - claimed_dt).total_seconds() < _PENDING_LEASE_SEC
2530
+ ):
2531
+ skipped.append({"channel": channel, "reason": "in_progress_concurrent"})
2532
+ continue
2533
+
2534
+ if dry_run:
2535
+ skipped.append({"channel": channel, "reason": "dry_run"})
2536
+ continue
2537
+
2538
+ attempts = int(existing.get("attempts", 0) or 0) + 1 if isinstance(existing, dict) else 1
2539
+ claim_record = {
2540
+ "status": "pending",
2541
+ "trade_date": trade_date,
2542
+ "channel": channel,
2543
+ "target_fp": fp_full,
2544
+ "claimed_at": datetime.now(timezone.utc).isoformat(),
2545
+ "pid": os.getpid(),
2546
+ "attempts": attempts,
2547
+ "content_sha256": content_hash,
2548
+ }
2549
+ state[key] = claim_record
2550
+ _save_state(ledger_path, state)
2551
+
2552
+ send_error: str | None = None
2553
+ try:
2554
+ _dispatch_target(
2555
+ spec,
2556
+ cfg,
2557
+ report=report,
2558
+ content=card,
2559
+ title=title,
2560
+ post_fn=post_fn,
2561
+ smtp_factory=smtp_factory,
2562
+ )
2563
+ except Exception as exc: # noqa: BLE001
2564
+ send_error = _redact_error(exc, cfg, spec.get("secrets") or ())
2565
+
2566
+ with _ledger_lock(ledger_path):
2567
+ latest_state = _load_state(ledger_path)
2568
+ if send_error is not None:
2569
+ latest_state[key] = {
2570
+ **(claim_record or {}),
2571
+ "status": "failed",
2572
+ "failed_at": datetime.now(timezone.utc).isoformat(),
2573
+ "last_error": send_error,
2574
+ }
2575
+ _save_state(ledger_path, latest_state)
2576
+ errors.append({"channel": channel, "error": send_error})
2577
+ else:
2578
+ latest_state[key] = {
2579
+ **(claim_record or {}),
2580
+ "status": "sent",
2581
+ "sent_at": datetime.now(timezone.utc).isoformat(),
2582
+ "chars": len(card),
2583
+ }
2584
+ _save_state(ledger_path, latest_state)
2585
+ sent.append(channel)
2586
+
2587
+ if errors and sent:
2588
+ status = "partial"
2589
+ elif errors and not sent:
2590
+ status = "error"
2591
+ elif sent:
2592
+ status = "ok"
2593
+ elif any(
2594
+ s["reason"] in {"duplicate_same_trade_date", "in_progress_concurrent"}
2595
+ for s in skipped
2596
+ ):
2597
+ status = "skipped_duplicate"
2598
+ else:
2599
+ status = "dry_run"
2600
+
2601
+ return {
2602
+ "status": status,
2603
+ "trade_date": trade_date,
2604
+ "card_chars": len(card),
2605
+ "sent": sent,
2606
+ "skipped": skipped,
2607
+ "errors": errors,
2608
+ }