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/pipeline.py ADDED
@@ -0,0 +1,1010 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Main pipeline — orchestrates L1 → L2 → result."""
3
+
4
+ import logging
5
+ import math
6
+ import uuid
7
+ from pathlib import Path
8
+
9
+ import pandas as pd
10
+
11
+ from alphasift.config import Config
12
+ from alphasift.candidate_context import collect_candidate_context
13
+ from alphasift.context import build_llm_context
14
+ from alphasift.daily import enrich_daily_features
15
+ from alphasift.dsa_provider import apply_dsa_provider_context
16
+ from alphasift.markets import get_market, latest_settled_close
17
+ from alphasift.filter import (
18
+ apply_hard_filters,
19
+ hard_filter_rejection_summary,
20
+ hard_filter_waterfall,
21
+ requires_daily_features,
22
+ without_daily_filters,
23
+ )
24
+ from alphasift.industry import enrich_industry_concepts
25
+ from alphasift.models import Pick, ScreenResult
26
+ from alphasift.normalize import (
27
+ normalize_code,
28
+ safe_bool as _safe_bool,
29
+ safe_float as _safe_float,
30
+ safe_int as _safe_int,
31
+ safe_text,
32
+ )
33
+ from alphasift.daily import _DAILY_FEATURE_DEFAULTS
34
+ from alphasift.pack import (
35
+ DailyPack,
36
+ PackError,
37
+ SnapshotStitchError,
38
+ expected_trade_date,
39
+ load_pack,
40
+ pack_dir,
41
+ stitch_snapshot,
42
+ )
43
+ from alphasift.pack_features import compute_pack_daily_features
44
+ from alphasift.post_analysis import normalize_post_analyzers, run_post_analyzers
45
+ from alphasift.ranker import rank_candidates_with_metadata
46
+ from alphasift.risk import (
47
+ PORTFOLIO_DIVERSITY_SKIPPED_NOTE,
48
+ apply_portfolio_overlay,
49
+ apply_risk_overlay,
50
+ summarize_portfolio_exposure,
51
+ )
52
+ from alphasift.scorer import compute_screen_scores, explain_topic_alignment, factor_score_columns
53
+ from alphasift.snapshot import _missing_required_columns, fetch_snapshot_with_fallback
54
+ from alphasift.strategy import load_all_strategies
55
+
56
+ logger = logging.getLogger(__name__)
57
+
58
+
59
+ def screen(
60
+ strategy: str,
61
+ *,
62
+ market: str = "cn",
63
+ max_output: int | None = None,
64
+ use_llm: bool = True,
65
+ llm_context: str | None = None,
66
+ llm_context_files: list[str | Path] | None = None,
67
+ candidate_context_files: list[str | Path] | None = None,
68
+ collect_llm_candidate_context: bool | None = None,
69
+ candidate_context_max_candidates: int | None = None,
70
+ candidate_context_providers: list[str] | None = None,
71
+ industry_map_files: list[str | Path] | None = None,
72
+ industry_provider: str | None = None,
73
+ post_analyzers: list[str] | None = None,
74
+ post_analysis_max_picks: int | None = None,
75
+ daily_enrich: bool | None = None,
76
+ daily_enrich_max_candidates: int | None = None,
77
+ explain_filters: bool = False,
78
+ deep_analysis: bool = False,
79
+ deep_analysis_max_picks: int | None = None,
80
+ context: dict[str, object] | None = None,
81
+ config: Config | None = None,
82
+ snapshot_df: pd.DataFrame | None = None,
83
+ allow_snapshot_refetch: bool = True,
84
+ daily_pack: DailyPack | None = None,
85
+ ) -> ScreenResult:
86
+ """Execute stock screening with the given strategy.
87
+
88
+ Args:
89
+ strategy: Strategy name (matches a YAML file in strategies/).
90
+ market: Market id from ``alphasift.markets`` (cn, us, hk, jp, kr, tw, in). A strategy must declare the
91
+ market in its own market_scope to be runnable against it.
92
+ max_output: Override max output count from strategy.
93
+ use_llm: Whether to use LLM for L2 ranking.
94
+ llm_context: Optional market/news/theme context supplied to the LLM ranker.
95
+ llm_context_files: Optional text files appended to LLM context.
96
+ candidate_context_files: Optional CSV/JSON/JSONL files keyed by code with candidate-level context.
97
+ collect_llm_candidate_context: Whether to fetch Top-K candidate news/fund-flow context for LLM.
98
+ candidate_context_max_candidates: Max candidates to fetch external context for.
99
+ candidate_context_providers: Optional provider names: news, fund_flow, announcement.
100
+ industry_map_files: Optional code->industry/concepts files used before L1/L2.
101
+ industry_provider: Optional provider for board mapping, e.g. "akshare".
102
+ post_analyzers: Optional L3 analyzers, e.g. ["scorecard", "dsa"].
103
+ post_analysis_max_picks: Override max number of picks sent to post analyzers.
104
+ daily_enrich: Whether to enrich shortlisted candidates with daily K-line features.
105
+ daily_enrich_max_candidates: Max candidates to enrich after snapshot filtering.
106
+ explain_filters: Whether to include sequential hard-filter waterfall diagnostics.
107
+ deep_analysis: Backward-compatible alias for post_analyzers=["dsa"].
108
+ deep_analysis_max_picks: Backward-compatible max-picks alias for DSA.
109
+ context: Optional host runtime context. DSA may provide LLM settings and
110
+ callable data providers under context["dsa"].
111
+ config: Runtime config. Defaults to Config.from_env().
112
+ snapshot_df: Optional pre-fetched snapshot DataFrame to reuse across multiple
113
+ screens of the same market. Copied internally; falls back to live
114
+ snapshot fetch if empty or missing strategy-required columns unless
115
+ ``allow_snapshot_refetch=False``.
116
+ allow_snapshot_refetch: Whether to call ``fetch_snapshot_with_fallback``
117
+ when ``snapshot_df`` is empty or lacks strategy-required columns.
118
+ Track-record sessions set this to ``False`` so an unvalidated
119
+ replacement snapshot can never bypass session freshness gates.
120
+
121
+ Returns:
122
+ ScreenResult with ranked picks.
123
+ """
124
+ if config is None:
125
+ config = Config.from_env()
126
+
127
+ market = get_market(market).id
128
+
129
+ run_id = uuid.uuid4().hex[:12]
130
+ degradation: list[str] = []
131
+
132
+ # 1. Load strategy
133
+ strategies = load_all_strategies(config.strategies_dir)
134
+ if strategy not in strategies:
135
+ available = ", ".join(strategies.keys()) or "(none)"
136
+ raise ValueError(f"Strategy '{strategy}' not found. Available: {available}")
137
+
138
+ strat = strategies[strategy]
139
+ screening = strat.screening
140
+ if market not in screening.market_scope:
141
+ raise ValueError(
142
+ f"Strategy '{strategy}' does not support market '{market}'. "
143
+ f"Supported: {', '.join(screening.market_scope)}"
144
+ )
145
+ output_count = max_output or screening.max_output
146
+ analyzer_names = normalize_post_analyzers(
147
+ post_analyzers if post_analyzers is not None else config.post_analyzers
148
+ )
149
+ if deep_analysis and "dsa" not in analyzer_names:
150
+ analyzer_names.append("dsa")
151
+ analyzer_max_picks = (
152
+ post_analysis_max_picks
153
+ or deep_analysis_max_picks
154
+ )
155
+ daily_needed = requires_daily_features(screening.hard_filters)
156
+ daily_requested = config.daily_enrich_enabled if daily_enrich is None else daily_enrich
157
+ daily_limit = daily_enrich_max_candidates or config.daily_enrich_max_candidates
158
+ snapshot_filters = without_daily_filters(screening.hard_filters) if daily_needed else screening.hard_filters
159
+
160
+ # 2. Fetch snapshot (or isolate a valid pre-fetched snapshot for reuse)
161
+ required_snapshot_columns = _required_snapshot_columns(snapshot_filters)
162
+ if snapshot_df is not None:
163
+ supplied_market = str(snapshot_df.attrs.get("market") or "").strip().lower()
164
+ if supplied_market and supplied_market != market:
165
+ raise ValueError(
166
+ f"snapshot_df market {supplied_market!r} does not match requested market {market!r}"
167
+ )
168
+ missing_supplied = (
169
+ _missing_required_columns(snapshot_df, required_snapshot_columns)
170
+ if snapshot_df is not None and not snapshot_df.empty
171
+ else []
172
+ )
173
+ if snapshot_df is not None and not snapshot_df.empty and not missing_supplied:
174
+ working_snapshot = snapshot_df.copy()
175
+ working_snapshot.attrs = {
176
+ key: list(val) if isinstance(val, list) else val
177
+ for key, val in snapshot_df.attrs.items()
178
+ }
179
+ snapshot_df = working_snapshot
180
+ elif snapshot_df is not None and not allow_snapshot_refetch:
181
+ detail = (
182
+ f"missing required columns: {','.join(missing_supplied)}"
183
+ if missing_supplied
184
+ else "empty snapshot"
185
+ )
186
+ raise RuntimeError(
187
+ f"Supplied snapshot for market {market!r} cannot run {strategy!r} ({detail})"
188
+ )
189
+ else:
190
+ snapshot_df = fetch_snapshot_with_fallback(
191
+ config.snapshot_source_priority,
192
+ required_columns=required_snapshot_columns,
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
+ effective_industry_map_files = (
199
+ list(industry_map_files)
200
+ if industry_map_files is not None
201
+ else list(config.industry_map_files)
202
+ )
203
+ effective_industry_provider = (
204
+ industry_provider
205
+ if industry_provider is not None
206
+ else config.industry_provider
207
+ )
208
+ effective_industry_provider = str(effective_industry_provider or "none").strip().lower()
209
+ if market != "cn" and effective_industry_provider not in {"", "none", "off", "false"}:
210
+ # Board providers (akshare / eastmoney) only know A-share codes.
211
+ degradation.append(
212
+ f"Industry provider {effective_industry_provider} skipped: A-share only (market={market})"
213
+ )
214
+ effective_industry_provider = "none"
215
+ if effective_industry_map_files or effective_industry_provider not in {"", "none", "off", "false"}:
216
+ snapshot_df, industry_notes = enrich_industry_concepts(
217
+ snapshot_df,
218
+ map_files=effective_industry_map_files,
219
+ provider=effective_industry_provider,
220
+ max_boards=config.industry_provider_max_boards,
221
+ provider_cache_dir=config.industry_provider_cache_dir,
222
+ provider_cache_ttl_hours=config.industry_provider_cache_ttl_hours,
223
+ )
224
+ degradation.extend(f"Industry/concepts enrichment: {item}" for item in industry_notes)
225
+ elif (
226
+ market == "cn"
227
+ and config.industry_auto_backfill
228
+ and _industry_coverage(snapshot_df) < _INDUSTRY_BACKFILL_MIN_COVERAGE
229
+ ):
230
+ # Routine backfill is not a degradation; only report it when the run
231
+ # still lacks industry labels afterwards.
232
+ snapshot_df, industry_notes = enrich_industry_concepts(
233
+ snapshot_df,
234
+ provider="eastmoney",
235
+ provider_cache_dir=config.industry_provider_cache_dir,
236
+ )
237
+ if _industry_coverage(snapshot_df) < _INDUSTRY_BACKFILL_MIN_COVERAGE:
238
+ degradation.extend(f"Industry auto-backfill: {item}" for item in industry_notes)
239
+ else:
240
+ for item in industry_notes:
241
+ logger.info("Industry auto-backfill: %s", item)
242
+ snapshot_count = len(snapshot_df)
243
+ snapshot_source = str(snapshot_df.attrs.get("snapshot_source", ""))
244
+ source_errors = [str(item) for item in snapshot_df.attrs.get("source_errors", [])]
245
+ for item in snapshot_df.attrs.get("source_order_notes", []):
246
+ logger.info("%s", item)
247
+ degradation.extend(f"Snapshot source fallback: {item}" for item in source_errors)
248
+ if bool(snapshot_df.attrs.get("fallback_used")):
249
+ stale_age = snapshot_df.attrs.get("stale_age_hours")
250
+ if stale_age is None:
251
+ degradation.append("Snapshot source fallback: last_good_cache stale")
252
+ else:
253
+ degradation.append(
254
+ f"Snapshot source fallback: last_good_cache stale_age_hours={stale_age}"
255
+ )
256
+
257
+ # 3. L1 hard filter. If a strategy needs daily features, first apply only
258
+ # snapshot-safe filters, then enrich a narrowed candidate pool.
259
+ if explain_filters:
260
+ snapshot_waterfall = hard_filter_waterfall(
261
+ snapshot_df,
262
+ snapshot_filters,
263
+ include_quantiles=True,
264
+ )
265
+ if snapshot_waterfall:
266
+ degradation.append(
267
+ "Snapshot hard-filter waterfall: "
268
+ + _format_filter_waterfall(snapshot_waterfall)
269
+ )
270
+ df = apply_hard_filters(snapshot_df, snapshot_filters)
271
+ after_filter_count = len(df)
272
+
273
+ if df.empty:
274
+ return ScreenResult(
275
+ strategy=strategy,
276
+ market=market,
277
+ snapshot_count=snapshot_count,
278
+ after_filter_count=0,
279
+ run_id=run_id,
280
+ track="rules",
281
+ degradation=[*degradation, "No candidates after hard filter"],
282
+ snapshot_source=snapshot_source,
283
+ source_errors=source_errors,
284
+ strategy_version=strat.version,
285
+ strategy_category=strat.category,
286
+ post_analyzers=analyzer_names,
287
+ daily_enriched=False,
288
+ risk_enabled=config.risk_enabled,
289
+ portfolio_diversity_enabled=config.portfolio_diversity_enabled,
290
+ )
291
+
292
+ daily_enriched = False
293
+ daily_enrich_count = 0
294
+ daily_source_counts: dict[str, int] = {}
295
+ daily_quality_flag_counts: dict[str, int] = {}
296
+ if daily_needed or daily_requested:
297
+ active_pack = _resolve_cn_daily_pack(
298
+ market=market,
299
+ snapshot_df=snapshot_df,
300
+ config=config,
301
+ daily_pack=daily_pack,
302
+ degradation=degradation,
303
+ )
304
+ enriched: pd.DataFrame | None = None
305
+ if active_pack is not None:
306
+ try:
307
+ quote_date = str(snapshot_df.attrs.get("quote_date") or "").strip()[:10] or None
308
+ enriched, matched_count = _attach_pack_daily_features(
309
+ df, active_pack, as_of_date=quote_date
310
+ )
311
+ daily_enriched = True
312
+ daily_enrich_count = matched_count
313
+ if matched_count > 0:
314
+ daily_source_counts = {"pack": matched_count}
315
+ if "daily_quality_flags" in enriched.columns:
316
+ for raw_flags in enriched["daily_quality_flags"]:
317
+ if pd.isna(raw_flags):
318
+ continue
319
+ for part in str(raw_flags).replace(";", ",").replace("|", ",").split(","):
320
+ flag = part.strip()
321
+ if flag and flag not in {"none", "ok"}:
322
+ daily_quality_flag_counts[flag] = daily_quality_flag_counts.get(flag, 0) + 1
323
+ used_date = quote_date if (quote_date and quote_date < active_pack.trade_date) else active_pack.trade_date
324
+ enrich_summary = (
325
+ f"Daily K-line enrichment via CN pack ({used_date}) "
326
+ f"matched {matched_count} of {after_filter_count} snapshot-filtered candidates"
327
+ )
328
+ if explain_filters or matched_count < after_filter_count:
329
+ degradation.append(enrich_summary)
330
+ else:
331
+ logger.info("%s", enrich_summary)
332
+ if explain_filters:
333
+ degradation.append(f"Daily K-line sources: pack={matched_count}")
334
+ except Exception as exc:
335
+ degradation.append(f"CN daily pack fallback: {exc}")
336
+ enriched = None
337
+
338
+ if enriched is None:
339
+ provisional = _sort_screened_candidates(compute_screen_scores(df, screening), screening)
340
+ enrich_count = min(daily_limit, len(provisional))
341
+ daily_candidates = provisional.head(enrich_count)
342
+ # config.daily_source's "auto" chain (tushare/tencent/sina/akshare/baostock)
343
+ # is CN-only and cannot resolve Yahoo symbols, so default non-CN runs to
344
+ # the yfinance adapter unless the caller explicitly configured a source.
345
+ effective_daily_source = (
346
+ "yfinance" if market != "cn" and config.daily_source in ("auto", "")
347
+ else config.daily_source
348
+ )
349
+ try:
350
+ enriched = enrich_daily_features(
351
+ daily_candidates,
352
+ max_rows=enrich_count,
353
+ lookback_days=config.daily_lookback_days,
354
+ source=effective_daily_source,
355
+ fetch_retries=config.daily_fetch_retries,
356
+ max_workers=config.daily_fetch_max_workers,
357
+ cache_policy=lambda: _screening_daily_cache_kwargs(config, market),
358
+ )
359
+ daily_enriched = True
360
+ daily_errors = [str(item) for item in enriched.attrs.get("daily_errors", [])]
361
+ daily_enrich_count = int(enriched.attrs.get("daily_success_count", len(enriched)))
362
+ daily_source_counts = dict(enriched.attrs.get("daily_source_counts", {}) or {})
363
+ daily_quality_flag_counts = dict(enriched.attrs.get("daily_quality_flag_counts", {}) or {})
364
+ daily_source_order_notes = [str(item) for item in enriched.attrs.get("daily_source_order_notes", [])]
365
+ daily_source_health_notes = _daily_source_health_notes(
366
+ dict(enriched.attrs.get("daily_source_health", {}) or {})
367
+ )
368
+ enrich_summary = (
369
+ f"Daily K-line enrichment attempted {enrich_count} candidates, "
370
+ f"succeeded {daily_enrich_count} of {after_filter_count} snapshot-filtered candidates"
371
+ )
372
+ if explain_filters or daily_enrich_count < enrich_count:
373
+ degradation.append(enrich_summary)
374
+ else:
375
+ logger.info("%s", enrich_summary)
376
+ if daily_source_counts:
377
+ source_summary = ", ".join(
378
+ f"{name}={count}" for name, count in sorted(daily_source_counts.items())
379
+ )
380
+ if explain_filters:
381
+ degradation.append(f"Daily K-line sources: {source_summary}")
382
+ else:
383
+ logger.info("Daily K-line sources: %s", source_summary)
384
+ if daily_quality_flag_counts:
385
+ flag_summary = ", ".join(
386
+ f"{name}={count}" for name, count in sorted(daily_quality_flag_counts.items())
387
+ )
388
+ degradation.append(f"Daily K-line quality flags: {flag_summary}")
389
+ if daily_source_order_notes:
390
+ degradation.append("Daily K-line source ordering: " + " | ".join(daily_source_order_notes[:3]))
391
+ if daily_source_health_notes:
392
+ degradation.append("Daily K-line source health: " + "; ".join(daily_source_health_notes))
393
+ if daily_errors:
394
+ sample = " | ".join(daily_errors[:5])
395
+ suffix = f" | +{len(daily_errors) - 5} more" if len(daily_errors) > 5 else ""
396
+ degradation.append(f"Daily K-line enrichment row errors: {sample}{suffix}")
397
+ except Exception as exc:
398
+ if daily_needed:
399
+ raise RuntimeError(
400
+ "Daily K-line enrichment is required by this strategy but failed: "
401
+ f"{exc}"
402
+ ) from exc
403
+ degradation.append(f"Daily K-line enrichment skipped: {exc}")
404
+ enriched = None
405
+
406
+ if enriched is not None:
407
+ if daily_needed:
408
+ if explain_filters:
409
+ daily_waterfall = hard_filter_waterfall(
410
+ enriched,
411
+ screening.hard_filters,
412
+ include_quantiles=True,
413
+ )
414
+ if daily_waterfall:
415
+ degradation.append(
416
+ "Daily hard-filter waterfall: "
417
+ + _format_filter_waterfall(daily_waterfall)
418
+ )
419
+ daily_filter_rejections = hard_filter_rejection_summary(
420
+ enriched,
421
+ screening.hard_filters,
422
+ limit=6,
423
+ )
424
+ df = apply_hard_filters(enriched, screening.hard_filters)
425
+ after_filter_count = len(df)
426
+ if daily_filter_rejections:
427
+ degradation.append(
428
+ "Daily hard-filter rejections: "
429
+ + "; ".join(daily_filter_rejections)
430
+ )
431
+ else:
432
+ df = apply_hard_filters(enriched, screening.hard_filters)
433
+ after_filter_count = len(df)
434
+ else:
435
+ df = enriched
436
+
437
+ if not df.empty and active_pack is not None and "daily_quality_flags" in df.columns:
438
+ daily_quality_flag_counts = {}
439
+ for raw_flags in df["daily_quality_flags"]:
440
+ if pd.isna(raw_flags):
441
+ continue
442
+ for part in str(raw_flags).replace(";", ",").replace("|", ",").split(","):
443
+ flag = part.strip()
444
+ if flag and flag not in {"none", "ok"}:
445
+ daily_quality_flag_counts[flag] = daily_quality_flag_counts.get(flag, 0) + 1
446
+
447
+ if df.empty:
448
+ return ScreenResult(
449
+ strategy=strategy,
450
+ market=market,
451
+ strategy_version=strat.version,
452
+ strategy_category=strat.category,
453
+ snapshot_count=snapshot_count,
454
+ after_filter_count=0,
455
+ run_id=run_id,
456
+ track="rules",
457
+ degradation=[*degradation, "No candidates after daily hard filter"],
458
+ snapshot_source=snapshot_source,
459
+ source_errors=source_errors,
460
+ post_analyzers=analyzer_names,
461
+ daily_enriched=daily_enriched,
462
+ daily_enrich_count=daily_enrich_count,
463
+ daily_source_counts=daily_source_counts,
464
+ daily_quality_flag_counts=daily_quality_flag_counts,
465
+ risk_enabled=config.risk_enabled,
466
+ portfolio_diversity_enabled=config.portfolio_diversity_enabled,
467
+ )
468
+
469
+ # 4. Compute screen_score
470
+ df = _sort_screened_candidates(compute_screen_scores(df, screening), screening)
471
+
472
+ # 5. Take Top K for LLM ranking
473
+ top_k = min(
474
+ max(output_count * config.llm_candidate_multiplier, output_count),
475
+ config.llm_max_candidates,
476
+ len(df),
477
+ )
478
+ df_top = df.head(top_k)
479
+
480
+ # 6. Build Pick list
481
+ picks = _df_to_picks(df_top)
482
+
483
+ # 6.5. Host-provided candidate context, e.g. DSA realtime quote,
484
+ # fundamentals, and news. This runs before LLM ranking so L2 can use it.
485
+ degradation.extend(apply_dsa_provider_context(picks, context))
486
+
487
+ # 7. L2 LLM ranking
488
+ llm_ranked = False
489
+ llm_market_view = ""
490
+ llm_selection_logic = ""
491
+ llm_portfolio_risk = ""
492
+ llm_coverage: float | None = None
493
+ llm_parse_errors: list[str] = []
494
+ if use_llm and config.has_llm_config():
495
+ candidate_context_rows: list[dict[str, object]] = []
496
+ event_source_weights = _event_source_weights(screening.event_profile)
497
+ should_collect_candidate_context = (
498
+ config.llm_candidate_context_enabled
499
+ if collect_llm_candidate_context is None
500
+ else collect_llm_candidate_context
501
+ )
502
+ if should_collect_candidate_context and market != "cn":
503
+ # News/announcement/fund-flow providers are A-share (EastMoney) only.
504
+ degradation.append(
505
+ f"Candidate context skipped: providers support market cn only (market={market})"
506
+ )
507
+ elif should_collect_candidate_context:
508
+ candidate_context_rows, candidate_context_errors = collect_candidate_context(
509
+ df_top,
510
+ max_rows=(
511
+ candidate_context_max_candidates
512
+ or config.llm_candidate_context_max_candidates
513
+ ),
514
+ providers=(
515
+ candidate_context_providers
516
+ if candidate_context_providers is not None
517
+ else config.llm_candidate_context_providers
518
+ ),
519
+ news_limit=config.llm_candidate_context_news_limit,
520
+ announcement_limit=config.llm_candidate_context_announcement_limit,
521
+ cache_dir=(
522
+ (config.llm_candidate_context_cache_dir or (config.data_dir / "candidate_context"))
523
+ if config.llm_candidate_context_cache_enabled
524
+ else None
525
+ ),
526
+ cache_ttl_hours=config.llm_candidate_context_cache_ttl_hours,
527
+ source_weights=event_source_weights,
528
+ )
529
+ degradation.append(
530
+ f"Candidate context collected rows={len(candidate_context_rows)}"
531
+ )
532
+ if candidate_context_errors:
533
+ sample = " | ".join(candidate_context_errors[:5])
534
+ suffix = (
535
+ f" | +{len(candidate_context_errors) - 5} more"
536
+ if len(candidate_context_errors) > 5
537
+ else ""
538
+ )
539
+ degradation.append(f"Candidate context row errors: {sample}{suffix}")
540
+ llm_context_degradation: list[str] = []
541
+ effective_context = build_llm_context(
542
+ base_context=llm_context if llm_context is not None else config.llm_context,
543
+ context_files=llm_context_files,
544
+ candidate_context_files=candidate_context_files,
545
+ candidate_context_rows=candidate_context_rows,
546
+ snapshot_df=snapshot_df,
547
+ candidate_df=df_top,
548
+ event_profile=screening.event_profile,
549
+ max_chars=config.llm_context_max_chars,
550
+ degradation=llm_context_degradation,
551
+ )
552
+ degradation.extend(llm_context_degradation)
553
+ llm_prompt_degradation: list[str] = []
554
+ llm_result = rank_candidates_with_metadata(
555
+ picks,
556
+ screening.ranking_hints,
557
+ config.llm_api_key,
558
+ config.llm_model,
559
+ config.llm_base_url,
560
+ context=effective_context,
561
+ candidate_context_rows=candidate_context_rows,
562
+ rank_weight=config.llm_rank_weight,
563
+ max_retries=config.llm_max_retries,
564
+ min_coverage=config.llm_min_coverage,
565
+ fallback_models=config.llm_fallback_models,
566
+ temperature=config.llm_temperature,
567
+ json_mode=config.llm_json_mode,
568
+ silent=config.llm_silent,
569
+ channels=config.llm_channels,
570
+ config_path=str(config.llm_config_path or ""),
571
+ timeout_sec=config.llm_timeout_sec,
572
+ max_tokens=config.llm_max_tokens,
573
+ degradation=llm_prompt_degradation,
574
+ )
575
+ degradation.extend(llm_prompt_degradation)
576
+ picks = llm_result.picks
577
+ llm_market_view = llm_result.market_view
578
+ llm_selection_logic = llm_result.selection_logic
579
+ llm_portfolio_risk = llm_result.portfolio_risk
580
+ llm_coverage = llm_result.coverage
581
+ llm_parse_errors = llm_result.errors
582
+ llm_ranked = bool(llm_result.ranked)
583
+ if not llm_ranked:
584
+ degradation.append("LLM ranking failed: fell back to screen_score")
585
+ for i, p in enumerate(picks):
586
+ p.rank = i + 1
587
+ p.final_score = p.screen_score
588
+ else:
589
+ if use_llm and not config.has_llm_config():
590
+ degradation.append("LLM ranking skipped: no LLM config")
591
+ for i, p in enumerate(picks):
592
+ p.rank = i + 1
593
+ p.final_score = p.screen_score
594
+
595
+ # 8. Independent risk overlay
596
+ if config.risk_enabled:
597
+ picks, risk_degradation = apply_risk_overlay(
598
+ picks,
599
+ max_penalty=config.risk_max_penalty,
600
+ veto_high_risk=config.risk_veto_high,
601
+ profile=screening.risk_profile,
602
+ )
603
+ degradation.extend(risk_degradation)
604
+
605
+ # 9. LLM-driven portfolio overlay. This runs before trimming so an
606
+ # over-crowded sector can make room for a comparable candidate elsewhere.
607
+ portfolio_concentration_notes: list[str] = []
608
+ if config.portfolio_diversity_enabled:
609
+ picks, portfolio_concentration_notes = apply_portfolio_overlay(
610
+ picks,
611
+ max_same_sector=config.portfolio_max_same_llm_sector,
612
+ concentration_penalty=config.portfolio_concentration_penalty,
613
+ profile=screening.portfolio_profile,
614
+ )
615
+ if PORTFOLIO_DIVERSITY_SKIPPED_NOTE in portfolio_concentration_notes:
616
+ degradation.append(PORTFOLIO_DIVERSITY_SKIPPED_NOTE)
617
+
618
+ # 10. Trim to max_output (retaining deferred candidates for exposure diagnostics)
619
+ overflow_picks = picks[output_count:]
620
+ picks = picks[:output_count]
621
+
622
+ # 11. Optional L3 post-analysis, DSA is only one possible analyzer.
623
+ if analyzer_names:
624
+ picks, post_degradation = run_post_analyzers(
625
+ picks,
626
+ analyzer_names=analyzer_names,
627
+ run_id=run_id,
628
+ config=config,
629
+ max_picks=analyzer_max_picks,
630
+ scorecard_profile=screening.scorecard_profile,
631
+ )
632
+ degradation.extend(post_degradation)
633
+
634
+ raw_bucket_cap = (screening.portfolio_profile or {}).get("max_same_bucket")
635
+ effective_bucket_cap = (
636
+ int(raw_bucket_cap)
637
+ if isinstance(raw_bucket_cap, (int, float))
638
+ and not isinstance(raw_bucket_cap, bool)
639
+ and math.isfinite(float(raw_bucket_cap))
640
+ and int(raw_bucket_cap) > 0
641
+ else config.portfolio_max_same_llm_sector
642
+ )
643
+ portfolio_topic_exposure, overconcentrated_topics, replacement_candidates = summarize_portfolio_exposure(
644
+ picks,
645
+ candidate_pool=overflow_picks,
646
+ max_same_bucket=effective_bucket_cap,
647
+ buckets=(screening.portfolio_profile or {}).get("buckets"),
648
+ )
649
+
650
+ return ScreenResult(
651
+ strategy=strategy,
652
+ market=market,
653
+ strategy_version=strat.version,
654
+ strategy_category=strat.category,
655
+ snapshot_count=snapshot_count,
656
+ after_filter_count=after_filter_count,
657
+ picks=picks,
658
+ run_id=run_id,
659
+ track="ai" if llm_ranked else "rules",
660
+ llm_ranked=llm_ranked,
661
+ llm_market_view=llm_market_view,
662
+ llm_selection_logic=llm_selection_logic,
663
+ llm_portfolio_risk=llm_portfolio_risk,
664
+ llm_coverage=llm_coverage,
665
+ llm_parse_errors=llm_parse_errors,
666
+ degradation=degradation,
667
+ snapshot_source=snapshot_source,
668
+ source_errors=source_errors,
669
+ deep_analysis_requested=("dsa" in analyzer_names),
670
+ post_analyzers=analyzer_names,
671
+ daily_enriched=daily_enriched,
672
+ daily_enrich_count=daily_enrich_count,
673
+ daily_source_counts=daily_source_counts,
674
+ daily_quality_flag_counts=daily_quality_flag_counts,
675
+ risk_enabled=config.risk_enabled,
676
+ portfolio_diversity_enabled=config.portfolio_diversity_enabled,
677
+ portfolio_concentration_notes=portfolio_concentration_notes,
678
+ portfolio_topic_exposure=portfolio_topic_exposure,
679
+ overconcentrated_topics=overconcentrated_topics,
680
+ replacement_candidates=replacement_candidates,
681
+ )
682
+
683
+
684
+ def _df_to_picks(df: pd.DataFrame) -> list[Pick]:
685
+ """Convert DataFrame rows to Pick objects."""
686
+ picks = []
687
+ factor_cols = factor_score_columns()
688
+ for i, (_, row) in enumerate(df.iterrows()):
689
+ factor_scores = {
690
+ factor: _safe_float(row.get(col)) or 0.0
691
+ for factor, col in factor_cols.items()
692
+ if col in df.columns
693
+ }
694
+ raw_industry = row.get("industry", row.get("行业", row.get("所属行业", "")))
695
+ raw_concepts = row.get("concepts", row.get("概念", row.get("概念题材", "")))
696
+ raw_board_summary = row.get("board_heat_summary")
697
+ align = explain_topic_alignment(raw_industry, raw_concepts, raw_board_summary)
698
+ industry_val = _safe_text(raw_industry)
699
+ concepts_val = _safe_text(raw_concepts)
700
+ board_summary_val = _safe_text(raw_board_summary)
701
+ screen_val = _safe_float(row.get("screen_score")) or 0.0
702
+ picks.append(Pick(
703
+ rank=i + 1,
704
+ code=normalize_code(row.get("code", row.get("代码", "")), allow_ticker=True),
705
+ name=str(row.get("name", row.get("名称", row.get("股票名称", "")))),
706
+ screen_score=screen_val,
707
+ final_score=screen_val,
708
+ price=_safe_float(row.get("price", row.get("最新价"))) or 0.0,
709
+ change_pct=_safe_float(row.get("change_pct", row.get("涨跌幅"))) or 0.0,
710
+ amount=_safe_float(row.get("amount", row.get("成交额"))) or 0.0,
711
+ total_mv=_safe_float(row.get("total_mv", row.get("总市值"))),
712
+ turnover_rate=_safe_float(row.get("turnover_rate", row.get("换手率"))),
713
+ volume_ratio=_safe_float(row.get("volume_ratio", row.get("量比"))),
714
+ pe_ratio=_safe_float(row.get("pe_ratio", row.get("市盈率"))),
715
+ pb_ratio=_safe_float(row.get("pb_ratio", row.get("市净率"))),
716
+ industry=industry_val,
717
+ concepts=concepts_val,
718
+ industry_rank=_safe_int(row.get("industry_rank")),
719
+ industry_change_pct=_safe_float(row.get("industry_change_pct")),
720
+ industry_heat_score=_safe_float(row.get("industry_heat_score")),
721
+ concept_heat_score=_safe_float(row.get("concept_heat_score")),
722
+ board_heat_score=_safe_float(row.get("board_heat_score")),
723
+ board_heat_latest_score=_safe_float(row.get("board_heat_latest_score")),
724
+ board_heat_trend_score=_safe_float(row.get("board_heat_trend_score")),
725
+ board_heat_persistence_score=_safe_float(row.get("board_heat_persistence_score")),
726
+ board_heat_cooling_score=_safe_float(row.get("board_heat_cooling_score")),
727
+ board_heat_observations=_safe_int(row.get("board_heat_observations")),
728
+ board_heat_state=_safe_text(row.get("board_heat_state")),
729
+ board_heat_summary=board_summary_val,
730
+ change_60d=_safe_float(row.get("change_60d")),
731
+ signal_score=_safe_float(row.get("signal_score")),
732
+ ma_bullish=_safe_bool(row.get("ma_bullish")),
733
+ price_above_ma20=_safe_bool(row.get("price_above_ma20")),
734
+ macd_status=str(row.get("macd_status", "") or ""),
735
+ rsi_status=str(row.get("rsi_status", "") or ""),
736
+ breakout_20d_pct=_safe_float(row.get("breakout_20d_pct")),
737
+ range_20d_pct=_safe_float(row.get("range_20d_pct")),
738
+ volume_ratio_20d=_safe_float(row.get("volume_ratio_20d")),
739
+ body_pct=_safe_float(row.get("body_pct")),
740
+ pullback_to_ma20_pct=_safe_float(row.get("pullback_to_ma20_pct")),
741
+ consolidation_days_20d=_safe_int(row.get("consolidation_days_20d")),
742
+ volatility_20d_pct=_safe_float(row.get("volatility_20d_pct")),
743
+ max_drawdown_20d_pct=_safe_float(row.get("max_drawdown_20d_pct")),
744
+ atr_20_pct=_safe_float(row.get("atr_20_pct")),
745
+ daily_quality_score=_safe_float(row.get("daily_quality_score")),
746
+ daily_quality_flags=_safe_text(row.get("daily_quality_flags")),
747
+ daily_source=_safe_text(row.get("daily_source")),
748
+ factor_scores=factor_scores,
749
+ topic_alignment_status=str(align["status"]),
750
+ topic_alignment_role=str(align["role"]),
751
+ topic_alignment_reason=str(align["reason"]),
752
+ matched_topics=list(align["matched_topics"]),
753
+ unmatched_topics=list(align["unmatched_topics"]),
754
+ ))
755
+ return picks
756
+
757
+
758
+ def _sort_screened_candidates(df: pd.DataFrame, screening=None) -> pd.DataFrame:
759
+ """Sort scored candidates deterministically with factor-aware tie breakers."""
760
+ factor_order = ["stability", "activity", "momentum", "value"]
761
+ if screening is not None and screening.factor_weights:
762
+ factor_order = [
763
+ factor
764
+ for factor, _weight in sorted(
765
+ screening.factor_weights.items(),
766
+ key=lambda item: (-float(item[1]), item[0]),
767
+ )
768
+ ]
769
+ sort_columns = [
770
+ column
771
+ for column in ["screen_score"] + [f"factor_{factor}_score" for factor in factor_order]
772
+ if column in df.columns
773
+ ]
774
+ ascending = [False] * len(sort_columns)
775
+ if "code" in df.columns:
776
+ sort_columns.append("code")
777
+ ascending.append(True)
778
+ if not sort_columns:
779
+ return df
780
+ return df.sort_values(sort_columns, ascending=ascending, kind="mergesort")
781
+
782
+
783
+ def _screening_daily_cache_kwargs(config: Config, market: str) -> dict[str, object]:
784
+ """Daily-history cache settings for screening.
785
+
786
+ After the latest close has settled, a history fetched since then that
787
+ reaches that session cannot change before the next open, so it is
788
+ reused. During the session (and just before the open) nothing is read
789
+ as fresh or written: a partial-day bar must not reach evaluation, which
790
+ shares the cache. If every source fails, the last cached history is
791
+ still used, flagged ``stale_cache``. Called per fetch, so a batch that
792
+ runs across the open switches over.
793
+ """
794
+ if config.daily_history_cache_dir is None:
795
+ return {"cache_dir": None}
796
+ settled = latest_settled_close(market)
797
+ if settled is None:
798
+ return {"cache_dir": config.daily_history_cache_dir, "cache_ttl_seconds": 0.0, "cache_write": False}
799
+ session, elapsed = settled
800
+ return {
801
+ "cache_dir": config.daily_history_cache_dir,
802
+ "cache_ttl_seconds": min(elapsed, float(config.daily_history_cache_ttl_hours) * 3600.0),
803
+ "cache_min_last_date": session,
804
+ }
805
+
806
+
807
+ def _required_snapshot_columns(filters) -> list[str]:
808
+ columns: list[str] = []
809
+ if filters.exclude_st:
810
+ columns.append("name")
811
+ if filters.amount_min is not None:
812
+ columns.append("amount")
813
+ if filters.avg_amount_usd_min is not None:
814
+ columns.append("avg_amount_usd")
815
+ if filters.price_min is not None or filters.price_max is not None:
816
+ columns.append("price")
817
+ if filters.market_cap_min is not None or filters.market_cap_max is not None:
818
+ columns.append("total_mv")
819
+ if filters.pe_ttm_min is not None or filters.pe_ttm_max is not None:
820
+ columns.append("pe_ratio")
821
+ if filters.pb_min is not None or filters.pb_max is not None:
822
+ columns.append("pb_ratio")
823
+ if filters.volume_ratio_min is not None:
824
+ columns.append("volume_ratio")
825
+ if filters.turnover_rate_min is not None:
826
+ columns.append("turnover_rate")
827
+ if filters.change_pct_min is not None or filters.change_pct_max is not None:
828
+ columns.append("change_pct")
829
+ return list(dict.fromkeys(columns))
830
+
831
+
832
+ def _event_source_weights(event_profile: dict[str, object]) -> dict[str, float] | None:
833
+ value = (event_profile or {}).get("source_weights")
834
+ if not isinstance(value, dict):
835
+ return None
836
+ result: dict[str, float] = {}
837
+ for key, raw in value.items():
838
+ try:
839
+ result[str(key)] = float(raw)
840
+ except (TypeError, ValueError):
841
+ continue
842
+ return result or None
843
+
844
+
845
+ def _daily_source_health_notes(health: dict[str, object], *, limit: int = 4) -> list[str]:
846
+ source_states: list[tuple[tuple[int, float, float, str], str, dict[object, object]]] = []
847
+ for source, raw_state in health.items():
848
+ if not isinstance(raw_state, dict):
849
+ continue
850
+ failures = _safe_float(raw_state.get("failures")) or 0.0
851
+ total_failures = _safe_float(raw_state.get("total_failures")) or 0.0
852
+ disabled = bool(raw_state.get("disabled"))
853
+ if not disabled and failures <= 0 and total_failures <= 0:
854
+ continue
855
+ severity_key = (
856
+ 0 if disabled else 1 if failures > 0 else 2,
857
+ -failures,
858
+ -total_failures,
859
+ str(source),
860
+ )
861
+ source_states.append((severity_key, str(source), raw_state))
862
+
863
+ notes: list[str] = []
864
+ for _severity_key, source, raw_state in sorted(source_states):
865
+ failures = _safe_float(raw_state.get("failures")) or 0.0
866
+ total_failures = _safe_float(raw_state.get("total_failures")) or 0.0
867
+ disabled = bool(raw_state.get("disabled"))
868
+ last_rows = _safe_float(raw_state.get("last_rows")) or 0.0
869
+ parts: list[str] = []
870
+ if disabled:
871
+ parts.append("disabled")
872
+ if failures > 0:
873
+ parts.append(f"failures={failures:g}")
874
+ elif total_failures > 0:
875
+ parts.append(f"total_failures={total_failures:g}")
876
+ if last_rows > 0:
877
+ parts.append(f"last_rows={last_rows:g}")
878
+ if parts:
879
+ notes.append(f"{source} " + ",".join(parts))
880
+ if len(notes) >= limit:
881
+ break
882
+ hidden_count = len(source_states) - len(notes)
883
+ if hidden_count > 0:
884
+ notes.append(f"+{hidden_count} more")
885
+ return notes
886
+
887
+
888
+ def _format_filter_waterfall(steps: list[dict[str, object]], *, limit: int = 8) -> str:
889
+ parts: list[str] = []
890
+ for step in steps[:limit]:
891
+ text = (
892
+ f"{step.get('filter')} {step.get('before')}->{step.get('after')} "
893
+ f"removed={step.get('removed')}"
894
+ )
895
+ samples = step.get("samples")
896
+ if isinstance(samples, list) and samples:
897
+ sample_names = [
898
+ str(item.get("name") or item.get("code") or item.get("value") or "")
899
+ for item in samples
900
+ if isinstance(item, dict)
901
+ ]
902
+ sample_names = [item for item in sample_names if item]
903
+ if sample_names:
904
+ text += f" samples={','.join(sample_names[:3])}"
905
+ if step.get("suggestion"):
906
+ text += f" next={step.get('suggestion')}"
907
+ parts.append(text)
908
+ hidden = len(steps) - len(parts)
909
+ if hidden > 0:
910
+ parts.append(f"+{hidden} more")
911
+ return "; ".join(parts)
912
+
913
+
914
+ def _resolve_cn_daily_pack(
915
+ *,
916
+ market: str,
917
+ snapshot_df: pd.DataFrame,
918
+ config: Config,
919
+ daily_pack: DailyPack | None,
920
+ degradation: list[str],
921
+ ) -> DailyPack | None:
922
+ if not get_market(market).supports_daily_pack:
923
+ return None
924
+ if daily_pack is None and not config.daily_pack_enabled:
925
+ return None
926
+ if daily_pack is not None:
927
+ active_pack = daily_pack
928
+ else:
929
+ pack_path = config.daily_pack_dir or pack_dir(config)
930
+ if not (pack_path / "manifest.json").is_file():
931
+ return None
932
+ try:
933
+ active_pack = load_pack(pack_path)
934
+ except (PackError, OSError) as exc:
935
+ degradation.append(f"CN daily pack fallback: {exc}")
936
+ return None
937
+
938
+ quote_date = str(snapshot_df.attrs.get("quote_date") or "").strip()[:10]
939
+ target_date = quote_date or expected_trade_date()
940
+ if active_pack.trade_date < target_date:
941
+ try:
942
+ active_pack = stitch_snapshot(active_pack, snapshot_df, trade_date=target_date)
943
+ except SnapshotStitchError as exc:
944
+ degradation.append(
945
+ f"CN daily pack stale ({active_pack.trade_date} < {target_date}; {exc}); "
946
+ "falling back to per-code daily enrichment"
947
+ )
948
+ return None
949
+ if active_pack.trade_date < target_date:
950
+ degradation.append(
951
+ f"CN daily pack stale ({active_pack.trade_date} < {target_date}); "
952
+ "falling back to per-code daily enrichment"
953
+ )
954
+ return None
955
+ return active_pack
956
+
957
+
958
+ def _attach_pack_daily_features(
959
+ df: pd.DataFrame,
960
+ active_pack: DailyPack,
961
+ *,
962
+ as_of_date: str | None = None,
963
+ ) -> tuple[pd.DataFrame, int]:
964
+ enriched = df.copy()
965
+ code_col = "code" if "code" in enriched.columns else "代码"
966
+ norm_codes = [normalize_code(v, allow_ticker=False) for v in enriched[code_col]]
967
+ target_trade_date: str | None = None
968
+ if as_of_date and as_of_date < active_pack.trade_date:
969
+ eligible = [str(d) for d in active_pack.dates if str(d) <= as_of_date]
970
+ if eligible:
971
+ target_trade_date = eligible[-1]
972
+ features_df = compute_pack_daily_features(
973
+ active_pack, codes=norm_codes, trade_date=target_trade_date
974
+ )
975
+ by_code = features_df.set_index("code").to_dict(orient="index") if not features_df.empty else {}
976
+ matched = sum(1 for c in norm_codes if c in by_code)
977
+
978
+ columns: dict[str, list[object]] = {col: [] for col in _DAILY_FEATURE_DEFAULTS}
979
+ for code in norm_codes:
980
+ feat = by_code.get(code)
981
+ if feat is None:
982
+ for col, default in _DAILY_FEATURE_DEFAULTS.items():
983
+ if col == "daily_quality_score":
984
+ columns[col].append(0.0)
985
+ elif col == "daily_quality_flags":
986
+ columns[col].append("missing_in_pack")
987
+ else:
988
+ columns[col].append(default)
989
+ else:
990
+ for col, default in _DAILY_FEATURE_DEFAULTS.items():
991
+ columns[col].append(feat.get(col, default))
992
+
993
+ for col, values in columns.items():
994
+ enriched[col] = values
995
+ return enriched, matched
996
+
997
+
998
+ def _safe_text(v: object) -> str:
999
+ return safe_text(v, max_len=120)
1000
+
1001
+
1002
+ _INDUSTRY_BACKFILL_MIN_COVERAGE = 0.5
1003
+
1004
+
1005
+ def _industry_coverage(df: pd.DataFrame) -> float:
1006
+ """Share of snapshot rows that carry a non-empty industry label."""
1007
+ if df.empty or "industry" not in df.columns:
1008
+ return 0.0
1009
+ labels = df["industry"].fillna("").astype(str).str.strip()
1010
+ return float((labels != "").mean())