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/doctor.py ADDED
@@ -0,0 +1,1123 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Runtime diagnostic helpers for AlphaSift data sources."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import asdict, dataclass, field
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import pandas as pd
12
+
13
+ from alphasift.config import Config
14
+ from alphasift.daily import compute_daily_features, daily_source_health_snapshot, fetch_daily_history
15
+ from alphasift.llm_client import configuration_error
16
+ from alphasift.snapshot import (
17
+ fetch_cn_snapshot,
18
+ fetch_snapshot_with_fallback,
19
+ snapshot_source_health_snapshot,
20
+ )
21
+ from alphasift.markets import get_market
22
+ from alphasift.strategy import list_strategies
23
+
24
+
25
+ @dataclass
26
+ class SourceCheckResult:
27
+ """Single source-family diagnostic result."""
28
+
29
+ status: str
30
+ sources: list[str] = field(default_factory=list)
31
+ source: str = ""
32
+ rows: int = 0
33
+ fallback_used: bool = False
34
+ stale: bool = False
35
+ stale_age_hours: float | None = None
36
+ errors: list[str] = field(default_factory=list)
37
+ health: dict[str, dict[str, float | bool | str]] = field(default_factory=dict)
38
+ required_fields: list[str] = field(default_factory=list)
39
+ missing_fields: list[str] = field(default_factory=list)
40
+ quality_summary: dict[str, Any] = field(default_factory=dict)
41
+
42
+
43
+ @dataclass
44
+ class DataSourcesDoctorResult:
45
+ """Machine-readable data-source doctor report."""
46
+
47
+ status: str
48
+ generated_at: str
49
+ config: dict[str, Any]
50
+ snapshot: SourceCheckResult
51
+ daily: SourceCheckResult | None = None
52
+ strategy_requirements: dict[str, Any] = field(default_factory=dict)
53
+ strategy_coverage: list[dict[str, Any]] = field(default_factory=list)
54
+ strategy_readiness_summary: dict[str, Any] = field(default_factory=dict)
55
+ health_summary: dict[str, Any] = field(default_factory=dict)
56
+ freshness_summary: dict[str, Any] = field(default_factory=dict)
57
+ snapshot_reconciliation: dict[str, Any] = field(default_factory=dict)
58
+ recommendations: list[str] = field(default_factory=list)
59
+
60
+ def to_dict(self) -> dict[str, Any]:
61
+ payload = asdict(self)
62
+ payload["source_health"] = {
63
+ "snapshot": self.snapshot.health,
64
+ "daily": self.daily.health if self.daily is not None else {},
65
+ }
66
+ return payload
67
+
68
+
69
+ def doctor_data_sources(
70
+ config: Config,
71
+ *,
72
+ snapshot_sources: list[str] | None = None,
73
+ daily_source: str | None = None,
74
+ daily_code: str = "000001",
75
+ run_live: bool = True,
76
+ check_daily: bool = True,
77
+ strategy_name: str | None = None,
78
+ all_strategies: bool = False,
79
+ compare_snapshot_sources: bool = False,
80
+ market: str | None = None,
81
+ ) -> DataSourcesDoctorResult:
82
+ """Check snapshot and daily K-line source health without exposing secrets.
83
+
84
+ ``market`` defaults to cn, or to the first market in ``strategy_name``'s
85
+ scope when that strategy does not run on cn (e.g. global_value -> us).
86
+ Non-CN markets check the Yahoo screener and the yfinance daily adapter.
87
+ """
88
+ # --all-strategies checks one market, so only the strategies that run on
89
+ # it count (CN sources cannot carry global_value's avg_amount_usd).
90
+ plan_market = _resolve_doctor_market(market, {}) if all_strategies and not strategy_name else None
91
+ strategy_requirements, coverage_requirements = _strategy_preflight_plan(
92
+ config,
93
+ strategy_name=strategy_name,
94
+ all_strategies=all_strategies,
95
+ market=plan_market,
96
+ )
97
+ market = _resolve_doctor_market(market, strategy_requirements)
98
+ if market == "cn":
99
+ sources = list(snapshot_sources or config.snapshot_source_priority)
100
+ daily_source_name = daily_source or config.daily_source
101
+ else:
102
+ # CN source names (sina, em_datacenter...) do not apply; the market
103
+ # registry routes non-CN snapshots through the Yahoo screener.
104
+ sources = ["yahoo_screener", "yfinance_tickers"] if market == "us" else ["yahoo_screener"]
105
+ configured_daily = daily_source or config.daily_source
106
+ daily_source_name = "yfinance" if configured_daily in ("", "auto") else configured_daily
107
+ if daily_code == "000001":
108
+ daily_code = _MARKET_SAMPLE_SYMBOLS[market]
109
+ snapshot_required_fields = _required_fields_for_check(
110
+ strategy_requirements.get("required_snapshot_fields"),
111
+ default=["code", "name", "price"],
112
+ )
113
+ daily_required_fields = list(strategy_requirements.get("required_daily_fields", []) or [])
114
+ snapshot = _check_snapshot_sources(
115
+ config,
116
+ sources=sources,
117
+ run_live=run_live,
118
+ required_fields=snapshot_required_fields,
119
+ market=market,
120
+ )
121
+ daily = (
122
+ _check_daily_sources(
123
+ config,
124
+ source=daily_source_name,
125
+ code=daily_code,
126
+ run_live=run_live,
127
+ required_fields=daily_required_fields,
128
+ )
129
+ if check_daily
130
+ else None
131
+ )
132
+ strategy_coverage = _build_strategy_coverage(coverage_requirements, snapshot, daily)
133
+ strategy_readiness_summary = _build_strategy_readiness_summary(strategy_coverage)
134
+ health_summary = _build_health_summary(snapshot, daily)
135
+ freshness_summary = _build_freshness_summary(snapshot, daily)
136
+ snapshot_reconciliation = _snapshot_source_reconciliation(
137
+ sources,
138
+ required_fields=snapshot_required_fields,
139
+ run_live=run_live,
140
+ # Per-source reconciliation compares the CN source chain only.
141
+ enabled=compare_snapshot_sources and market == "cn",
142
+ )
143
+ recommendations = _build_recommendations(snapshot, daily)
144
+ if error := configuration_error(config.llm_channels, str(config.llm_config_path or "")):
145
+ recommendations.append(error)
146
+ statuses = [snapshot.status, daily.status if daily is not None else "skipped"]
147
+ status = _overall_status(statuses)
148
+ return DataSourcesDoctorResult(
149
+ status=status,
150
+ generated_at=datetime.now(timezone.utc).isoformat(),
151
+ config={
152
+ "market": market,
153
+ "snapshot_source_priority": sources,
154
+ "daily_source": daily_source_name,
155
+ "daily_code": daily_code if check_daily else "",
156
+ "fallback_snapshot_path": str(config.fallback_snapshot_path or ""),
157
+ "daily_history_cache_dir": str(config.daily_history_cache_dir or ""),
158
+ "tushare_configured": bool(_has_configured_tushare()),
159
+ "live_checks": bool(run_live),
160
+ },
161
+ snapshot=snapshot,
162
+ daily=daily,
163
+ strategy_requirements=strategy_requirements,
164
+ strategy_coverage=strategy_coverage,
165
+ strategy_readiness_summary=strategy_readiness_summary,
166
+ health_summary=health_summary,
167
+ freshness_summary=freshness_summary,
168
+ snapshot_reconciliation=snapshot_reconciliation,
169
+ recommendations=recommendations,
170
+ )
171
+
172
+
173
+ def _check_snapshot_sources(
174
+ config: Config,
175
+ *,
176
+ sources: list[str],
177
+ run_live: bool,
178
+ required_fields: list[str],
179
+ market: str = "cn",
180
+ ) -> SourceCheckResult:
181
+ health = snapshot_source_health_snapshot(sources)
182
+ if not run_live:
183
+ return SourceCheckResult(
184
+ status="skipped",
185
+ sources=sources,
186
+ health=health,
187
+ required_fields=required_fields,
188
+ )
189
+ try:
190
+ df = fetch_snapshot_with_fallback(
191
+ sources,
192
+ required_columns=required_fields,
193
+ fallback_snapshot_path=config.fallback_snapshot_path,
194
+ fallback_max_age_hours=config.snapshot_fallback_max_age_hours,
195
+ market=market,
196
+ source_health_path=config.source_health_path,
197
+ )
198
+ except Exception as exc: # noqa: BLE001 - doctor must aggregate failures.
199
+ return SourceCheckResult(
200
+ status="failed",
201
+ sources=sources,
202
+ errors=[str(exc)],
203
+ health=snapshot_source_health_snapshot(sources),
204
+ required_fields=required_fields,
205
+ )
206
+ missing_fields = [field for field in required_fields if field not in df.columns]
207
+ quality_summary = _snapshot_quality_summary(df, required_fields=required_fields)
208
+ quality_degraded = str(quality_summary.get("status", "")) not in {"", "ok"}
209
+ return SourceCheckResult(
210
+ status="degraded"
211
+ if bool(df.attrs.get("fallback_used")) or missing_fields or quality_degraded
212
+ else "ok",
213
+ sources=sources,
214
+ source=str(df.attrs.get("snapshot_source", "")),
215
+ rows=int(len(df)),
216
+ fallback_used=bool(df.attrs.get("fallback_used")),
217
+ stale=bool(df.attrs.get("stale")),
218
+ stale_age_hours=df.attrs.get("stale_age_hours"),
219
+ errors=[str(item) for item in list(df.attrs.get("source_errors", []) or [])],
220
+ health=snapshot_source_health_snapshot(sources),
221
+ required_fields=required_fields,
222
+ missing_fields=missing_fields,
223
+ quality_summary=quality_summary,
224
+ )
225
+
226
+
227
+ def _check_daily_sources(
228
+ config: Config,
229
+ *,
230
+ source: str,
231
+ code: str,
232
+ run_live: bool,
233
+ required_fields: list[str],
234
+ ) -> SourceCheckResult:
235
+ health = daily_source_health_snapshot()
236
+ if not run_live:
237
+ return SourceCheckResult(
238
+ status="skipped",
239
+ sources=[source],
240
+ health=health,
241
+ required_fields=required_fields,
242
+ )
243
+ try:
244
+ df = fetch_daily_history(
245
+ code,
246
+ lookback_days=config.daily_lookback_days,
247
+ source=source,
248
+ retries=0,
249
+ cache_dir=config.daily_history_cache_dir,
250
+ cache_ttl_seconds=config.daily_history_cache_ttl_hours * 3600,
251
+ )
252
+ missing_fields = _missing_daily_feature_fields(df, required_fields)
253
+ except Exception as exc: # noqa: BLE001 - doctor must aggregate failures.
254
+ return SourceCheckResult(
255
+ status="failed",
256
+ sources=[source],
257
+ errors=[str(exc)],
258
+ health=daily_source_health_snapshot(),
259
+ required_fields=required_fields,
260
+ )
261
+ degraded = bool(df.attrs.get("daily_stale")) or bool(missing_fields)
262
+ return SourceCheckResult(
263
+ status="degraded" if degraded else "ok",
264
+ sources=[source],
265
+ source=str(df.attrs.get("daily_source", "")),
266
+ rows=int(len(df)),
267
+ fallback_used=bool(df.attrs.get("source_errors")),
268
+ stale=bool(df.attrs.get("daily_stale")),
269
+ errors=[str(item) for item in list(df.attrs.get("source_errors", []) or [])],
270
+ health=daily_source_health_snapshot(),
271
+ required_fields=required_fields,
272
+ missing_fields=missing_fields,
273
+ )
274
+
275
+
276
+ def _strategy_preflight_plan(
277
+ config: Config,
278
+ *,
279
+ strategy_name: str | None,
280
+ all_strategies: bool,
281
+ market: str | None = None,
282
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
283
+ if strategy_name and all_strategies:
284
+ raise ValueError("--strategy and --all-strategies cannot be combined")
285
+ if all_strategies:
286
+ requirements = [_strategy_requirement_payload(item) for item in list_strategies(config.strategies_dir)]
287
+ if market:
288
+ requirements = [item for item in requirements if market in item["market_scope"]]
289
+ return (
290
+ {
291
+ "mode": "all",
292
+ "market": market or "",
293
+ "strategy_count": len(requirements),
294
+ "daily_strategy_count": sum(
295
+ 1 for item in requirements if item["requires_daily_features"]
296
+ ),
297
+ "data_requirements": _union_fields(requirements, "data_requirements"),
298
+ "required_snapshot_fields": _union_fields(requirements, "required_snapshot_fields"),
299
+ "required_daily_fields": _union_fields(requirements, "required_daily_fields"),
300
+ },
301
+ requirements,
302
+ )
303
+ strategy_requirements = _strategy_requirements(config, strategy_name)
304
+ return strategy_requirements, [strategy_requirements] if strategy_requirements else []
305
+
306
+
307
+ # One liquid listing per market for the daily K-line smoke test.
308
+ _MARKET_SAMPLE_SYMBOLS = {
309
+ "us": "AAPL",
310
+ "hk": "0700.HK",
311
+ "jp": "7203.T",
312
+ "kr": "005930.KS",
313
+ "tw": "2330.TW",
314
+ "in": "RELIANCE.NS",
315
+ }
316
+
317
+
318
+ def _resolve_doctor_market(market: str | None, strategy_requirements: dict[str, Any]) -> str:
319
+ if market:
320
+ resolved = get_market(market).id
321
+ scope = strategy_requirements.get("market_scope")
322
+ if scope and resolved not in scope:
323
+ raise ValueError(
324
+ f"Strategy '{strategy_requirements.get('strategy')}' does not support market "
325
+ f"'{resolved}'. Supported: {', '.join(scope)}"
326
+ )
327
+ return resolved
328
+ scope = list(strategy_requirements.get("market_scope") or [])
329
+ if scope and "cn" not in scope:
330
+ return get_market(scope[0]).id
331
+ return "cn"
332
+
333
+
334
+ def _strategy_requirements(config: Config, strategy_name: str | None) -> dict[str, Any]:
335
+ if not strategy_name:
336
+ return {}
337
+ for item in list_strategies(config.strategies_dir):
338
+ if item.name == strategy_name:
339
+ return _strategy_requirement_payload(item)
340
+ raise ValueError(f"Strategy '{strategy_name}' not found")
341
+
342
+
343
+ def _strategy_requirement_payload(item) -> dict[str, Any]:
344
+ return {
345
+ "strategy": item.name,
346
+ "display_name": item.display_name,
347
+ "category": item.category,
348
+ "style": dict(item.style),
349
+ "data_requirements": list(item.data_requirements),
350
+ "requires_daily_features": bool(item.requires_daily_features),
351
+ "required_snapshot_fields": list(item.required_snapshot_fields),
352
+ "required_daily_fields": list(item.required_daily_fields),
353
+ "market_scope": list(getattr(item, "market_scope", None) or ["cn"]),
354
+ }
355
+
356
+
357
+ def _union_fields(items: list[dict[str, Any]], key: str) -> list[str]:
358
+ values: list[str] = []
359
+ for item in items:
360
+ values.extend(str(value) for value in item.get(key, []) or [])
361
+ return list(dict.fromkeys(values))
362
+
363
+
364
+ def _required_fields_for_check(value: object, *, default: list[str]) -> list[str]:
365
+ fields = [str(item) for item in (value or []) if str(item).strip()]
366
+ if not fields:
367
+ fields = list(default)
368
+ if "code" not in fields:
369
+ fields.insert(0, "code")
370
+ return list(dict.fromkeys(fields))
371
+
372
+
373
+ def _missing_daily_feature_fields(df, required_fields: list[str]) -> list[str]:
374
+ if not required_fields:
375
+ return []
376
+ features = compute_daily_features(df)
377
+ return [field for field in required_fields if field not in features]
378
+
379
+
380
+ def _snapshot_quality_summary(df, *, required_fields: list[str]) -> dict[str, Any]:
381
+ checked_fields = _snapshot_quality_fields(df, required_fields)
382
+ anomalies: list[str] = []
383
+ field_stats: dict[str, dict[str, Any]] = {}
384
+ row_count = int(len(df))
385
+ if row_count == 0:
386
+ anomalies.append("snapshot_empty")
387
+
388
+ duplicate_code_count = 0
389
+ if "code" in df.columns:
390
+ duplicate_code_count = int(df["code"].astype(str).duplicated().sum())
391
+ if duplicate_code_count > 0:
392
+ anomalies.append(f"duplicate_code_count:{duplicate_code_count}")
393
+
394
+ for field_name in checked_fields:
395
+ if field_name not in df.columns:
396
+ field_stats[field_name] = {
397
+ "present": False,
398
+ "missing_count": row_count,
399
+ "missing_ratio": 1.0 if row_count else 0.0,
400
+ "invalid_numeric_count": 0,
401
+ "non_positive_count": 0,
402
+ }
403
+ anomalies.append(f"{field_name}:missing_column")
404
+ continue
405
+ series = df[field_name]
406
+ missing_mask = series.isna() | (series.astype(str).str.strip() == "")
407
+ missing_count = int(missing_mask.sum())
408
+ missing_ratio = _ratio(missing_count, row_count)
409
+ stats: dict[str, Any] = {
410
+ "present": True,
411
+ "missing_count": missing_count,
412
+ "missing_ratio": missing_ratio,
413
+ "invalid_numeric_count": 0,
414
+ "non_positive_count": 0,
415
+ }
416
+ if field_name in _SNAPSHOT_NUMERIC_FIELDS:
417
+ numeric = pd.to_numeric(series, errors="coerce")
418
+ invalid_numeric_count = int((numeric.isna() & ~missing_mask).sum())
419
+ non_positive_count = (
420
+ int((numeric <= 0).sum())
421
+ if field_name in _SNAPSHOT_POSITIVE_FIELDS
422
+ else 0
423
+ )
424
+ stats["invalid_numeric_count"] = invalid_numeric_count
425
+ stats["non_positive_count"] = non_positive_count
426
+ if invalid_numeric_count > 0:
427
+ anomalies.append(f"{field_name}:invalid_numeric={invalid_numeric_count}")
428
+ if non_positive_count > 0:
429
+ anomalies.append(f"{field_name}:non_positive={non_positive_count}")
430
+ if missing_count > 0 and field_name in required_fields:
431
+ anomalies.append(f"{field_name}:missing_values={missing_count}")
432
+ elif missing_ratio >= 0.25 and row_count > 0:
433
+ anomalies.append(f"{field_name}:missing_ratio={missing_ratio:.2f}")
434
+ field_stats[field_name] = stats
435
+
436
+ return {
437
+ "status": "degraded" if anomalies else "ok",
438
+ "row_count": row_count,
439
+ "duplicate_code_count": duplicate_code_count,
440
+ "checked_fields": checked_fields,
441
+ "anomalies": anomalies,
442
+ "field_stats": field_stats,
443
+ }
444
+
445
+
446
+ _SNAPSHOT_DEFAULT_QUALITY_FIELDS = [
447
+ "code",
448
+ "name",
449
+ "price",
450
+ "change_pct",
451
+ "amount",
452
+ "total_mv",
453
+ "pe_ratio",
454
+ "pb_ratio",
455
+ "turnover_rate",
456
+ "volume_ratio",
457
+ ]
458
+ _SNAPSHOT_NUMERIC_FIELDS = {
459
+ "price",
460
+ "change_pct",
461
+ "amount",
462
+ "avg_amount",
463
+ "avg_amount_usd",
464
+ "total_mv",
465
+ "pe_ratio",
466
+ "pb_ratio",
467
+ "turnover_rate",
468
+ "volume_ratio",
469
+ }
470
+ _SNAPSHOT_POSITIVE_FIELDS = {"price", "amount", "avg_amount", "avg_amount_usd", "total_mv"}
471
+
472
+
473
+ def _snapshot_quality_fields(df, required_fields: list[str]) -> list[str]:
474
+ fields: list[str] = []
475
+ fields.extend(required_fields)
476
+ fields.extend(field for field in _SNAPSHOT_DEFAULT_QUALITY_FIELDS if field in df.columns)
477
+ return list(dict.fromkeys(field for field in fields if field))
478
+
479
+
480
+ def _snapshot_source_reconciliation(
481
+ sources: list[str],
482
+ *,
483
+ required_fields: list[str],
484
+ run_live: bool,
485
+ enabled: bool,
486
+ ) -> dict[str, Any]:
487
+ if not enabled:
488
+ return {}
489
+ if not run_live:
490
+ return {
491
+ "status": "skipped",
492
+ "reason": "live_checks_disabled",
493
+ "required_fields": list(required_fields),
494
+ "sources": [],
495
+ "summary": {
496
+ "source_count": len(sources),
497
+ "ok_source_count": 0,
498
+ "degraded_source_count": 0,
499
+ "failed_source_count": 0,
500
+ "field_coverage": {},
501
+ "warnings": ["snapshot_reconciliation_skipped:no_live"],
502
+ },
503
+ }
504
+
505
+ rows: list[dict[str, Any]] = []
506
+ code_sets: dict[str, set[str]] = {}
507
+ for source in sources:
508
+ try:
509
+ df = fetch_cn_snapshot(source)
510
+ except Exception as exc: # noqa: BLE001 - doctor should capture provider failures.
511
+ rows.append({
512
+ "source": source,
513
+ "status": "failed",
514
+ "rows": 0,
515
+ "missing_fields": list(required_fields),
516
+ "quality_status": "",
517
+ "quality_anomaly_count": 0,
518
+ "overlap_with_baseline_count": 0,
519
+ "overlap_with_baseline_ratio": None,
520
+ "sample_codes": [],
521
+ "errors": [str(exc)],
522
+ })
523
+ continue
524
+
525
+ missing_fields = [field for field in required_fields if field not in df.columns]
526
+ quality_summary = _snapshot_quality_summary(df, required_fields=required_fields)
527
+ quality_status = str(quality_summary.get("status", ""))
528
+ status = "degraded" if missing_fields or quality_status == "degraded" else "ok"
529
+ codes = _snapshot_reconciliation_codes(df)
530
+ code_sets[source] = codes
531
+ rows.append({
532
+ "source": source,
533
+ "status": status,
534
+ "rows": int(len(df)),
535
+ "missing_fields": missing_fields,
536
+ "quality_status": quality_status,
537
+ "quality_anomaly_count": len(quality_summary.get("anomalies", []) or []),
538
+ "overlap_with_baseline_count": 0,
539
+ "overlap_with_baseline_ratio": None,
540
+ "sample_codes": sorted(codes)[:5],
541
+ "errors": [],
542
+ })
543
+
544
+ baseline_source = _snapshot_reconciliation_baseline(rows)
545
+ baseline_codes = code_sets.get(baseline_source, set())
546
+ if baseline_codes:
547
+ for row in rows:
548
+ source = str(row.get("source", ""))
549
+ codes = code_sets.get(source, set())
550
+ shared_count = len(codes & baseline_codes)
551
+ row["overlap_with_baseline_count"] = shared_count
552
+ row["overlap_with_baseline_ratio"] = _ratio(shared_count, len(baseline_codes))
553
+
554
+ summary = _snapshot_reconciliation_summary(rows, required_fields)
555
+ if not any(row.get("status") in {"ok", "degraded"} for row in rows):
556
+ status = "failed"
557
+ elif summary["failed_source_count"] or summary["degraded_source_count"]:
558
+ status = "degraded"
559
+ else:
560
+ status = "ok"
561
+ return {
562
+ "status": status,
563
+ "baseline_source": baseline_source,
564
+ "required_fields": list(required_fields),
565
+ "sources": rows,
566
+ "summary": summary,
567
+ }
568
+
569
+
570
+ def _snapshot_reconciliation_codes(df: pd.DataFrame) -> set[str]:
571
+ if "code" not in df.columns:
572
+ return set()
573
+ return {
574
+ str(value).strip()
575
+ for value in df["code"].tolist()
576
+ if str(value).strip()
577
+ }
578
+
579
+
580
+ def _snapshot_reconciliation_baseline(rows: list[dict[str, Any]]) -> str:
581
+ for row in rows:
582
+ if row.get("status") in {"ok", "degraded"}:
583
+ return str(row.get("source", ""))
584
+ return ""
585
+
586
+
587
+ def _snapshot_reconciliation_summary(
588
+ rows: list[dict[str, Any]],
589
+ required_fields: list[str],
590
+ ) -> dict[str, Any]:
591
+ warnings: list[str] = []
592
+ field_coverage: dict[str, dict[str, Any]] = {}
593
+ for field_name in required_fields:
594
+ present_sources: list[str] = []
595
+ missing_sources: list[str] = []
596
+ for row in rows:
597
+ source = str(row.get("source", ""))
598
+ if row.get("status") == "failed":
599
+ continue
600
+ if field_name in (row.get("missing_fields") or []):
601
+ missing_sources.append(source)
602
+ else:
603
+ present_sources.append(source)
604
+ if missing_sources:
605
+ warnings.append(f"{field_name}:missing_in={','.join(missing_sources)}")
606
+ field_coverage[field_name] = {
607
+ "present_source_count": len(present_sources),
608
+ "missing_sources": missing_sources,
609
+ }
610
+
611
+ failed_sources = [str(row.get("source", "")) for row in rows if row.get("status") == "failed"]
612
+ if failed_sources:
613
+ warnings.append("failed_sources:" + ",".join(failed_sources))
614
+ return {
615
+ "source_count": len(rows),
616
+ "ok_source_count": sum(1 for row in rows if row.get("status") == "ok"),
617
+ "degraded_source_count": sum(1 for row in rows if row.get("status") == "degraded"),
618
+ "failed_source_count": len(failed_sources),
619
+ "field_coverage": field_coverage,
620
+ "warnings": warnings,
621
+ }
622
+
623
+
624
+ def _ratio(count: int, total: int) -> float:
625
+ if total <= 0:
626
+ return 0.0
627
+ return round(float(count) / float(total), 4)
628
+
629
+
630
+ def _build_strategy_coverage(
631
+ requirements: list[dict[str, Any]],
632
+ snapshot: SourceCheckResult,
633
+ daily: SourceCheckResult | None,
634
+ ) -> list[dict[str, Any]]:
635
+ if not requirements:
636
+ return []
637
+ snapshot_missing = set(snapshot.missing_fields)
638
+ daily_missing = set(daily.missing_fields if daily is not None else [])
639
+ coverage: list[dict[str, Any]] = []
640
+ for item in requirements:
641
+ required_snapshot = list(item.get("required_snapshot_fields", []) or [])
642
+ required_daily = list(item.get("required_daily_fields", []) or [])
643
+ item_snapshot_missing = [field for field in required_snapshot if field in snapshot_missing]
644
+ item_daily_missing = [field for field in required_daily if field in daily_missing]
645
+ coverage.append(
646
+ {
647
+ "strategy": item.get("strategy", ""),
648
+ "display_name": item.get("display_name", ""),
649
+ "category": item.get("category", ""),
650
+ "style": dict(item.get("style", {}) or {}),
651
+ "data_requirements": list(item.get("data_requirements", []) or []),
652
+ "requires_daily_features": bool(item.get("requires_daily_features")),
653
+ "status": _strategy_coverage_status(
654
+ item,
655
+ snapshot,
656
+ daily,
657
+ snapshot_missing=item_snapshot_missing,
658
+ daily_missing=item_daily_missing,
659
+ ),
660
+ "required_snapshot_fields": required_snapshot,
661
+ "required_daily_fields": required_daily,
662
+ "snapshot_missing_fields": item_snapshot_missing,
663
+ "daily_missing_fields": item_daily_missing,
664
+ }
665
+ )
666
+ return coverage
667
+
668
+
669
+ def _strategy_coverage_status(
670
+ item: dict[str, Any],
671
+ snapshot: SourceCheckResult,
672
+ daily: SourceCheckResult | None,
673
+ *,
674
+ snapshot_missing: list[str],
675
+ daily_missing: list[str],
676
+ ) -> str:
677
+ requires_daily = bool(item.get("requires_daily_features")) or bool(
678
+ item.get("required_daily_fields")
679
+ )
680
+ if snapshot.status == "failed" or (requires_daily and daily is not None and daily.status == "failed"):
681
+ return "failed"
682
+ if snapshot.status == "skipped" or (requires_daily and (daily is None or daily.status == "skipped")):
683
+ return "skipped"
684
+ if snapshot_missing or daily_missing:
685
+ return "degraded"
686
+ if snapshot.status == "degraded" or (requires_daily and daily is not None and daily.status == "degraded"):
687
+ return "degraded"
688
+ return "ok"
689
+
690
+
691
+ def _build_strategy_readiness_summary(coverage: list[dict[str, Any]]) -> dict[str, Any]:
692
+ status_counts = {status: 0 for status in ("ok", "degraded", "failed", "skipped")}
693
+ for item in coverage:
694
+ status = str(item.get("status") or "unknown")
695
+ status_counts[status] = status_counts.get(status, 0) + 1
696
+
697
+ impacted = [
698
+ _strategy_readiness_item(item)
699
+ for item in coverage
700
+ if str(item.get("status") or "") in {"degraded", "failed"}
701
+ ]
702
+ unchecked = [
703
+ _strategy_readiness_item(item)
704
+ for item in coverage
705
+ if str(item.get("status") or "") == "skipped"
706
+ ]
707
+ next_actions: list[str] = []
708
+ if unchecked:
709
+ next_actions.append("Run a live data-source check before relying on strategy readiness.")
710
+ if impacted:
711
+ next_actions.append("Review missing snapshot/daily fields for degraded or failed strategies.")
712
+
713
+ return {
714
+ "schema_version": 1,
715
+ "strategy_count": len(coverage),
716
+ "ready_strategy_count": status_counts.get("ok", 0),
717
+ "attention_strategy_count": status_counts.get("degraded", 0) + status_counts.get("failed", 0),
718
+ "unchecked_strategy_count": status_counts.get("skipped", 0),
719
+ "daily_strategy_count": sum(1 for item in coverage if bool(item.get("requires_daily_features"))),
720
+ "status_counts": status_counts,
721
+ "impacted_strategies": impacted,
722
+ "unchecked_strategies": unchecked,
723
+ "missing_snapshot_fields": _missing_field_impacts(coverage, "snapshot_missing_fields"),
724
+ "missing_daily_fields": _missing_field_impacts(coverage, "daily_missing_fields"),
725
+ "next_actions": next_actions,
726
+ }
727
+
728
+
729
+ def _strategy_readiness_item(item: dict[str, Any]) -> dict[str, Any]:
730
+ return {
731
+ "strategy": item.get("strategy", ""),
732
+ "display_name": item.get("display_name", ""),
733
+ "status": item.get("status", ""),
734
+ "requires_daily_features": bool(item.get("requires_daily_features")),
735
+ "snapshot_missing_fields": list(item.get("snapshot_missing_fields", []) or []),
736
+ "daily_missing_fields": list(item.get("daily_missing_fields", []) or []),
737
+ }
738
+
739
+
740
+ def _missing_field_impacts(coverage: list[dict[str, Any]], key: str) -> list[dict[str, Any]]:
741
+ impacts: dict[str, list[str]] = {}
742
+ for item in coverage:
743
+ strategy_name = str(item.get("strategy") or "")
744
+ for field_name in item.get(key, []) or []:
745
+ impacts.setdefault(str(field_name), []).append(strategy_name)
746
+ rows = [
747
+ {
748
+ "field": field_name,
749
+ "strategy_count": len(strategy_names),
750
+ "strategies": sorted(strategy_names),
751
+ }
752
+ for field_name, strategy_names in impacts.items()
753
+ ]
754
+ rows.sort(key=lambda item: (-int(item["strategy_count"]), str(item["field"])))
755
+ return rows
756
+
757
+
758
+ def _overall_status(statuses: list[str]) -> str:
759
+ active = [status for status in statuses if status != "skipped"]
760
+ if not active:
761
+ return "skipped"
762
+ if all(status == "ok" for status in active):
763
+ return "ok"
764
+ if any(status == "ok" for status in active) or any(
765
+ status == "degraded" for status in active
766
+ ):
767
+ return "degraded"
768
+ return "failed"
769
+
770
+
771
+ def _build_health_summary(
772
+ snapshot: SourceCheckResult,
773
+ daily: SourceCheckResult | None,
774
+ ) -> dict[str, Any]:
775
+ return {
776
+ "snapshot": _source_family_health_summary(snapshot),
777
+ "daily": _source_family_health_summary(daily) if daily is not None else {
778
+ "status": "skipped",
779
+ "requested_sources": [],
780
+ "selected_source": "",
781
+ "available_source_count": 0,
782
+ "healthy_sources": [],
783
+ "failing_sources": [],
784
+ "disabled_sources": [],
785
+ "never_seen_sources": [],
786
+ "last_errors": [],
787
+ "fallback_used": False,
788
+ "stale": False,
789
+ "missing_fields": [],
790
+ "error_count": 0,
791
+ },
792
+ }
793
+
794
+
795
+ def _build_freshness_summary(
796
+ snapshot: SourceCheckResult,
797
+ daily: SourceCheckResult | None,
798
+ ) -> dict[str, Any]:
799
+ snapshot_summary = _source_freshness_summary(snapshot, family="snapshot")
800
+ daily_summary = (
801
+ _source_freshness_summary(daily, family="daily")
802
+ if daily is not None
803
+ else _skipped_freshness_summary("daily")
804
+ )
805
+ family_summaries = [snapshot_summary, daily_summary]
806
+ warnings = [
807
+ f"{item['family']}:{item['data_state']}"
808
+ for item in family_summaries
809
+ if item.get("data_state") not in {"fresh", "not_requested"}
810
+ ]
811
+ return {
812
+ "snapshot": snapshot_summary,
813
+ "daily": daily_summary,
814
+ "fresh_enough": not warnings,
815
+ "fresh_family_count": sum(1 for item in family_summaries if item.get("data_state") == "fresh"),
816
+ "stale_family_count": sum(1 for item in family_summaries if item.get("data_state") == "stale"),
817
+ "fallback_family_count": sum(1 for item in family_summaries if item.get("fallback_used")),
818
+ "unavailable_family_count": sum(1 for item in family_summaries if item.get("data_state") == "unavailable"),
819
+ "not_checked_family_count": sum(1 for item in family_summaries if item.get("data_state") == "not_checked"),
820
+ "warnings": warnings,
821
+ }
822
+
823
+
824
+ def _source_freshness_summary(
825
+ result: SourceCheckResult,
826
+ *,
827
+ family: str,
828
+ ) -> dict[str, Any]:
829
+ quality_status = str(result.quality_summary.get("status", ""))
830
+ quality_anomaly_count = len(result.quality_summary.get("anomalies", []) or [])
831
+ if result.status == "skipped":
832
+ data_state = "not_checked"
833
+ cache_state = "not_checked"
834
+ recommendation = f"Run live {family} check before relying on fresh data."
835
+ elif result.status == "failed":
836
+ data_state = "unavailable"
837
+ cache_state = "unavailable"
838
+ recommendation = f"Fix {family} source errors before running live screening."
839
+ elif result.stale:
840
+ data_state = "stale"
841
+ cache_state = "stale_cache"
842
+ recommendation = f"Refresh {family} data; current result came from stale cache."
843
+ elif result.fallback_used:
844
+ data_state = "fallback"
845
+ cache_state = "last_good_cache" if family == "snapshot" else "provider_fallback"
846
+ recommendation = f"Review {family} source errors; data used a fallback path."
847
+ elif result.missing_fields or quality_status == "degraded":
848
+ data_state = "degraded"
849
+ cache_state = "live"
850
+ recommendation = f"Review {family} missing fields or quality anomalies before trusting filters."
851
+ else:
852
+ data_state = "fresh"
853
+ cache_state = "live"
854
+ recommendation = ""
855
+ return {
856
+ "family": family,
857
+ "status": result.status,
858
+ "data_state": data_state,
859
+ "cache_state": cache_state,
860
+ "selected_source": result.source,
861
+ "rows": result.rows,
862
+ "fallback_used": result.fallback_used,
863
+ "stale": result.stale,
864
+ "stale_age_hours": result.stale_age_hours,
865
+ "missing_fields": list(result.missing_fields),
866
+ "error_count": len(result.errors),
867
+ "quality_status": quality_status,
868
+ "quality_anomaly_count": quality_anomaly_count,
869
+ "recommendation": recommendation,
870
+ }
871
+
872
+
873
+ def _skipped_freshness_summary(family: str) -> dict[str, Any]:
874
+ return {
875
+ "family": family,
876
+ "status": "skipped",
877
+ "data_state": "not_requested",
878
+ "cache_state": "not_requested",
879
+ "selected_source": "",
880
+ "rows": 0,
881
+ "fallback_used": False,
882
+ "stale": False,
883
+ "stale_age_hours": None,
884
+ "missing_fields": [],
885
+ "error_count": 0,
886
+ "quality_status": "",
887
+ "quality_anomaly_count": 0,
888
+ "recommendation": "",
889
+ }
890
+
891
+
892
+ def _source_family_health_summary(result: SourceCheckResult) -> dict[str, Any]:
893
+ health = result.health or {}
894
+ requested_sources = list(dict.fromkeys([*result.sources, *health.keys()]))
895
+ healthy_sources: list[str] = []
896
+ failing_sources: list[str] = []
897
+ disabled_sources: list[str] = []
898
+ never_seen_sources: list[str] = []
899
+ last_errors: list[dict[str, Any]] = []
900
+
901
+ for source in requested_sources:
902
+ state = health.get(source, {}) or {}
903
+ successes = float(state.get("successes", 0.0))
904
+ failures = float(state.get("failures", 0.0))
905
+ total_failures = float(state.get("total_failures", 0.0))
906
+ disabled = bool(state.get("disabled", False))
907
+ last_error = str(state.get("last_error", ""))
908
+ if disabled:
909
+ disabled_sources.append(source)
910
+ elif failures > 0:
911
+ failing_sources.append(source)
912
+ elif successes > 0:
913
+ healthy_sources.append(source)
914
+ elif total_failures == 0:
915
+ never_seen_sources.append(source)
916
+ if last_error:
917
+ last_errors.append({
918
+ "source": source,
919
+ "error": last_error,
920
+ "failures": failures,
921
+ "total_failures": total_failures,
922
+ "disabled": disabled,
923
+ "cooldown_remaining_seconds": float(state.get("cooldown_remaining_seconds", 0.0)),
924
+ })
925
+
926
+ return {
927
+ "status": result.status,
928
+ "requested_sources": requested_sources,
929
+ "selected_source": result.source,
930
+ "available_source_count": len(requested_sources) - len(disabled_sources),
931
+ "healthy_sources": healthy_sources,
932
+ "failing_sources": failing_sources,
933
+ "disabled_sources": disabled_sources,
934
+ "never_seen_sources": never_seen_sources,
935
+ "last_errors": last_errors,
936
+ "fallback_used": result.fallback_used,
937
+ "stale": result.stale,
938
+ "missing_fields": list(result.missing_fields),
939
+ "error_count": len(result.errors),
940
+ "quality_status": result.quality_summary.get("status", ""),
941
+ "quality_anomaly_count": len(result.quality_summary.get("anomalies", []) or []),
942
+ }
943
+
944
+
945
+ def _build_recommendations(
946
+ snapshot: SourceCheckResult,
947
+ daily: SourceCheckResult | None,
948
+ ) -> list[str]:
949
+ recommendations: list[str] = []
950
+ if snapshot.status == "skipped" and (daily is None or daily.status == "skipped"):
951
+ recommendations.append(
952
+ "Live data-source checks were skipped: rerun without --no-live before relying on fresh screening."
953
+ )
954
+ if snapshot.status == "failed":
955
+ recommendations.append(
956
+ "Snapshot failed: check network access and SNAPSHOT_SOURCE_PRIORITY; attach this doctor output to issue #18."
957
+ )
958
+ elif snapshot.fallback_used:
959
+ recommendations.append(
960
+ "Snapshot used last-good cache: live sources are degraded; inspect snapshot.errors for the failing provider."
961
+ )
962
+ if snapshot.quality_summary.get("anomalies"):
963
+ anomalies = [
964
+ str(item)
965
+ for item in list(snapshot.quality_summary.get("anomalies", []) or [])[:4]
966
+ ]
967
+ recommendations.append(
968
+ "Snapshot quality anomalies detected: "
969
+ + ", ".join(anomalies)
970
+ + "; inspect snapshot.quality_summary before trusting hard filters."
971
+ )
972
+ if daily is not None:
973
+ if daily.status == "failed":
974
+ recommendations.append(
975
+ "Daily K-line failed: try DAILY_SOURCE=auto or verify TUSHARE_TOKEN/Tencent/Sina/Akshare connectivity."
976
+ )
977
+ elif daily.stale:
978
+ recommendations.append(
979
+ "Daily K-line used stale cache: refresh network-backed sources before relying on fresh technical filters."
980
+ )
981
+ recommendations.extend(_source_health_recommendations("Snapshot", snapshot))
982
+ if daily is not None:
983
+ recommendations.extend(_source_health_recommendations("Daily K-line", daily))
984
+ if not recommendations:
985
+ recommendations.append("Data sources look usable for a basic AlphaSift run.")
986
+ return recommendations
987
+
988
+
989
+ def _source_health_recommendations(label: str, result: SourceCheckResult) -> list[str]:
990
+ summary = _source_family_health_summary(result)
991
+ recommendations: list[str] = []
992
+ disabled = summary.get("disabled_sources", []) or []
993
+ failing = summary.get("failing_sources", []) or []
994
+ if disabled:
995
+ recommendations.append(
996
+ f"{label} health guard disabled sources: {','.join(disabled)}; wait for cooldown or lower their priority."
997
+ )
998
+ if failing:
999
+ recommendations.append(
1000
+ f"{label} sources have recent failures: {','.join(failing)}; inspect health_summary.last_errors."
1001
+ )
1002
+ return recommendations
1003
+
1004
+
1005
+ def _has_configured_tushare() -> bool:
1006
+ import os
1007
+
1008
+ return bool(
1009
+ os.getenv("TUSHARE_TOKEN", "").strip()
1010
+ or os.getenv("TUSHARE_API_TOKEN", "").strip()
1011
+ )
1012
+
1013
+
1014
+ def write_doctor_report(path: str | Path, result: DataSourcesDoctorResult) -> Path:
1015
+ import json
1016
+
1017
+ output = Path(path)
1018
+ output.parent.mkdir(parents=True, exist_ok=True)
1019
+ output.write_text(
1020
+ json.dumps(result.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8"
1021
+ )
1022
+ return output
1023
+
1024
+
1025
+ def doctor_radar_readiness(
1026
+ config: Config,
1027
+ *,
1028
+ pack_dir: Path | None = None,
1029
+ trade_date: str | None = None,
1030
+ ) -> dict[str, Any]:
1031
+ """Check CN DailyPack freshness, pattern catalog, LLM track, and IM webhook readiness."""
1032
+ from alphasift import pack
1033
+ from alphasift.notify import notify_readiness
1034
+ from alphasift.patterns import list_patterns
1035
+
1036
+ directory = Path(pack_dir).expanduser() if pack_dir is not None else pack.pack_dir(config)
1037
+ expected = trade_date or pack.expected_trade_date()
1038
+ pack_info: dict[str, Any] = {
1039
+ "directory": str(directory),
1040
+ "exists": directory.is_dir(),
1041
+ "valid": False,
1042
+ "expected_trade_date": expected,
1043
+ "trade_date": None,
1044
+ "fresh": False,
1045
+ "dates": 0,
1046
+ "codes": 0,
1047
+ "size_mb": None,
1048
+ "error": None,
1049
+ }
1050
+ if directory.is_dir():
1051
+ try:
1052
+ loaded = pack.load_pack(directory)
1053
+ npz_path = directory / "daily.npz"
1054
+ size_mb = round(npz_path.stat().st_size / (1024 * 1024), 2) if npz_path.is_file() else None
1055
+ fresh = pack.is_fresh(loaded, expected)
1056
+ pack_info.update({
1057
+ "valid": True,
1058
+ "trade_date": loaded.trade_date,
1059
+ "fresh": fresh,
1060
+ "dates": int(len(loaded.dates)),
1061
+ "codes": int(len(loaded.codes)),
1062
+ "size_mb": size_mb,
1063
+ })
1064
+ except Exception as exc: # noqa: BLE001
1065
+ pack_info["error"] = str(exc)[:240]
1066
+
1067
+ mirror_sync_ok = True
1068
+ pattern_error = None
1069
+ specs = []
1070
+ try:
1071
+ specs = list_patterns(include_experimental=True)
1072
+ except Exception as exc: # noqa: BLE001
1073
+ mirror_sync_ok = False
1074
+ pattern_error = str(exc)[:240]
1075
+
1076
+ active_patterns = [s.name for s in specs if s.status == "active"]
1077
+ experimental_patterns = [s.name for s in specs if s.status == "experimental"]
1078
+ push_info = notify_readiness(config)
1079
+ llm_ready = config.has_usable_llm_config() if hasattr(config, "has_usable_llm_config") else config.has_llm_config()
1080
+
1081
+ recommendations: list[str] = []
1082
+ if not pack_info["valid"]:
1083
+ recommendations.append(
1084
+ "CN DailyPack 未就绪:数据包仅限本地/私有使用,请运行 `alphasift pack build`(或 `python scripts/build_pack.py backfill`)构建本地日线包。"
1085
+ )
1086
+ elif not pack_info["fresh"]:
1087
+ recommendations.append(
1088
+ f"CN DailyPack 日期为 {pack_info['trade_date']},早于预期交易日 {expected},可运行增量更新或拉取最新包。"
1089
+ )
1090
+ if not mirror_sync_ok:
1091
+ recommendations.append(f"形态目录同步检查失败:{pattern_error}")
1092
+ if not push_info["any_configured"]:
1093
+ recommendations.append(
1094
+ "未配置企微/飞书/Telegram Webhook,每日推送将静默跳过;需要通知时配置 WECOM_WEBHOOK_URL / FEISHU_WEBHOOK_URL / TELEGRAM_BOT_TOKEN+CHAT_ID。"
1095
+ )
1096
+ if not llm_ready:
1097
+ recommendations.append("未配置 LLM Key,战绩跟踪与筛选将自动仅运行纯规则赛道(rules track)。")
1098
+
1099
+ if not pack_info["valid"] or not pack_info["fresh"] or not mirror_sync_ok:
1100
+ status = "degraded"
1101
+ else:
1102
+ status = "ok"
1103
+
1104
+ return {
1105
+ "status": status,
1106
+ "generated_at": datetime.now(timezone.utc).isoformat(),
1107
+ "pack": pack_info,
1108
+ "patterns": {
1109
+ "total": len(specs),
1110
+ "active_count": len(active_patterns),
1111
+ "experimental_count": len(experimental_patterns),
1112
+ "active": active_patterns,
1113
+ "experimental": experimental_patterns,
1114
+ "mirror_sync_ok": mirror_sync_ok,
1115
+ "error": pattern_error,
1116
+ },
1117
+ "notify": push_info,
1118
+ "llm": {
1119
+ "configured": llm_ready,
1120
+ "ai_track_mode": "enabled" if llm_ready else "rules_only",
1121
+ },
1122
+ "recommendations": recommendations,
1123
+ }