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/context.py ADDED
@@ -0,0 +1,672 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Context assembly for LLM ranking."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import pandas as pd
11
+
12
+ from alphasift.normalize import normalize_code
13
+
14
+
15
+ def _normalize_code(value: object) -> str:
16
+ # Candidate rows carry structured codes; non-CN tickers must survive.
17
+ return normalize_code(value, allow_ticker=True)
18
+
19
+
20
+ _CONTEXT_TRIM_MARKER = "[context_trimmed]"
21
+ _CANDIDATE_CONTEXT_COLUMNS = {
22
+ "news": "新闻",
23
+ "announcement": "公告",
24
+ "announcements": "公告",
25
+ "fund_flow": "资金流",
26
+ "fundflow": "资金流",
27
+ "quote": "行情估值",
28
+ "summary": "摘要",
29
+ "context": "上下文",
30
+ "context_summary": "压缩摘要",
31
+ "text": "文本",
32
+ "risk": "风险",
33
+ "catalyst": "催化",
34
+ "source_count": "来源数",
35
+ "source_confidence": "来源置信度",
36
+ "source_weight_score": "来源权重分",
37
+ "event_tags": "事件标签",
38
+ "announcement_categories": "公告类别",
39
+ "negative_event_flags": "负面风险",
40
+ }
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class _ContextSection:
45
+ text: str
46
+ kind: str
47
+ priority: int
48
+ min_chars: int
49
+ weight: int
50
+ line_aware: bool = False
51
+
52
+
53
+ def build_llm_context(
54
+ *,
55
+ base_context: str = "",
56
+ context_files: list[str | Path] | None = None,
57
+ candidate_context_files: list[str | Path] | None = None,
58
+ candidate_context_rows: list[dict[str, object]] | None = None,
59
+ snapshot_df: pd.DataFrame | None = None,
60
+ candidate_df: pd.DataFrame | None = None,
61
+ event_profile: dict[str, object] | None = None,
62
+ max_chars: int = 4000,
63
+ degradation: list[str] | None = None,
64
+ ) -> str:
65
+ """Build bounded context text for the LLM soft ranker."""
66
+ sections: list[_ContextSection] = []
67
+ if base_context.strip():
68
+ sections.append(_section(
69
+ "【人工上下文】\n" + base_context.strip(),
70
+ kind="market_context",
71
+ priority=5,
72
+ min_chars=80,
73
+ weight=1,
74
+ line_aware=True,
75
+ ))
76
+
77
+ file_context = _read_context_files(context_files or [])
78
+ if file_context:
79
+ sections.append(_section(
80
+ "【上下文文件】\n" + file_context,
81
+ kind="market_files",
82
+ priority=5,
83
+ min_chars=80,
84
+ weight=1,
85
+ line_aware=True,
86
+ ))
87
+
88
+ event_profile_context = summarize_event_profile(event_profile)
89
+ if event_profile_context:
90
+ sections.append(_section(
91
+ event_profile_context,
92
+ kind="event_profile",
93
+ priority=2,
94
+ min_chars=160,
95
+ weight=2,
96
+ line_aware=True,
97
+ ))
98
+
99
+ candidate_identity = summarize_candidate_identity(candidate_df)
100
+ if candidate_identity:
101
+ sections.append(_section(
102
+ candidate_identity,
103
+ kind="candidate_identity",
104
+ priority=0,
105
+ min_chars=360,
106
+ weight=4,
107
+ line_aware=True,
108
+ ))
109
+
110
+ candidate_external_context = _read_candidate_context_files(
111
+ candidate_context_files or [],
112
+ candidate_df,
113
+ )
114
+ if candidate_external_context:
115
+ sections.append(_section(
116
+ "【候选外部线索】\n" + candidate_external_context,
117
+ kind="candidate_external_context",
118
+ priority=1,
119
+ min_chars=320,
120
+ weight=4,
121
+ line_aware=True,
122
+ ))
123
+
124
+ collected_candidate_context = _format_candidate_context_rows(
125
+ candidate_context_rows or [],
126
+ candidate_df,
127
+ )
128
+ if collected_candidate_context:
129
+ sections.append(_section(
130
+ "【候选抓取线索】\n" + collected_candidate_context,
131
+ kind="candidate_collected_context",
132
+ priority=1,
133
+ min_chars=360,
134
+ weight=4,
135
+ line_aware=True,
136
+ ))
137
+
138
+ snapshot_context = summarize_snapshot_context(snapshot_df, title="全市场快照")
139
+ if snapshot_context:
140
+ sections.append(_section(
141
+ snapshot_context,
142
+ kind="market_snapshot",
143
+ priority=4,
144
+ min_chars=160,
145
+ weight=2,
146
+ line_aware=True,
147
+ ))
148
+
149
+ candidate_context = summarize_snapshot_context(candidate_df, title="候选池快照")
150
+ if candidate_context:
151
+ sections.append(_section(
152
+ candidate_context,
153
+ kind="candidate_snapshot",
154
+ priority=2,
155
+ min_chars=180,
156
+ weight=2,
157
+ line_aware=True,
158
+ ))
159
+
160
+ candidate_profile = summarize_candidate_profile(candidate_df)
161
+ if candidate_profile:
162
+ sections.append(_section(
163
+ candidate_profile,
164
+ kind="candidate_profile",
165
+ priority=2,
166
+ min_chars=240,
167
+ weight=3,
168
+ line_aware=True,
169
+ ))
170
+
171
+ return _join_bounded_context_sections(sections, max_chars=max_chars, degradation=degradation)
172
+
173
+
174
+ def summarize_snapshot_context(df: pd.DataFrame | None, *, title: str) -> str:
175
+ """Summarize breadth, activity and extremes from a snapshot DataFrame."""
176
+ if df is None or df.empty:
177
+ return ""
178
+
179
+ lines = [f"【{title}】", f"样本数: {len(df)}"]
180
+ if "change_pct" in df.columns:
181
+ change = pd.to_numeric(df["change_pct"], errors="coerce").dropna()
182
+ if not change.empty:
183
+ positive_ratio = (change > 0).mean() * 100
184
+ lines.append(
185
+ "涨跌分布: "
186
+ f"上涨占比 {positive_ratio:.1f}%, "
187
+ f"中位涨跌幅 {change.median():.2f}%, "
188
+ f"平均涨跌幅 {change.mean():.2f}%"
189
+ )
190
+ lines.append("涨跌极值: " + _format_extremes(df, change, ascending=False))
191
+ if "amount" in df.columns:
192
+ amount = pd.to_numeric(df["amount"], errors="coerce").dropna()
193
+ if not amount.empty:
194
+ lines.append(f"成交额中位数: {amount.median():.0f}")
195
+ if "volume_ratio" in df.columns:
196
+ volume_ratio = pd.to_numeric(df["volume_ratio"], errors="coerce").dropna()
197
+ if not volume_ratio.empty:
198
+ hot_ratio = (volume_ratio >= 2).mean() * 100
199
+ lines.append(f"量比>=2占比: {hot_ratio:.1f}%")
200
+ return "\n".join(lines)
201
+
202
+
203
+ def summarize_candidate_profile(df: pd.DataFrame | None) -> str:
204
+ """Summarize factor conflicts and leadership inside the candidate pool."""
205
+ if df is None or df.empty:
206
+ return ""
207
+
208
+ lines = ["【候选池结构】"]
209
+ factor_cols = {
210
+ "价值": "factor_value_score",
211
+ "流动性": "factor_liquidity_score",
212
+ "动量": "factor_momentum_score",
213
+ "反转": "factor_reversal_score",
214
+ "活跃度": "factor_activity_score",
215
+ "稳定性": "factor_stability_score",
216
+ "市值容量": "factor_size_score",
217
+ "主题热度": "factor_theme_heat_score",
218
+ }
219
+ available = {label: col for label, col in factor_cols.items() if col in df.columns}
220
+ if available:
221
+ averages = []
222
+ for label, col in available.items():
223
+ series = pd.to_numeric(df[col], errors="coerce").dropna()
224
+ if not series.empty:
225
+ averages.append(f"{label}{series.mean():.1f}")
226
+ if averages:
227
+ lines.append("因子均值: " + ",".join(averages))
228
+
229
+ leaders = []
230
+ columns = [col for col in ("code", "name") if col in df.columns]
231
+ for label, col in available.items():
232
+ series = pd.to_numeric(df[col], errors="coerce")
233
+ if series.dropna().empty or not columns:
234
+ continue
235
+ idx = series.idxmax()
236
+ row = df.loc[idx]
237
+ leaders.append(f"{label}:{row.get('code', '')}{row.get('name', '')}({series.loc[idx]:.1f})")
238
+ if leaders:
239
+ lines.append("因子领先: " + ",".join(leaders[:8]))
240
+
241
+ if "screen_score" in df.columns:
242
+ screen_score = pd.to_numeric(df["screen_score"], errors="coerce").dropna()
243
+ if not screen_score.empty:
244
+ lines.append(
245
+ f"主评分分布: 最高{screen_score.max():.1f},"
246
+ f"中位{screen_score.median():.1f},最低{screen_score.min():.1f}"
247
+ )
248
+
249
+ industry_summary = _summarize_label_distribution(df, "industry")
250
+ if industry_summary:
251
+ lines.append("行业分布: " + industry_summary)
252
+ concept_summary = _summarize_label_distribution(df, "concepts")
253
+ if concept_summary:
254
+ lines.append("概念线索: " + concept_summary)
255
+ heat_summary = _summarize_board_heat(df)
256
+ if heat_summary:
257
+ lines.append("板块/主题热度: " + heat_summary)
258
+
259
+ return "\n".join(lines) if len(lines) > 1 else ""
260
+
261
+
262
+ def summarize_candidate_identity(df: pd.DataFrame | None, *, limit: int = 30) -> str:
263
+ """Summarize top candidate identities and key ranking fields."""
264
+ if df is None or df.empty or "code" not in df.columns:
265
+ return ""
266
+
267
+ lines = ["【候选身份】"]
268
+ for _, row in df.head(max(int(limit), 1)).iterrows():
269
+ code = _normalize_code(row.get("code", row.get("代码", "")))
270
+ if not code:
271
+ continue
272
+ name = _safe_context_value(
273
+ row.get("name") or row.get("名称") or row.get("股票名称"),
274
+ max_len=40,
275
+ )
276
+ fields = []
277
+ score = _safe_context_value(row.get("screen_score"), max_len=24)
278
+ if score:
279
+ fields.append(f"screen_score={score}")
280
+ industry = _safe_context_value(row.get("industry") or row.get("行业"), max_len=40)
281
+ if industry:
282
+ fields.append(f"industry={industry}")
283
+ concepts = _safe_context_value(row.get("concepts") or row.get("概念"), max_len=80)
284
+ if concepts:
285
+ fields.append(f"concepts={concepts}")
286
+ heat = _safe_context_value(row.get("board_heat_score"), max_len=24)
287
+ if heat:
288
+ fields.append(f"board_heat_score={heat}")
289
+ suffix = ": " + ", ".join(fields) if fields else ""
290
+ lines.append(f"- {code} {name}{suffix}")
291
+ if len(df) > limit:
292
+ lines.append(f"...[candidate_identity_omitted:{len(df) - limit}]")
293
+ return "\n".join(lines) if len(lines) > 1 else ""
294
+
295
+
296
+ def summarize_event_profile(event_profile: dict[str, object] | None) -> str:
297
+ """Summarize strategy-level event preferences for the LLM."""
298
+ if not event_profile:
299
+ return ""
300
+ lines = ["【策略事件偏好】"]
301
+ field_labels = {
302
+ "preferred_event_tags": "偏好事件标签",
303
+ "avoided_event_tags": "规避事件标签",
304
+ "preferred_announcement_categories": "偏好公告类别",
305
+ "avoided_announcement_categories": "规避公告类别",
306
+ "notes": "事件备注",
307
+ }
308
+ for field, label in field_labels.items():
309
+ value = _format_profile_value(event_profile.get(field))
310
+ if value:
311
+ lines.append(f"{label}: {value}")
312
+ source_weights = event_profile.get("source_weights")
313
+ if isinstance(source_weights, dict) and source_weights:
314
+ items = []
315
+ for source, weight in source_weights.items():
316
+ text = _safe_context_value(source, max_len=40)
317
+ if not text:
318
+ continue
319
+ try:
320
+ items.append(f"{text}={float(weight):.2f}")
321
+ except (TypeError, ValueError):
322
+ continue
323
+ if items:
324
+ lines.append("来源权重: " + ",".join(items))
325
+ return "\n".join(lines) if len(lines) > 1 else ""
326
+
327
+
328
+ def _read_context_files(paths: list[str | Path]) -> str:
329
+ chunks: list[str] = []
330
+ for path_like in paths:
331
+ path = Path(path_like)
332
+ if not path.is_file():
333
+ raise FileNotFoundError(f"Context file not found: {path}")
334
+ text = path.read_text(encoding="utf-8").strip()
335
+ if text:
336
+ chunks.append(f"# {path.name}\n{text}")
337
+ return "\n\n".join(chunks)
338
+
339
+
340
+ def _read_candidate_context_files(
341
+ paths: list[str | Path],
342
+ candidate_df: pd.DataFrame | None,
343
+ ) -> str:
344
+ if not paths or candidate_df is None or candidate_df.empty or "code" not in candidate_df.columns:
345
+ return ""
346
+
347
+ candidate_names, candidate_order = _candidate_maps(candidate_df)
348
+ candidate_codes = set(candidate_names)
349
+ chunks: list[tuple[int, int, str]] = []
350
+ row_position = 0
351
+ for path_like in paths:
352
+ path = Path(path_like)
353
+ if not path.is_file():
354
+ raise FileNotFoundError(f"Candidate context file not found: {path}")
355
+ rows = _load_candidate_context_rows(path)
356
+ for row in rows:
357
+ code = _normalize_code(row.get("code", row.get("代码", "")))
358
+ item = _format_candidate_context_row(row, candidate_codes, candidate_names)
359
+ if item:
360
+ chunks.append((candidate_order.get(code, len(candidate_order)), row_position, item))
361
+ row_position += 1
362
+ return "\n".join(item for _, _, item in sorted(chunks))
363
+
364
+
365
+ def _format_candidate_context_rows(
366
+ rows: list[dict[str, object]],
367
+ candidate_df: pd.DataFrame | None,
368
+ ) -> str:
369
+ if not rows or candidate_df is None or candidate_df.empty or "code" not in candidate_df.columns:
370
+ return ""
371
+ candidate_names, candidate_order = _candidate_maps(candidate_df)
372
+ candidate_codes = set(candidate_names)
373
+ chunks = []
374
+ for idx, row in enumerate(rows):
375
+ code = _normalize_code(row.get("code", row.get("代码", "")))
376
+ item = _format_candidate_context_row(row, candidate_codes, candidate_names)
377
+ if item:
378
+ chunks.append((candidate_order.get(code, len(candidate_order)), idx, item))
379
+ return "\n".join(item for _, _, item in sorted(chunks))
380
+
381
+
382
+ def _candidate_maps(candidate_df: pd.DataFrame) -> tuple[dict[str, str], dict[str, int]]:
383
+ candidate_names: dict[str, str] = {}
384
+ candidate_order: dict[str, int] = {}
385
+ for idx, (_, row) in enumerate(candidate_df.iterrows()):
386
+ code = _normalize_code(row.get("code", row.get("代码", "")))
387
+ if not code:
388
+ continue
389
+ candidate_names[code] = str(row.get("name", row.get("名称", "")) or "")
390
+ candidate_order.setdefault(code, idx)
391
+ return candidate_names, candidate_order
392
+
393
+
394
+ def _format_candidate_context_row(
395
+ row: dict[str, object],
396
+ candidate_codes: set[str],
397
+ candidate_names: dict[str, str],
398
+ ) -> str:
399
+ code = _normalize_code(row.get("code", row.get("代码", "")))
400
+ if code not in candidate_codes:
401
+ return ""
402
+ fields = []
403
+ for column, label in _CANDIDATE_CONTEXT_COLUMNS.items():
404
+ value = _safe_context_value(row.get(column))
405
+ if value:
406
+ fields.append(f"{label}:{value}")
407
+ if not fields:
408
+ return ""
409
+ name = _safe_context_value(row.get("name") or row.get("名称")) or candidate_names.get(code, "")
410
+ return f"- {code} {name}: " + ";".join(fields)
411
+
412
+
413
+ def _load_candidate_context_rows(path: Path) -> list[dict[str, object]]:
414
+ suffix = path.suffix.lower()
415
+ if suffix == ".csv":
416
+ return pd.read_csv(path, dtype=str).fillna("").to_dict(orient="records")
417
+ if suffix == ".jsonl":
418
+ rows = []
419
+ for line in path.read_text(encoding="utf-8").splitlines():
420
+ line = line.strip()
421
+ if line:
422
+ item = json.loads(line)
423
+ if isinstance(item, dict):
424
+ rows.append(item)
425
+ return rows
426
+ if suffix == ".json":
427
+ data = json.loads(path.read_text(encoding="utf-8"))
428
+ if isinstance(data, list):
429
+ return [item for item in data if isinstance(item, dict)]
430
+ if isinstance(data, dict):
431
+ items = data.get("items") or data.get("data")
432
+ if isinstance(items, list):
433
+ return [item for item in items if isinstance(item, dict)]
434
+ rows = []
435
+ for code, value in data.items():
436
+ if isinstance(value, dict):
437
+ rows.append({"code": code, **value})
438
+ elif isinstance(value, str):
439
+ rows.append({"code": code, "text": value})
440
+ return rows
441
+ raise ValueError(f"Unsupported candidate context file format: {path}")
442
+
443
+
444
+ def _safe_context_value(value: object, *, max_len: int = 280) -> str:
445
+ if value is None:
446
+ return ""
447
+ if isinstance(value, list):
448
+ text = ",".join(str(item).strip() for item in value if str(item).strip())
449
+ else:
450
+ text = str(value).strip()
451
+ if not text or text.lower() in {"nan", "none", "<na>"}:
452
+ return ""
453
+ return text[:max_len]
454
+
455
+
456
+ def _format_profile_value(value: object) -> str:
457
+ if isinstance(value, list):
458
+ return ",".join(
459
+ item
460
+ for item in (_safe_context_value(raw, max_len=80) for raw in value)
461
+ if item
462
+ )
463
+ return _safe_context_value(value, max_len=280)
464
+
465
+
466
+ def _section(
467
+ text: str,
468
+ *,
469
+ kind: str,
470
+ priority: int,
471
+ min_chars: int,
472
+ weight: int,
473
+ line_aware: bool = False,
474
+ ) -> _ContextSection:
475
+ return _ContextSection(
476
+ text=text.strip(),
477
+ kind=kind,
478
+ priority=priority,
479
+ min_chars=max(int(min_chars), 0),
480
+ weight=max(int(weight), 1),
481
+ line_aware=line_aware,
482
+ )
483
+
484
+
485
+ def _join_bounded_context_sections(
486
+ sections: list[_ContextSection],
487
+ *,
488
+ max_chars: int,
489
+ degradation: list[str] | None,
490
+ ) -> str:
491
+ sections = [section for section in sections if section.text.strip()]
492
+ combined = "\n\n".join(section.text for section in sections).strip()
493
+ if not combined:
494
+ return ""
495
+ if len(combined) <= max_chars:
496
+ return combined
497
+
498
+ marker_line = f"【上下文降级】{_CONTEXT_TRIM_MARKER} low-priority context trimmed."
499
+ budget = max(int(max_chars) - len(marker_line) - 2, 0)
500
+ if budget <= 0:
501
+ return marker_line[:max_chars]
502
+
503
+ allocations = _allocate_section_budgets(sections, budget)
504
+ chunks: list[str] = []
505
+ trimmed_kinds: list[str] = []
506
+ for section, limit in zip(sections, allocations, strict=False):
507
+ trimmed = _trim_section(section, limit)
508
+ if trimmed:
509
+ chunks.append(trimmed)
510
+ if len(trimmed) < len(section.text):
511
+ trimmed_kinds.append(section.kind)
512
+
513
+ result = "\n\n".join(chunks).strip()
514
+ if trimmed_kinds:
515
+ trimmed_labels = ",".join(dict.fromkeys(trimmed_kinds))
516
+ marker_line = (
517
+ f"【上下文降级】{_CONTEXT_TRIM_MARKER} "
518
+ f"trimmed={trimmed_labels}"
519
+ )
520
+ result = _append_marker_within_limit(result, marker_line, max_chars=max_chars)
521
+ if degradation is not None:
522
+ degradation.append(f"LLM context truncated: trimmed={trimmed_labels}")
523
+ return result[:max_chars]
524
+
525
+
526
+ def _allocate_section_budgets(sections: list[_ContextSection], budget: int) -> list[int]:
527
+ separator_budget = max(len(sections) - 1, 0) * 2
528
+ body_budget = max(budget - separator_budget, 0)
529
+ minimums = [min(len(section.text), section.min_chars) for section in sections]
530
+ minimum_total = sum(minimums)
531
+ if minimum_total > body_budget:
532
+ return _priority_floor_allocations(sections, body_budget)
533
+
534
+ allocations = list(minimums)
535
+ remaining = body_budget - minimum_total
536
+ while remaining > 0:
537
+ expandable = [
538
+ idx
539
+ for idx, section in enumerate(sections)
540
+ if allocations[idx] < len(section.text)
541
+ ]
542
+ if not expandable:
543
+ break
544
+ total_weight = sum(sections[idx].weight for idx in expandable)
545
+ progressed = False
546
+ for idx in expandable:
547
+ section = sections[idx]
548
+ extra = len(section.text) - allocations[idx]
549
+ share = max(1, int(remaining * section.weight / max(total_weight, 1)))
550
+ take = min(extra, share, remaining)
551
+ if take <= 0:
552
+ continue
553
+ allocations[idx] += take
554
+ remaining -= take
555
+ progressed = True
556
+ if remaining <= 0:
557
+ break
558
+ if not progressed:
559
+ break
560
+ return allocations
561
+
562
+
563
+ def _priority_floor_allocations(sections: list[_ContextSection], budget: int) -> list[int]:
564
+ allocations = [0] * len(sections)
565
+ remaining = max(int(budget), 0)
566
+ for idx in sorted(range(len(sections)), key=lambda item: sections[item].priority):
567
+ if remaining <= 0:
568
+ break
569
+ section = sections[idx]
570
+ floor = min(len(section.text), max(section.min_chars, 80))
571
+ take = min(floor, remaining)
572
+ allocations[idx] = take
573
+ remaining -= take
574
+ return allocations
575
+
576
+
577
+ def _trim_section(section: _ContextSection, limit: int) -> str:
578
+ if limit <= 0:
579
+ return ""
580
+ text = section.text
581
+ if len(text) <= limit:
582
+ return text
583
+
584
+ marker = f"\n...{_CONTEXT_TRIM_MARKER}:{section.kind}"
585
+ if limit <= len(marker) + 8:
586
+ return text[:limit].rstrip()
587
+ content_limit = limit - len(marker)
588
+ if not section.line_aware:
589
+ return text[:content_limit].rstrip() + marker
590
+
591
+ kept: list[str] = []
592
+ for line in text.splitlines():
593
+ candidate = "\n".join([*kept, line]).rstrip() + marker
594
+ if len(candidate) > limit:
595
+ prefix = "\n".join(kept).rstrip()
596
+ separator = "\n" if prefix else ""
597
+ remaining = limit - len(prefix) - len(separator) - len(marker)
598
+ if remaining > 8:
599
+ kept.append(line[:remaining].rstrip())
600
+ break
601
+ kept.append(line)
602
+ if not kept:
603
+ return text[:content_limit].rstrip() + marker
604
+ return "\n".join(kept).rstrip() + marker
605
+
606
+
607
+ def _append_marker_within_limit(text: str, marker: str, *, max_chars: int) -> str:
608
+ if not text:
609
+ return marker[:max_chars]
610
+ candidate = f"{text}\n{marker}"
611
+ if len(candidate) <= max_chars:
612
+ return candidate
613
+ keep = max(max_chars - len(marker) - 1, 0)
614
+ if keep <= 0:
615
+ return marker[:max_chars]
616
+ return text[:keep].rstrip() + "\n" + marker
617
+
618
+
619
+ def _format_extremes(df: pd.DataFrame, change: pd.Series, *, ascending: bool) -> str:
620
+ columns = [col for col in ("code", "name", "change_pct") if col in df.columns]
621
+ if not columns:
622
+ return ""
623
+ top = df.loc[change.sort_values(ascending=ascending).head(3).index, columns]
624
+ items = []
625
+ for _, row in top.iterrows():
626
+ code = str(row.get("code", ""))
627
+ name = str(row.get("name", ""))
628
+ pct = row.get("change_pct", 0)
629
+ items.append(f"{code}{name}({float(pct):.2f}%)")
630
+ return ", ".join(items)
631
+
632
+
633
+ def _summarize_label_distribution(df: pd.DataFrame, column: str) -> str:
634
+ if column not in df.columns:
635
+ return ""
636
+ labels: list[str] = []
637
+ for raw in df[column].dropna().astype(str):
638
+ for item in raw.replace(",", ",").replace("、", ",").split(","):
639
+ label = item.strip()
640
+ if label and label.lower() not in {"nan", "none", "<na>"}:
641
+ labels.append(label)
642
+ if not labels:
643
+ return ""
644
+ counts = pd.Series(labels).value_counts().head(6)
645
+ return ",".join(f"{label}{count}" for label, count in counts.items())
646
+
647
+
648
+ def _summarize_board_heat(df: pd.DataFrame, *, limit: int = 5) -> str:
649
+ if "board_heat_score" not in df.columns:
650
+ return ""
651
+ values = pd.to_numeric(df["board_heat_score"], errors="coerce")
652
+ if values.dropna().empty:
653
+ return ""
654
+ items = []
655
+ for idx in values.sort_values(ascending=False).dropna().head(limit).index:
656
+ row = df.loc[idx]
657
+ code = str(row.get("code", "") or "")
658
+ name = str(row.get("name", "") or "")
659
+ label = str(row.get("board_heat_summary", "") or row.get("industry", "") or "")
660
+ trend = _safe_context_value(row.get("board_heat_trend_score"), max_len=20)
661
+ persistence = _safe_context_value(row.get("board_heat_persistence_score"), max_len=20)
662
+ cooling = _safe_context_value(row.get("board_heat_cooling_score"), max_len=20)
663
+ state = _safe_context_value(row.get("board_heat_state"), max_len=20)
664
+ trend_text = f",trend={trend}" if trend else ""
665
+ persistence_text = f",persist={persistence}" if persistence else ""
666
+ cooling_text = f",cooling={cooling}" if cooling else ""
667
+ state_text = f",state={state}" if state else ""
668
+ items.append(
669
+ f"{code}{name}:{float(values.loc[idx]):.1f}"
670
+ f"{trend_text}{persistence_text}{cooling_text}{state_text}({label[:60]})"
671
+ )
672
+ return ",".join(items)