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/ranker.py ADDED
@@ -0,0 +1,990 @@
1
+ # -*- coding: utf-8 -*-
2
+ """L2 LLM ranker — relative ranking of shortlisted candidates."""
3
+
4
+ import json
5
+ import logging
6
+ import re
7
+ from collections.abc import Callable
8
+ from copy import deepcopy
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ from alphasift.llm_client import (
13
+ DEFAULT_LLM_MAX_TOKENS,
14
+ LLMClientError,
15
+ build_attempts,
16
+ complete,
17
+ configuration_error,
18
+ )
19
+ from alphasift.models import Pick
20
+ from alphasift.normalize import (
21
+ bounded_float as _bounded_float,
22
+ normalize_code,
23
+ safe_string_list as _safe_string_list,
24
+ safe_text,
25
+ )
26
+
27
+
28
+ def _normalize_code(value: object) -> str:
29
+ # Candidate codes and LLM ranking JSON code fields are structured, so
30
+ # US tickers may pass through (see normalize_code docstring).
31
+ return normalize_code(value, allow_ticker=True)
32
+
33
+
34
+ logger = logging.getLogger(__name__)
35
+ _DEFAULT_RANKING_PROMPT_MAX_CHARS = 24_000
36
+ _PROMPT_TRIM_MARKER = "[prompt_trimmed]"
37
+ _ADVERSE_FILING_MARKERS = (
38
+ "unresolved adverse filing",
39
+ "adverse filing",
40
+ "red_flag_capped",
41
+ "立案调查",
42
+ "监管调查",
43
+ "证监会调查",
44
+ "被调查",
45
+ "立案",
46
+ "股东减持",
47
+ "拟减持",
48
+ "大股东减持",
49
+ "业绩预亏",
50
+ "亏损",
51
+ "*st",
52
+ "冻结",
53
+ "留置",
54
+ "退市",
55
+ "终止上市",
56
+ "st风险",
57
+ "警示函",
58
+ "监管函",
59
+ "问询函",
60
+ "行政处罚",
61
+ "处罚",
62
+ "造假",
63
+ "违约",
64
+ "大幅下滑",
65
+ "under investigation",
66
+ "pending investigation",
67
+ "regulatory investigation",
68
+ "delisting",
69
+ "regulatory penalty",
70
+ "regulatory_penalty",
71
+ )
72
+ _NEGATED_RISK_RE = re.compile(
73
+ r"(?:无|未发生|不存在|不涉及|未受|未遭到|已解除|已撤销|撤销)"
74
+ r"(?:任何|重大|相关|新的)?"
75
+ r"(?:立案调查|监管调查|证监会调查|调查|行政处罚|处罚|退市风险警示|警示|违约|冻结|留置|减持)"
76
+ r"|\b(?:no|not|without|resolved|cleared|lifted)\s+"
77
+ r"(?:pending\s+|under\s+|any\s+)?"
78
+ r"(?:investigation|adverse filing|delisting|penalty)\b",
79
+ re.I,
80
+ )
81
+ _SEVERE_CONTEXT_FLAGS = frozenset({"监管", "退市风险", "财务风险", "业绩压力", "减持", "诉讼风险", "质押冻结"})
82
+ _LLM_RED_FLAG_MAX_SCORE = 35.0
83
+
84
+
85
+ def _strip_negated_risk_phrases(text: str) -> str:
86
+ return _NEGATED_RISK_RE.sub(" ", text)
87
+
88
+
89
+ @dataclass
90
+ class RankingParseResult:
91
+ picks: list[Pick]
92
+ coverage: float
93
+ errors: list[str]
94
+ market_view: str = ""
95
+ selection_logic: str = ""
96
+ portfolio_risk: str = ""
97
+ matched_codes: set[str] | None = None
98
+ matched_count: int = 0
99
+
100
+
101
+ @dataclass
102
+ class LLMRankingResult:
103
+ picks: list[Pick]
104
+ ranked: bool = False
105
+ market_view: str = ""
106
+ selection_logic: str = ""
107
+ portfolio_risk: str = ""
108
+ coverage: float = 0.0
109
+ errors: list[str] | None = None
110
+
111
+ def __post_init__(self) -> None:
112
+ if self.errors is None:
113
+ self.errors = []
114
+
115
+
116
+ def rank_candidates(
117
+ candidates: list[Pick],
118
+ ranking_hints: str,
119
+ llm_api_key: str,
120
+ llm_model: str,
121
+ llm_base_url: str = "",
122
+ *,
123
+ context: str = "",
124
+ rank_weight: float = 0.40,
125
+ max_retries: int = 1,
126
+ min_coverage: float = 0.60,
127
+ fallback_models: list[str] | None = None,
128
+ temperature: float = 0.2,
129
+ json_mode: bool = True,
130
+ silent: bool = True,
131
+ channels: list[dict[str, object]] | None = None,
132
+ config_path: str = "",
133
+ timeout_sec: float = 60.0,
134
+ max_prompt_chars: int | None = _DEFAULT_RANKING_PROMPT_MAX_CHARS,
135
+ max_tokens: int | None = DEFAULT_LLM_MAX_TOKENS,
136
+ ) -> list[Pick]:
137
+ """Use LLM to re-rank candidates and add ranking_reason / risk_summary.
138
+
139
+ Falls back to screen_score order if LLM call fails.
140
+ """
141
+ return rank_candidates_with_metadata(
142
+ candidates,
143
+ ranking_hints,
144
+ llm_api_key,
145
+ llm_model,
146
+ llm_base_url,
147
+ context=context,
148
+ rank_weight=rank_weight,
149
+ max_retries=max_retries,
150
+ min_coverage=min_coverage,
151
+ fallback_models=fallback_models,
152
+ temperature=temperature,
153
+ json_mode=json_mode,
154
+ silent=silent,
155
+ channels=channels,
156
+ config_path=config_path,
157
+ timeout_sec=timeout_sec,
158
+ max_prompt_chars=max_prompt_chars,
159
+ max_tokens=max_tokens,
160
+ ).picks
161
+
162
+
163
+ def rank_candidates_with_metadata(
164
+ candidates: list[Pick],
165
+ ranking_hints: str,
166
+ llm_api_key: str,
167
+ llm_model: str,
168
+ llm_base_url: str = "",
169
+ *,
170
+ context: str = "",
171
+ rank_weight: float = 0.40,
172
+ max_retries: int = 1,
173
+ min_coverage: float = 0.60,
174
+ fallback_models: list[str] | None = None,
175
+ temperature: float = 0.2,
176
+ json_mode: bool = True,
177
+ silent: bool = True,
178
+ channels: list[dict[str, object]] | None = None,
179
+ config_path: str = "",
180
+ timeout_sec: float = 60.0,
181
+ max_prompt_chars: int | None = _DEFAULT_RANKING_PROMPT_MAX_CHARS,
182
+ degradation: list[str] | None = None,
183
+ max_tokens: int | None = DEFAULT_LLM_MAX_TOKENS,
184
+ candidate_context_rows: list[dict[str, object]] | None = None,
185
+ ) -> LLMRankingResult:
186
+ """Use LLM to re-rank candidates and return global research metadata."""
187
+ if not candidates:
188
+ return LLMRankingResult(picks=candidates)
189
+
190
+ adverse_context_by_code: dict[str, list[str]] = {}
191
+ for row in candidate_context_rows or []:
192
+ norm_code = _normalize_code(row.get("code", ""))
193
+ if not norm_code:
194
+ continue
195
+ raw_flags = row.get("negative_event_flags")
196
+ if isinstance(raw_flags, (list, tuple, set)):
197
+ flags = [str(x).strip() for x in raw_flags if str(x).strip()]
198
+ elif isinstance(raw_flags, str) and raw_flags.strip():
199
+ flags = [x.strip() for x in raw_flags.replace(",", ",").split(",") if x.strip()]
200
+ else:
201
+ flags = []
202
+ severe = [f for f in flags if f in _SEVERE_CONTEXT_FLAGS]
203
+ if severe:
204
+ adverse_context_by_code[norm_code] = severe
205
+
206
+ prompt = _build_ranking_prompt(
207
+ candidates,
208
+ ranking_hints,
209
+ context,
210
+ max_chars=max_prompt_chars,
211
+ degradation=degradation,
212
+ )
213
+
214
+ try:
215
+ last_errors: list[str] = []
216
+ parsed: RankingParseResult | None = None
217
+ for attempt in range(max_retries + 1):
218
+ attempt_prompt = prompt
219
+ if attempt:
220
+ attempt_prompt += (
221
+ "\n\n上一次输出没有满足结构化覆盖率要求。"
222
+ "请重新返回严格 JSON,并覆盖尽可能多的候选代码。"
223
+ )
224
+ response = _call_llm(
225
+ attempt_prompt,
226
+ llm_api_key,
227
+ llm_model,
228
+ llm_base_url,
229
+ fallback_models=fallback_models or [],
230
+ temperature=temperature,
231
+ json_mode=json_mode,
232
+ silent=silent,
233
+ channels=channels or [],
234
+ config_path=config_path,
235
+ timeout_sec=timeout_sec,
236
+ max_tokens=max_tokens,
237
+ degradation=degradation,
238
+ )
239
+ parsed = _parse_ranking_response_detail(
240
+ response,
241
+ [deepcopy(pick) for pick in candidates],
242
+ )
243
+ last_errors = parsed.errors
244
+ if parsed.coverage >= min_coverage and parsed.matched_count > 0:
245
+ break
246
+ if parsed is None or parsed.coverage < min_coverage or parsed.matched_count == 0:
247
+ raise ValueError(
248
+ "LLM ranking response coverage below threshold: "
249
+ f"{0 if parsed is None else parsed.coverage:.2f}; "
250
+ f"errors={last_errors}"
251
+ )
252
+ ranked = parsed.picks
253
+ matched_codes = parsed.matched_codes
254
+ weight = min(max(rank_weight, 0.0), 1.0)
255
+ pre_risk_by_code = {
256
+ _normalize_code(p.code): str(p.risk_summary)
257
+ for p in candidates
258
+ if _normalize_code(p.code) and p.risk_summary
259
+ }
260
+ for i, pick in enumerate(ranked):
261
+ norm_code = _normalize_code(pick.code)
262
+ was_matched = matched_codes is None or norm_code in matched_codes
263
+ prior_risk = pre_risk_by_code.get(norm_code, "")
264
+ if prior_risk and not pick.risk_summary:
265
+ pick.risk_summary = prior_risk
266
+ adverse_reasons = _unresolved_adverse_reasons(
267
+ pick,
268
+ context_flags=adverse_context_by_code.get(norm_code, ()),
269
+ extra_texts=(prior_risk,),
270
+ )
271
+ if not was_matched:
272
+ pick.llm_score = None
273
+ if "llm_omitted" not in pick.risk_flags:
274
+ pick.risk_flags = [*pick.risk_flags, "llm_omitted"]
275
+ if adverse_reasons:
276
+ cap_final = float(pick.screen_score) * (1.0 - weight) + _LLM_RED_FLAG_MAX_SCORE * weight
277
+ pick.final_score = min(float(pick.screen_score), cap_final)
278
+ if "red_flag_capped" not in pick.risk_flags:
279
+ pick.risk_flags = [*pick.risk_flags, "red_flag_capped"]
280
+ note = f"触发红线上限({_LLM_RED_FLAG_MAX_SCORE:.0f}): {', '.join(adverse_reasons[:3])}"
281
+ pick.risk_summary = f"{pick.risk_summary}; {note}" if pick.risk_summary else note
282
+ else:
283
+ pick.final_score = float(pick.screen_score)
284
+ continue
285
+ if pick.llm_score is None:
286
+ pick.llm_score = 100.0 - i * (100.0 / max(len(ranked), 1))
287
+ if adverse_reasons and pick.llm_score > _LLM_RED_FLAG_MAX_SCORE:
288
+ pick.llm_score = _LLM_RED_FLAG_MAX_SCORE
289
+ if "red_flag_capped" not in pick.llm_risks:
290
+ pick.llm_risks = [*pick.llm_risks, "red_flag_capped"]
291
+ if "red_flag_capped" not in pick.risk_flags:
292
+ pick.risk_flags = [*pick.risk_flags, "red_flag_capped"]
293
+ note = f"触发红线上限({_LLM_RED_FLAG_MAX_SCORE:.0f}): {', '.join(adverse_reasons[:3])}"
294
+ pick.risk_summary = f"{pick.risk_summary}; {note}" if pick.risk_summary else note
295
+ pick.final_score = pick.screen_score * (1 - weight) + (pick.llm_score or 0.0) * weight
296
+ ranked.sort(key=lambda item: item.final_score, reverse=True)
297
+ for i, pick in enumerate(ranked, start=1):
298
+ pick.rank = i
299
+ return LLMRankingResult(
300
+ picks=ranked,
301
+ ranked=True,
302
+ market_view=parsed.market_view,
303
+ selection_logic=parsed.selection_logic,
304
+ portfolio_risk=parsed.portfolio_risk,
305
+ coverage=parsed.coverage,
306
+ errors=parsed.errors,
307
+ )
308
+ except Exception as e:
309
+ logger.warning("LLM ranking failed, falling back to screen_score: %s", e)
310
+ return LLMRankingResult(picks=candidates, errors=[str(e)])
311
+
312
+
313
+ def _note_truncation(degradation: list[str] | None, exc: LLMClientError) -> None:
314
+ """Record a truncated ranking completion so the run report cannot hide it."""
315
+ note = f"LLM ranking: {exc}; raise LLM_MAX_TOKENS"
316
+ if exc.partial_content:
317
+ note += f"; partial answer discarded ({len(exc.partial_content)} chars)"
318
+ logger.warning(note)
319
+ if degradation is not None:
320
+ degradation.append(note)
321
+
322
+
323
+ def _unresolved_adverse_reasons(
324
+ pick: Pick,
325
+ *,
326
+ context_flags: tuple[str, ...] | list[str] = (),
327
+ extra_texts: tuple[str, ...] | list[str] = (),
328
+ ) -> list[str]:
329
+ reasons: list[str] = []
330
+ for flag in context_flags:
331
+ if flag and flag not in reasons:
332
+ reasons.append(str(flag))
333
+ news_items = list(pick.dsa_news or [])
334
+ if not news_items and isinstance(pick.dsa_context, dict):
335
+ news_payload = pick.dsa_context.get("news")
336
+ if isinstance(news_payload, dict) and isinstance(news_payload.get("results"), list):
337
+ news_items = [item for item in news_payload["results"] if isinstance(item, dict)]
338
+ news_titles = [
339
+ str(item.get("title") or "").strip()
340
+ for item in news_items
341
+ if isinstance(item, dict) and item.get("title")
342
+ ]
343
+ text_sources = [
344
+ *pick.llm_risks,
345
+ *pick.risk_flags,
346
+ *pick.deep_analysis_risk_flags,
347
+ pick.risk_summary,
348
+ pick.dsa_analysis_summary,
349
+ *extra_texts,
350
+ *news_titles,
351
+ ]
352
+ cleaned_sources = [_strip_negated_risk_phrases(str(x)) for x in text_sources if x]
353
+ combined = " | ".join(cleaned_sources).lower()
354
+ for marker in _ADVERSE_FILING_MARKERS:
355
+ if marker in combined and marker not in reasons:
356
+ reasons.append(marker)
357
+ return reasons
358
+
359
+
360
+ def _build_ranking_prompt(
361
+ candidates: list[Pick],
362
+ hints: str,
363
+ context: str = "",
364
+ *,
365
+ max_chars: int | None = _DEFAULT_RANKING_PROMPT_MAX_CHARS,
366
+ degradation: list[str] | None = None,
367
+ ) -> str:
368
+ hints_text = hints.strip() or "无额外排序提示。"
369
+ context_text = context.strip() or "无额外上下文。只能基于候选池结构化数据和策略偏好判断。"
370
+ candidates_text = "\n".join(_format_candidate_for_prompt(p) for p in candidates)
371
+ prompt = _render_ranking_prompt(hints_text, context_text, candidates_text)
372
+ if max_chars is None or len(prompt) <= max_chars:
373
+ return prompt
374
+ return _build_bounded_ranking_prompt(
375
+ candidates,
376
+ hints_text,
377
+ context_text,
378
+ max_chars=max_chars,
379
+ degradation=degradation,
380
+ )
381
+
382
+
383
+ def _render_ranking_prompt(hints: str, context: str, candidates_text: str) -> str:
384
+ return f"""你是一个兼具深度基本面与风险排雷视角的股票研究员,任务是在“已经由代码硬筛过”的候选池内做相对排序。
385
+ 你不能推荐候选池外股票,不能修改硬筛条件,不能给目标价或承诺收益。请重点发挥代码公式无法替代的语义判断与排雷能力:
386
+ 1. **情报优先排雷(红旗一票降权)**:认真核查市场/情报上下文与 DSA 信息中的公告类别、新闻标题和负面关键词;若发现未消化重大利空(股东减持、立案调查、监管/问询函、业绩预亏或大幅下滑、商誉/债务/违约风险、退市警戒或纯粹高位蹭热点透支),必须将其 `llm_score` 严格压低到 `<= 35`,并在 `risk_flags` 与 `risk` 中写明依据;
387
+ 2. **禁止品牌/名气偏见**:严禁仅凭耳熟能详的大盘白马或银行股名气给高分;优先奖励业绩预增/扭亏、大额回购增持、重大合同中标且公告干净、资金与产业逻辑共振的标的;
388
+ 3. **跨候选可审计对比**:结合策略偏好、行业/概念持续性热度(不追单日过热炒作)对比相对强弱,所有结论必须锚定输入字段或上下文事实,不得编造未提供的数据。
389
+
390
+ ## 排序依据
391
+ {hints}
392
+
393
+ ## 市场/情报上下文
394
+ {context}
395
+
396
+ ## 候选列表
397
+ {candidates_text}
398
+
399
+ ## 输出要求
400
+ 只返回 JSON,不要 Markdown,不要解释 JSON 以外的文本。
401
+ 格式:
402
+ {{
403
+ "market_view": "一句话概括当前候选池和市场背景是否适合该策略",
404
+ "selection_logic": "说明本次排序最主要的2-3个判断维度",
405
+ "portfolio_risk": "说明最终名单可能存在的集中风险或共同风险",
406
+ "ranked": [
407
+ {{
408
+ "code": "股票代码",
409
+ "llm_score": 0-100,
410
+ "confidence": 0-1,
411
+ "sector": "行业/主题短标签,优先参考候选的 industry/concepts,并尽量统一,如 券商、银行、医药、AI算力",
412
+ "theme": "主要交易逻辑或主题",
413
+ "thesis": "该候选入选的核心投资假设",
414
+ "reason": "一句话排序理由(需锚定具体情报/催化或因子对比)",
415
+ "risk": "一句话主要排雷风险(红旗项须直指具体隐患)",
416
+ "catalysts": ["潜在催化1", "潜在催化2"],
417
+ "risk_flags": ["风险标签1"],
418
+ "tags": ["价值", "趋势", "防守", "事件", "流动性"],
419
+ "style_fit": "与策略风格的匹配度说明",
420
+ "watch_items": ["后续应跟踪的数据或事件"],
421
+ "invalidators": ["会推翻该候选逻辑的观察点"]
422
+ }}
423
+ ]
424
+ }}
425
+ """
426
+
427
+
428
+ def _build_bounded_ranking_prompt(
429
+ candidates: list[Pick],
430
+ hints: str,
431
+ context: str,
432
+ *,
433
+ max_chars: int,
434
+ degradation: list[str] | None,
435
+ ) -> str:
436
+ trimmed: list[str] = []
437
+ identity_text = "\n".join(_format_candidate_for_prompt(p, detail="identity") for p in candidates)
438
+ base_min = _render_ranking_prompt(
439
+ _truncate_prompt_text(hints, 900, "hints", trimmed),
440
+ "",
441
+ identity_text,
442
+ )
443
+ context_budget = max(int(max_chars) - len(base_min) - 80, 0)
444
+ context_text = _truncate_prompt_text(context, context_budget, "context", trimmed)
445
+
446
+ prompt_without_candidates = _render_ranking_prompt(
447
+ _truncate_prompt_text(hints, 900, "hints", trimmed),
448
+ context_text,
449
+ "",
450
+ )
451
+ candidate_budget = max(int(max_chars) - len(prompt_without_candidates), 0)
452
+ candidates_text = _fit_candidate_prompt_lines(candidates, candidate_budget, trimmed)
453
+ prompt = _render_ranking_prompt(
454
+ _truncate_prompt_text(hints, 900, "hints", trimmed),
455
+ context_text,
456
+ candidates_text,
457
+ )
458
+
459
+ if len(prompt) > max_chars:
460
+ overflow = len(prompt) - int(max_chars)
461
+ context_text = _truncate_prompt_text(
462
+ context_text,
463
+ max(len(context_text) - overflow - 80, 0),
464
+ "context",
465
+ trimmed,
466
+ )
467
+ prompt_without_candidates = _render_ranking_prompt(
468
+ _truncate_prompt_text(hints, 600, "hints", trimmed),
469
+ context_text,
470
+ "",
471
+ )
472
+ candidate_budget = max(int(max_chars) - len(prompt_without_candidates), 0)
473
+ candidates_text = _fit_candidate_prompt_lines(candidates, candidate_budget, trimmed)
474
+ prompt = _render_ranking_prompt(
475
+ _truncate_prompt_text(hints, 600, "hints", trimmed),
476
+ context_text,
477
+ candidates_text,
478
+ )
479
+
480
+ if len(prompt) > max_chars:
481
+ marker = f"\n...{_PROMPT_TRIM_MARKER}:hard_cap"
482
+ prompt = prompt[: max(int(max_chars) - len(marker), 0)].rstrip() + marker
483
+ trimmed.append("hard_cap")
484
+
485
+ if trimmed and degradation is not None:
486
+ labels = ",".join(dict.fromkeys(trimmed))
487
+ degradation.append(f"LLM ranking prompt truncated: trimmed={labels}")
488
+ return prompt[:max_chars]
489
+
490
+
491
+ def _format_candidate_for_prompt(p: Pick, *, detail: str = "full") -> str:
492
+ if detail == "identity":
493
+ return (
494
+ f"- {p.code} {p.name}: rank={p.rank}, "
495
+ f"screen_score={p.screen_score:.1f}, final_score={p.final_score:.1f}"
496
+ )
497
+ if detail == "compact":
498
+ return (
499
+ f"- {p.code} {p.name}: rank={p.rank}, price={p.price}, "
500
+ f"change_pct={p.change_pct}%, amount={p.amount:.0f}, "
501
+ f"screen_score={p.screen_score:.1f}, industry={p.industry or 'unknown'}, "
502
+ f"concepts={p.concepts or 'unknown'}, board_heat_score={p.board_heat_score}, "
503
+ f"signal_score={p.signal_score}, dsa_context={_format_dsa_context_for_prompt(p)}"
504
+ )
505
+ return (
506
+ f"- {p.code} {p.name}: price={p.price}, change_pct={p.change_pct}%, "
507
+ f"amount={p.amount:.0f}, turnover={p.turnover_rate}, volume_ratio={p.volume_ratio}, "
508
+ f"total_mv={p.total_mv}, PE={p.pe_ratio}, PB={p.pb_ratio}, "
509
+ f"industry={p.industry or 'unknown'}, concepts={p.concepts or 'unknown'}, "
510
+ f"industry_rank={p.industry_rank}, industry_change_pct={p.industry_change_pct}, "
511
+ f"board_heat_score={p.board_heat_score}, board_heat_summary={p.board_heat_summary or 'unknown'}, "
512
+ f"board_heat_latest_score={p.board_heat_latest_score}, "
513
+ f"board_heat_trend_score={p.board_heat_trend_score}, "
514
+ f"board_heat_persistence_score={p.board_heat_persistence_score}, "
515
+ f"board_heat_cooling_score={p.board_heat_cooling_score}, "
516
+ f"board_heat_observations={p.board_heat_observations}, "
517
+ f"board_heat_state={p.board_heat_state or 'unknown'}, "
518
+ f"change_60d={p.change_60d}, signal_score={p.signal_score}, "
519
+ f"macd={p.macd_status}, rsi={p.rsi_status}, "
520
+ f"breakout_20d_pct={p.breakout_20d_pct}, range_20d_pct={p.range_20d_pct}, "
521
+ f"volume_ratio_20d={p.volume_ratio_20d}, body_pct={p.body_pct}, "
522
+ f"pullback_to_ma20_pct={p.pullback_to_ma20_pct}, "
523
+ f"consolidation_days_20d={p.consolidation_days_20d}, "
524
+ f"screen_score={p.screen_score:.1f}, factor_scores={p.factor_scores}, "
525
+ f"dsa_context={_format_dsa_context_for_prompt(p)}"
526
+ )
527
+
528
+
529
+ def _fit_candidate_prompt_lines(
530
+ candidates: list[Pick],
531
+ budget: int,
532
+ trimmed: list[str],
533
+ ) -> str:
534
+ marker = f"...{_PROMPT_TRIM_MARKER}:candidate_details"
535
+ full_text = "\n".join(_format_candidate_for_prompt(p) for p in candidates)
536
+ if len(full_text) <= budget:
537
+ return full_text
538
+
539
+ available = max(int(budget) - len(marker) - 1, 0)
540
+ if available <= 0:
541
+ trimmed.append("candidate_details")
542
+ return marker[:budget]
543
+
544
+ identity_lines = [_format_candidate_for_prompt(p, detail="identity") for p in candidates]
545
+ lines: list[str] = []
546
+ used = 0
547
+ omitted = 0
548
+ for line in identity_lines:
549
+ extra = len(line) + (1 if lines else 0)
550
+ if used + extra > available:
551
+ omitted += 1
552
+ continue
553
+ lines.append(line)
554
+ used += extra
555
+
556
+ if omitted == 0:
557
+ for idx, pick in enumerate(candidates):
558
+ for detail in ("full", "compact"):
559
+ replacement = _format_candidate_for_prompt(pick, detail=detail)
560
+ delta = len(replacement) - len(lines[idx])
561
+ if used + delta <= available:
562
+ lines[idx] = replacement
563
+ used += delta
564
+ break
565
+
566
+ if omitted:
567
+ trimmed.append("candidate_omitted")
568
+ lines.append(f"...{_PROMPT_TRIM_MARKER}:candidate_omitted={omitted}")
569
+ else:
570
+ trimmed.append("candidate_details")
571
+ lines.append(marker)
572
+ return "\n".join(lines)
573
+
574
+
575
+ def _truncate_prompt_text(text: str, limit: int, label: str, trimmed: list[str]) -> str:
576
+ text = text.strip()
577
+ if len(text) <= limit:
578
+ return text
579
+ marker = f"\n...{_PROMPT_TRIM_MARKER}:{label}"
580
+ trimmed.append(label)
581
+ if limit <= len(marker) + 8:
582
+ return marker[:limit]
583
+ return text[: max(limit - len(marker), 0)].rstrip() + marker
584
+
585
+
586
+ def _format_dsa_context_for_prompt(p: Pick) -> str:
587
+ parts: list[str] = []
588
+ if p.dsa_analysis_summary:
589
+ parts.append(f"summary={_truncate_text(p.dsa_analysis_summary, 240)}")
590
+
591
+ context = p.dsa_context if isinstance(p.dsa_context, dict) else {}
592
+ quote = context.get("quote") if isinstance(context.get("quote"), dict) else {}
593
+ if quote:
594
+ parts.append(
595
+ "quote="
596
+ f"price:{quote.get('price')},change_pct:{quote.get('change_pct')},"
597
+ f"amount:{quote.get('amount')}"
598
+ )
599
+
600
+ fundamentals = context.get("fundamentals") if isinstance(context.get("fundamentals"), dict) else {}
601
+ coverage = fundamentals.get("coverage") if isinstance(fundamentals.get("coverage"), dict) else {}
602
+ if coverage:
603
+ available = [
604
+ str(key)
605
+ for key, value in coverage.items()
606
+ if str(value).lower() in {"available", "partial"}
607
+ ]
608
+ if available:
609
+ parts.append(f"fundamental_coverage={','.join(available[:5])}")
610
+
611
+ news_items = p.dsa_news
612
+ if not news_items:
613
+ news_payload = context.get("news") if isinstance(context.get("news"), dict) else {}
614
+ raw_results = news_payload.get("results") if isinstance(news_payload, dict) else []
615
+ if isinstance(raw_results, list):
616
+ news_items = [item for item in raw_results if isinstance(item, dict)]
617
+ titles = [
618
+ _truncate_text(str(item.get("title") or "").strip(), 80)
619
+ for item in news_items[:3]
620
+ if isinstance(item, dict) and item.get("title")
621
+ ]
622
+ if titles:
623
+ parts.append(f"news_titles={';'.join(titles)}")
624
+
625
+ warnings = context.get("warnings") if isinstance(context.get("warnings"), list) else []
626
+ warning_text = [str(item) for item in warnings[:3] if item]
627
+ if warning_text:
628
+ parts.append(f"warnings={';'.join(warning_text)}")
629
+
630
+ return "; ".join(parts) if parts else "none"
631
+
632
+
633
+ def _truncate_text(value: str, limit: int) -> str:
634
+ text = " ".join(value.split())
635
+ if len(text) <= limit:
636
+ return text
637
+ return text[: max(limit - 1, 0)] + "…"
638
+
639
+
640
+ def _call_llm_with_metadata(
641
+ prompt: str,
642
+ api_key: str,
643
+ model: str,
644
+ base_url: str,
645
+ *,
646
+ fallback_models: list[str] | None = None,
647
+ temperature: float = 0.2,
648
+ json_mode: bool = True,
649
+ silent: bool = True,
650
+ channels: list[dict[str, object]] | None = None,
651
+ config_path: str = "",
652
+ timeout_sec: float = 60.0,
653
+ max_tokens: int | None = DEFAULT_LLM_MAX_TOKENS,
654
+ reasoning_effort: str | None = None,
655
+ validator: Callable[[str], Any] | None = None,
656
+ degradation: list[str] | None = None,
657
+ ) -> tuple[str, str]:
658
+ """Try configured OpenAI-compatible endpoints and return (content, used_model)."""
659
+ if error := configuration_error(channels or [], config_path):
660
+ raise LLMClientError(error)
661
+
662
+ attempts = build_attempts(
663
+ model,
664
+ api_key=api_key,
665
+ base_url=base_url,
666
+ channels=channels or [],
667
+ fallback_models=fallback_models or [],
668
+ )
669
+ if not attempts:
670
+ raise RuntimeError("No LLM model configured")
671
+
672
+ messages = [{"role": "user", "content": prompt}]
673
+ response_format = {"type": "json_object"} if json_mode else None
674
+ formats = (response_format, None) if json_mode else (None,)
675
+ last_error: LLMClientError | None = None
676
+ truncation_noted = False
677
+
678
+ for attempt in attempts:
679
+ for requested_format in formats:
680
+ try:
681
+ text = complete(
682
+ attempt,
683
+ messages=messages,
684
+ temperature=temperature,
685
+ max_tokens=max_tokens,
686
+ response_format=requested_format,
687
+ reasoning_effort=reasoning_effort,
688
+ timeout=timeout_sec,
689
+ silent=silent,
690
+ )
691
+ except LLMClientError as exc:
692
+ last_error = exc
693
+ if exc.truncated and not truncation_noted:
694
+ # Recorded here rather than by the caller: a fallback model can
695
+ # still rescue the run, and the truncation must survive that.
696
+ _note_truncation(degradation, exc)
697
+ truncation_noted = True
698
+ if exc.timed_out:
699
+ # Do not blindly retry the SAME endpoint without response_format
700
+ # after a timeout, but fall through to remaining fallback models/channels.
701
+ break
702
+ if requested_format is not None and exc.json_mode_rejected:
703
+ continue
704
+ break
705
+ if validator is not None:
706
+ try:
707
+ validator(text)
708
+ except (ValueError, KeyError, TypeError) as exc:
709
+ last_error = LLMClientError(f"Invalid LLM structured output: {exc}")
710
+ break
711
+ return text, attempt.model
712
+
713
+ if last_error is not None:
714
+ raise last_error
715
+ raise RuntimeError("No LLM model configured")
716
+
717
+
718
+ def _call_llm(
719
+ prompt: str,
720
+ api_key: str,
721
+ model: str,
722
+ base_url: str,
723
+ *,
724
+ fallback_models: list[str] | None = None,
725
+ temperature: float = 0.2,
726
+ json_mode: bool = True,
727
+ silent: bool = True,
728
+ channels: list[dict[str, object]] | None = None,
729
+ config_path: str = "",
730
+ timeout_sec: float = 60.0,
731
+ max_tokens: int | None = DEFAULT_LLM_MAX_TOKENS,
732
+ degradation: list[str] | None = None,
733
+ ) -> str:
734
+ """Try configured OpenAI-compatible endpoints for one LLM prompt."""
735
+ text, _ = _call_llm_with_metadata(
736
+ prompt,
737
+ api_key,
738
+ model,
739
+ base_url,
740
+ fallback_models=fallback_models,
741
+ temperature=temperature,
742
+ json_mode=json_mode,
743
+ silent=silent,
744
+ channels=channels,
745
+ config_path=config_path,
746
+ timeout_sec=timeout_sec,
747
+ max_tokens=max_tokens,
748
+ degradation=degradation,
749
+ )
750
+ return text
751
+
752
+
753
+ def _parse_ranking_response(response: str, candidates: list[Pick]) -> list[Pick]:
754
+ """Parse LLM response and reorder candidates."""
755
+ return _parse_ranking_response_detail(response, candidates).picks
756
+
757
+
758
+ def _parse_ranking_response_detail(response: str, candidates: list[Pick]) -> RankingParseResult:
759
+ """Parse LLM response and return diagnostics."""
760
+ errors: list[str] = []
761
+ if not response or not response.strip():
762
+ errors.append("empty_response")
763
+ logger.warning("Empty LLM ranking response")
764
+ return RankingParseResult(candidates, 0.0, errors, matched_codes=set(), matched_count=0)
765
+
766
+ parsed = _extract_ranking_json(response, errors)
767
+ if parsed is None:
768
+ errors.append("no_json_found")
769
+ logger.warning("No JSON object or array found in LLM response")
770
+ return RankingParseResult(candidates, 0.0, errors, matched_codes=set(), matched_count=0)
771
+ if isinstance(parsed, dict):
772
+ items = parsed.get("ranked", [])
773
+ market_view = _safe_str(parsed.get("market_view"), max_len=260)
774
+ selection_logic = _safe_str(parsed.get("selection_logic"), max_len=360)
775
+ portfolio_risk = _safe_str(parsed.get("portfolio_risk"), max_len=360)
776
+ else:
777
+ items = parsed
778
+ market_view = ""
779
+ selection_logic = ""
780
+ portfolio_risk = ""
781
+ if not isinstance(items, list):
782
+ errors.append("ranked_not_list")
783
+ logger.warning("LLM ranking JSON has no ranked list")
784
+ return RankingParseResult(candidates, 0.0, errors, matched_codes=set(), matched_count=0)
785
+
786
+ code_to_pick = {_normalize_code(p.code): p for p in candidates if _normalize_code(p.code)}
787
+
788
+ ranked = []
789
+ matched = 0
790
+ seen_codes = set()
791
+ for item in items:
792
+ if not isinstance(item, dict):
793
+ errors.append("non_object_item")
794
+ continue
795
+ code = _normalize_code(item.get("code", ""))
796
+ if code in seen_codes:
797
+ errors.append(f"duplicate_code:{code}")
798
+ continue
799
+ seen_codes.add(code)
800
+ if code in code_to_pick:
801
+ pick = code_to_pick.pop(code)
802
+ pick.ranking_reason = _safe_str(item.get("reason"), max_len=180)
803
+ pick.risk_summary = _safe_str(item.get("risk"), max_len=180)
804
+ pick.llm_score = _bounded_float(item.get("llm_score"), low=0, high=100)
805
+ pick.llm_confidence = _bounded_float(item.get("confidence"), low=0, high=1)
806
+ pick.llm_sector = _safe_str(
807
+ item.get("sector") or item.get("industry") or item.get("sector_label"),
808
+ max_len=40,
809
+ )
810
+ pick.llm_theme = _safe_str(item.get("theme"), max_len=100)
811
+ pick.llm_thesis = _safe_str(item.get("thesis"), max_len=220)
812
+ pick.llm_catalysts = _safe_string_list(item.get("catalysts"))
813
+ pick.llm_invalidators = _safe_string_list(item.get("invalidators"))
814
+ pick.llm_style_fit = _safe_str(item.get("style_fit"), max_len=120)
815
+ pick.llm_watch_items = _safe_string_list(item.get("watch_items"))
816
+ pick.llm_risks = _safe_string_list(item.get("risk_flags"))
817
+ pick.llm_tags = _safe_string_list(item.get("tags"))
818
+ if pick.llm_sector:
819
+ pick.llm_tags = _dedupe([*pick.llm_tags, f"sector:{pick.llm_sector}"])
820
+ if pick.llm_theme:
821
+ pick.llm_tags = _dedupe([*pick.llm_tags, f"theme:{pick.llm_theme}"])
822
+ if pick.llm_style_fit:
823
+ pick.llm_tags = _dedupe([*pick.llm_tags, f"style_fit:{pick.llm_style_fit}"])
824
+ ranked.append(pick)
825
+ matched += 1
826
+ elif code:
827
+ errors.append(f"unknown_code:{code}")
828
+
829
+ # Append any candidates not mentioned by LLM, preserving which codes were actually matched.
830
+ matched_codes = {_normalize_code(p.code) for p in ranked if _normalize_code(p.code)}
831
+ ranked.extend(code_to_pick.values())
832
+ coverage = matched / max(len(candidates), 1)
833
+ return RankingParseResult(
834
+ ranked,
835
+ coverage,
836
+ errors,
837
+ market_view=market_view,
838
+ selection_logic=selection_logic,
839
+ portfolio_risk=portfolio_risk,
840
+ matched_codes=matched_codes,
841
+ matched_count=matched,
842
+ )
843
+
844
+
845
+ def _safe_str(value, *, max_len: int) -> str:
846
+ return safe_text(value, max_len=max_len)
847
+
848
+
849
+ def _try_parse_json_lenient(raw: str, errors: list[str]):
850
+ """Attempt to parse LLM JSON output, tolerating common formatting drift.
851
+
852
+ Steps applied in order: strict parse → strip trailing commas → balance
853
+ truncated brackets → return None if all fail. Any repair that succeeds is
854
+ recorded in ``errors`` for diagnostics.
855
+ """
856
+ import re
857
+
858
+ try:
859
+ return json.loads(raw)
860
+ except json.JSONDecodeError as exc:
861
+ first_error = exc
862
+
863
+ # Repair 1: remove trailing commas before } or ].
864
+ repaired = re.sub(r",(\s*[}\]])", r"\1", raw)
865
+ if repaired != raw:
866
+ try:
867
+ result = json.loads(repaired)
868
+ errors.append("json_repaired:trailing_comma")
869
+ return result
870
+ except json.JSONDecodeError:
871
+ pass
872
+
873
+ # Repair 2: close unbalanced brackets caused by truncated output.
874
+ open_curly = repaired.count("{") - repaired.count("}")
875
+ open_square = repaired.count("[") - repaired.count("]")
876
+ if open_curly > 0 or open_square > 0:
877
+ patched = repaired + ("]" * max(open_square, 0)) + ("}" * max(open_curly, 0))
878
+ try:
879
+ result = json.loads(patched)
880
+ errors.append("json_repaired:closed_brackets")
881
+ return result
882
+ except json.JSONDecodeError:
883
+ pass
884
+
885
+ errors.append(f"json_decode_error:{first_error}")
886
+ logger.warning("Failed to parse LLM ranking JSON: %s", first_error)
887
+ return None
888
+
889
+
890
+ def _extract_ranking_json(response: str, errors: list[str]):
891
+ """Extract ranking JSON from common LLM response shapes."""
892
+ for raw in _iter_json_payloads(response):
893
+ parsed = _try_parse_json_lenient(raw, errors)
894
+ if _looks_like_ranking_payload(parsed):
895
+ return parsed
896
+
897
+ partial = _extract_partial_ranking_array(response, errors)
898
+ if partial is not None:
899
+ return partial
900
+ return None
901
+
902
+
903
+ def _looks_like_ranking_payload(value: object) -> bool:
904
+ if isinstance(value, dict):
905
+ return isinstance(value.get("ranked"), list)
906
+ if isinstance(value, list):
907
+ return any(isinstance(item, dict) and "code" in item for item in value)
908
+ return False
909
+
910
+
911
+ def _iter_json_payloads(response: str):
912
+ """Yield likely JSON payload substrings in priority order."""
913
+ import re
914
+
915
+ yielded: set[str] = set()
916
+ fence_pattern = re.compile(r"```(?:json|JSON)?\s*(.*?)```", re.DOTALL)
917
+ for match in fence_pattern.finditer(response):
918
+ payload = match.group(1).strip()
919
+ if payload and payload not in yielded:
920
+ yielded.add(payload)
921
+ yield payload
922
+
923
+ cleaned = fence_pattern.sub(lambda match: match.group(1), response)
924
+ for payload in _balanced_json_values(cleaned):
925
+ if payload not in yielded:
926
+ yielded.add(payload)
927
+ yield payload
928
+
929
+
930
+ def _balanced_json_values(text: str) -> list[str]:
931
+ """Return balanced top-level JSON object/array substrings."""
932
+ values: list[str] = []
933
+ stack: list[str] = []
934
+ start: int | None = None
935
+ in_string = False
936
+ escaped = False
937
+ pairs = {"{": "}", "[": "]"}
938
+
939
+ for index, char in enumerate(text):
940
+ if in_string:
941
+ if escaped:
942
+ escaped = False
943
+ elif char == "\\":
944
+ escaped = True
945
+ elif char == '"':
946
+ in_string = False
947
+ continue
948
+ if char == '"':
949
+ in_string = True
950
+ continue
951
+ if char in pairs:
952
+ if not stack:
953
+ start = index
954
+ stack.append(pairs[char])
955
+ continue
956
+ if char in ("}", "]") and stack:
957
+ expected = stack.pop()
958
+ if char != expected:
959
+ stack.clear()
960
+ start = None
961
+ continue
962
+ if not stack and start is not None:
963
+ values.append(text[start : index + 1])
964
+ start = None
965
+ return values
966
+
967
+
968
+ def _extract_partial_ranking_array(response: str, errors: list[str]):
969
+ """Recover a ranked list from multiple JSON objects in a noisy response."""
970
+ items = []
971
+ item_errors: list[str] = []
972
+ for raw in _balanced_json_values(response):
973
+ parsed = _try_parse_json_lenient(raw, item_errors)
974
+ if isinstance(parsed, dict) and "code" in parsed:
975
+ items.append(parsed)
976
+ if not items:
977
+ return None
978
+ errors.append("json_repaired:partial_array")
979
+ return {"ranked": items}
980
+
981
+
982
+ def _dedupe(items: list[str]) -> list[str]:
983
+ seen = set()
984
+ result = []
985
+ for item in items:
986
+ key = str(item).strip()
987
+ if key and key not in seen:
988
+ seen.add(key)
989
+ result.append(key)
990
+ return result