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.
- alphasift/__init__.py +52 -0
- alphasift/__main__.py +7 -0
- alphasift/audit.py +191 -0
- alphasift/candidate_context.py +738 -0
- alphasift/cli.py +2797 -0
- alphasift/config.py +705 -0
- alphasift/context.py +672 -0
- alphasift/daily.py +1256 -0
- alphasift/daily_brief.py +593 -0
- alphasift/daily_report.py +1115 -0
- alphasift/daily_report_html.py +1257 -0
- alphasift/doctor.py +1123 -0
- alphasift/dsa.py +302 -0
- alphasift/dsa_adapter.py +178 -0
- alphasift/dsa_provider.py +192 -0
- alphasift/evaluate.py +2418 -0
- alphasift/filter.py +517 -0
- alphasift/hotspot.py +1713 -0
- alphasift/industry.py +959 -0
- alphasift/llm_client.py +349 -0
- alphasift/market_digest.py +284 -0
- alphasift/market_news.py +446 -0
- alphasift/market_regime.py +578 -0
- alphasift/markets.py +160 -0
- alphasift/mcp.py +720 -0
- alphasift/models.py +315 -0
- alphasift/normalize.py +113 -0
- alphasift/notify.py +2608 -0
- alphasift/overview.py +225 -0
- alphasift/pack.py +1470 -0
- alphasift/pack_features.py +431 -0
- alphasift/pattern_replay.py +1449 -0
- alphasift/patterns/bottom_volume_yang.yaml +32 -0
- alphasift/patterns/box_breakout.yaml +36 -0
- alphasift/patterns/double_bottom_breakout.yaml +38 -0
- alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
- alphasift/patterns/shooting_star_confirm.yaml +49 -0
- alphasift/patterns/single_yang_hold.yaml +44 -0
- alphasift/patterns/steady_trend_breakout.yaml +39 -0
- alphasift/patterns/three_white_soldiers.yaml +72 -0
- alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
- alphasift/patterns.py +1233 -0
- alphasift/performance_history.py +297 -0
- alphasift/pipeline.py +1010 -0
- alphasift/post_analysis.py +337 -0
- alphasift/ranker.py +990 -0
- alphasift/report.py +379 -0
- alphasift/result_schema.py +179 -0
- alphasift/risk.py +452 -0
- alphasift/run_history.py +164 -0
- alphasift/scorer.py +597 -0
- alphasift/server.py +680 -0
- alphasift/snapshot.py +1025 -0
- alphasift/snapshot_us.py +280 -0
- alphasift/snapshot_yahoo.py +358 -0
- alphasift/source_guard.py +70 -0
- alphasift/source_history.py +306 -0
- alphasift/store.py +294 -0
- alphasift/strategies/balanced_alpha.yaml +76 -0
- alphasift/strategies/blue_chip_income.yaml +87 -0
- alphasift/strategies/capital_heat.yaml +74 -0
- alphasift/strategies/dual_low.yaml +80 -0
- alphasift/strategies/global_value.yaml +65 -0
- alphasift/strategies/low_volatility_quality.yaml +95 -0
- alphasift/strategies/momentum_quality.yaml +81 -0
- alphasift/strategies/oversold_reversal.yaml +75 -0
- alphasift/strategies/quality_value.yaml +80 -0
- alphasift/strategies/shrink_pullback.yaml +77 -0
- alphasift/strategies/us_momentum_quality.yaml +74 -0
- alphasift/strategies/volume_breakout.yaml +78 -0
- alphasift/strategy.py +1090 -0
- alphasift/strategy_cards.py +424 -0
- alphasift/strategy_templates.py +291 -0
- alphasift/timeutil.py +38 -0
- alphasift/valuation_kr.py +149 -0
- alphasift/workbench_ui.py +1051 -0
- alphasift-0.3.1.data/data/.env.example +151 -0
- alphasift-0.3.1.data/data/LICENSE +184 -0
- alphasift-0.3.1.data/data/SKILL.md +190 -0
- alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
- alphasift-0.3.1.dist-info/METADATA +312 -0
- alphasift-0.3.1.dist-info/RECORD +86 -0
- alphasift-0.3.1.dist-info/WHEEL +5 -0
- alphasift-0.3.1.dist-info/entry_points.txt +2 -0
- alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
- alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/daily_brief.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Cross-strategy synthesis and AI / deterministic daily editorial brief for CN reports."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from alphasift.config import Config
|
|
13
|
+
|
|
14
|
+
BRIEF_DISCLAIMER = "仅供量化研究与复盘观察,不构成投资建议。"
|
|
15
|
+
|
|
16
|
+
BUILTIN_STRATEGY_DISPLAY_NAMES: dict[str, str] = {
|
|
17
|
+
"balanced_alpha": "均衡多因子",
|
|
18
|
+
"blue_chip_income": "蓝筹收益质量",
|
|
19
|
+
"capital_heat": "资金热度",
|
|
20
|
+
"dual_low": "双低选股",
|
|
21
|
+
"global_value": "全球低估值",
|
|
22
|
+
"low_volatility_quality": "低波质量",
|
|
23
|
+
"momentum_quality": "趋势质量",
|
|
24
|
+
"oversold_reversal": "超跌反转",
|
|
25
|
+
"quality_value": "稳健价值",
|
|
26
|
+
"shrink_pullback": "缩量回踩",
|
|
27
|
+
"us_momentum_quality": "美股趋势质量",
|
|
28
|
+
"volume_breakout": "放量突破",
|
|
29
|
+
}
|
|
30
|
+
_STRATEGY_NAMES_CACHE: dict[Path | None, dict[str, str]] = {}
|
|
31
|
+
_THINK_CLOSED_RE = re.compile(r"<think>.*?</think>", flags=re.IGNORECASE | re.DOTALL)
|
|
32
|
+
_THINK_UNCLOSED_TAIL_RE = re.compile(r"<think>.*$", flags=re.IGNORECASE | re.DOTALL)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def resolve_strategy_display_names(
|
|
36
|
+
strategies_dir: Path | None = None,
|
|
37
|
+
*,
|
|
38
|
+
overrides: dict[str, str] | None = None,
|
|
39
|
+
) -> dict[str, str]:
|
|
40
|
+
"""Return mapping of strategy slug -> localized display name."""
|
|
41
|
+
cache_key = strategies_dir.resolve() if isinstance(strategies_dir, Path) else None
|
|
42
|
+
base = _STRATEGY_NAMES_CACHE.get(cache_key)
|
|
43
|
+
if base is None:
|
|
44
|
+
merged = dict(BUILTIN_STRATEGY_DISPLAY_NAMES)
|
|
45
|
+
try:
|
|
46
|
+
from alphasift.strategy import list_strategies
|
|
47
|
+
|
|
48
|
+
for info in list_strategies(strategies_dir):
|
|
49
|
+
if info.name and info.display_name:
|
|
50
|
+
# Keep clean Chinese label for us_momentum_quality when YAML uses ASCII title
|
|
51
|
+
if info.name in BUILTIN_STRATEGY_DISPLAY_NAMES and info.display_name.isascii():
|
|
52
|
+
continue
|
|
53
|
+
merged[info.name] = str(info.display_name).strip()
|
|
54
|
+
except Exception: # noqa: BLE001
|
|
55
|
+
pass
|
|
56
|
+
_STRATEGY_NAMES_CACHE[cache_key] = merged
|
|
57
|
+
base = merged
|
|
58
|
+
out = dict(base)
|
|
59
|
+
if isinstance(overrides, dict):
|
|
60
|
+
for k, v in overrides.items():
|
|
61
|
+
if k and v:
|
|
62
|
+
out[str(k)] = str(v)
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def build_cross_strategy_synthesis(
|
|
67
|
+
report: dict[str, Any],
|
|
68
|
+
*,
|
|
69
|
+
strategy_names: dict[str, str] | None = None,
|
|
70
|
+
) -> dict[str, Any]:
|
|
71
|
+
"""Build deterministic cross-strategy consensus, sector concentration, resonance, and risk spotlight."""
|
|
72
|
+
display_map = resolve_strategy_display_names(
|
|
73
|
+
overrides=(strategy_names or report.get("strategy_display_names"))
|
|
74
|
+
)
|
|
75
|
+
cand_news = (
|
|
76
|
+
(report.get("market_news") or {}).get("candidate_news") or {}
|
|
77
|
+
if isinstance(report.get("market_news"), dict)
|
|
78
|
+
else {}
|
|
79
|
+
)
|
|
80
|
+
strategies = report.get("strategies") or []
|
|
81
|
+
by_code: dict[str, dict[str, Any]] = {}
|
|
82
|
+
sector_counts: dict[str, dict[str, Any]] = {}
|
|
83
|
+
pick_pairs_seen: set[tuple[str, str]] = set()
|
|
84
|
+
total_pick_slots = 0
|
|
85
|
+
|
|
86
|
+
for st in strategies:
|
|
87
|
+
if not isinstance(st, dict):
|
|
88
|
+
continue
|
|
89
|
+
strat_name = str(st.get("strategy") or "").strip()
|
|
90
|
+
track_name = str(st.get("track") or ("ai" if st.get("llm_ranked") else "rules"))
|
|
91
|
+
for pk in st.get("picks") or []:
|
|
92
|
+
if not isinstance(pk, dict):
|
|
93
|
+
continue
|
|
94
|
+
code = str(pk.get("code") or "").strip()
|
|
95
|
+
if not code:
|
|
96
|
+
continue
|
|
97
|
+
name = str(pk.get("name") or "").strip()
|
|
98
|
+
industry = str(pk.get("industry") or "").strip()
|
|
99
|
+
score = pk.get("final_score")
|
|
100
|
+
chg = pk.get("change_pct")
|
|
101
|
+
reason = str(pk.get("ranking_reason") or "").strip()
|
|
102
|
+
ann_flags = [str(f) for f in (pk.get("announcement_risk_flags") or []) if f]
|
|
103
|
+
risk_flags = [str(f) for f in (pk.get("risk_flags") or []) if f]
|
|
104
|
+
risk_level = str(pk.get("risk_level") or "").strip()
|
|
105
|
+
|
|
106
|
+
entry = by_code.setdefault(
|
|
107
|
+
code,
|
|
108
|
+
{
|
|
109
|
+
"code": code,
|
|
110
|
+
"name": name,
|
|
111
|
+
"industry": industry,
|
|
112
|
+
"strategies": set(),
|
|
113
|
+
"tracks": set(),
|
|
114
|
+
"scores": [],
|
|
115
|
+
"change_pct": chg,
|
|
116
|
+
"price": pk.get("price"),
|
|
117
|
+
"pe_ratio": pk.get("pe_ratio"),
|
|
118
|
+
"pb_ratio": pk.get("pb_ratio"),
|
|
119
|
+
"market_cap_yi": pk.get("market_cap_yi"),
|
|
120
|
+
"reasons": [],
|
|
121
|
+
"announcement_risk_flags": set(),
|
|
122
|
+
"risk_flags": set(),
|
|
123
|
+
"risk_level": risk_level,
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
if not entry["name"] and name:
|
|
127
|
+
entry["name"] = name
|
|
128
|
+
if not entry["industry"] and industry:
|
|
129
|
+
entry["industry"] = industry
|
|
130
|
+
if strat_name:
|
|
131
|
+
entry["strategies"].add(strat_name)
|
|
132
|
+
entry["tracks"].add(track_name)
|
|
133
|
+
if score is not None:
|
|
134
|
+
entry["scores"].append(float(score))
|
|
135
|
+
if entry["change_pct"] is None and chg is not None:
|
|
136
|
+
entry["change_pct"] = chg
|
|
137
|
+
for fld in ("price", "pe_ratio", "pb_ratio", "market_cap_yi"):
|
|
138
|
+
if entry[fld] is None and pk.get(fld) is not None:
|
|
139
|
+
entry[fld] = pk.get(fld)
|
|
140
|
+
if reason and reason not in entry["reasons"] and len(entry["reasons"]) < 2:
|
|
141
|
+
entry["reasons"].append(reason)
|
|
142
|
+
entry["announcement_risk_flags"].update(ann_flags)
|
|
143
|
+
entry["risk_flags"].update(risk_flags)
|
|
144
|
+
if not entry["risk_level"] and risk_level:
|
|
145
|
+
entry["risk_level"] = risk_level
|
|
146
|
+
|
|
147
|
+
pair_key = (strat_name or track_name, code)
|
|
148
|
+
if pair_key not in pick_pairs_seen:
|
|
149
|
+
pick_pairs_seen.add(pair_key)
|
|
150
|
+
total_pick_slots += 1
|
|
151
|
+
ind_key = industry or "未分类"
|
|
152
|
+
sec = sector_counts.setdefault(ind_key, {"industry": ind_key, "pick_count": 0, "codes": set()})
|
|
153
|
+
sec["pick_count"] += 1
|
|
154
|
+
sec["codes"].add(code)
|
|
155
|
+
|
|
156
|
+
consensus_picks: list[dict[str, Any]] = []
|
|
157
|
+
for code, item in by_code.items():
|
|
158
|
+
if len(item["strategies"]) < 2:
|
|
159
|
+
continue
|
|
160
|
+
avg_score = round(sum(item["scores"]) / len(item["scores"]), 2) if item["scores"] else 0.0
|
|
161
|
+
sorted_strats = sorted(item["strategies"])
|
|
162
|
+
news_list = cand_news.get(code) if isinstance(cand_news, dict) else None
|
|
163
|
+
first_news = ""
|
|
164
|
+
if isinstance(news_list, list) and news_list:
|
|
165
|
+
first_item = news_list[0]
|
|
166
|
+
if isinstance(first_item, dict):
|
|
167
|
+
first_news = str(first_item.get("title") or "").strip()[:100]
|
|
168
|
+
else:
|
|
169
|
+
first_news = str(first_item).strip()[:100]
|
|
170
|
+
rec: dict[str, Any] = {
|
|
171
|
+
"code": code,
|
|
172
|
+
"name": item["name"],
|
|
173
|
+
"industry": item["industry"],
|
|
174
|
+
"strategy_count": len(sorted_strats),
|
|
175
|
+
"strategies": sorted_strats,
|
|
176
|
+
"strategy_display_names": [display_map.get(s, s) for s in sorted_strats],
|
|
177
|
+
"tracks": sorted(item["tracks"]),
|
|
178
|
+
"avg_final_score": avg_score,
|
|
179
|
+
"change_pct": item["change_pct"],
|
|
180
|
+
"announcement_risk_flags": sorted(item["announcement_risk_flags"]),
|
|
181
|
+
}
|
|
182
|
+
for fld in ("price", "pe_ratio", "pb_ratio", "market_cap_yi"):
|
|
183
|
+
if item[fld] is not None:
|
|
184
|
+
rec[fld] = item[fld]
|
|
185
|
+
if item["reasons"]:
|
|
186
|
+
rec["reasons"] = item["reasons"]
|
|
187
|
+
if first_news:
|
|
188
|
+
rec["news_headline"] = first_news
|
|
189
|
+
consensus_picks.append(rec)
|
|
190
|
+
consensus_picks.sort(key=lambda x: (-x["strategy_count"], -x["avg_final_score"], x["code"]))
|
|
191
|
+
|
|
192
|
+
sector_concentration: list[dict[str, Any]] = []
|
|
193
|
+
for sec in sector_counts.values():
|
|
194
|
+
sector_concentration.append({
|
|
195
|
+
"industry": sec["industry"],
|
|
196
|
+
"pick_count": sec["pick_count"],
|
|
197
|
+
"unique_codes": len(sec["codes"]),
|
|
198
|
+
"share_pct": round((sec["pick_count"] / total_pick_slots) * 100.0, 1) if total_pick_slots else 0.0,
|
|
199
|
+
})
|
|
200
|
+
sector_concentration.sort(key=lambda x: (-x["pick_count"], -x["unique_codes"], x["industry"]))
|
|
201
|
+
|
|
202
|
+
pat_sec = report.get("patterns") or {}
|
|
203
|
+
pat_hits: dict[str, dict[str, Any]] = {}
|
|
204
|
+
for bucket, pat_key in (("active", "active_patterns"), ("experimental", "experimental_patterns")):
|
|
205
|
+
for pat in pat_sec.get(bucket) or []:
|
|
206
|
+
if not isinstance(pat, dict):
|
|
207
|
+
continue
|
|
208
|
+
pname = str(pat.get("display_name") or pat.get("pattern") or "").strip()
|
|
209
|
+
for sig in pat.get("signals") or []:
|
|
210
|
+
if not isinstance(sig, dict):
|
|
211
|
+
continue
|
|
212
|
+
code = str(sig.get("code") or "").strip()
|
|
213
|
+
if code not in by_code:
|
|
214
|
+
continue
|
|
215
|
+
rec = pat_hits.setdefault(code, {"active_patterns": [], "experimental_patterns": []})
|
|
216
|
+
if pname and pname not in rec[pat_key]:
|
|
217
|
+
rec[pat_key].append(pname)
|
|
218
|
+
|
|
219
|
+
strategy_pattern_resonance: list[dict[str, Any]] = []
|
|
220
|
+
for code in sorted(pat_hits):
|
|
221
|
+
st_info = by_code[code]
|
|
222
|
+
p_info = pat_hits[code]
|
|
223
|
+
strategy_pattern_resonance.append({
|
|
224
|
+
"code": code,
|
|
225
|
+
"name": st_info["name"],
|
|
226
|
+
"strategies": sorted(st_info["strategies"]),
|
|
227
|
+
"active_patterns": p_info["active_patterns"],
|
|
228
|
+
"experimental_patterns": p_info["experimental_patterns"],
|
|
229
|
+
"announcement_risk_flags": sorted(st_info["announcement_risk_flags"]),
|
|
230
|
+
})
|
|
231
|
+
strategy_pattern_resonance.sort(
|
|
232
|
+
key=lambda x: (-len(x["active_patterns"]), -len(x["strategies"]), -len(x["experimental_patterns"]), x["code"])
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
risk_map: dict[str, dict[str, Any]] = {}
|
|
236
|
+
ann = report.get("announcement_risks") or {}
|
|
237
|
+
for item in ann.get("flagged_items") or []:
|
|
238
|
+
if not isinstance(item, dict):
|
|
239
|
+
continue
|
|
240
|
+
code = str(item.get("code") or "").strip()
|
|
241
|
+
if not code:
|
|
242
|
+
continue
|
|
243
|
+
flags = [str(f) for f in (item.get("negative_event_flags") or []) if f]
|
|
244
|
+
risk_map[code] = {
|
|
245
|
+
"code": code,
|
|
246
|
+
"name": str(item.get("name") or "").strip(),
|
|
247
|
+
"severity": "high",
|
|
248
|
+
"flags": flags,
|
|
249
|
+
"summary": str(item.get("announcement_summary") or "").strip()[:160],
|
|
250
|
+
"source": "announcement",
|
|
251
|
+
}
|
|
252
|
+
for code, item in by_code.items():
|
|
253
|
+
if code in risk_map:
|
|
254
|
+
continue
|
|
255
|
+
flags = sorted(item["announcement_risk_flags"] | item["risk_flags"])
|
|
256
|
+
lvl = item["risk_level"].lower()
|
|
257
|
+
if flags or lvl in {"high", "warning"}:
|
|
258
|
+
risk_map[code] = {
|
|
259
|
+
"code": code,
|
|
260
|
+
"name": item["name"],
|
|
261
|
+
"severity": "high" if (item["announcement_risk_flags"] or lvl == "high") else "medium",
|
|
262
|
+
"flags": flags or [item["risk_level"]],
|
|
263
|
+
"summary": "",
|
|
264
|
+
"source": "pick_risk",
|
|
265
|
+
}
|
|
266
|
+
risk_spotlight = sorted(
|
|
267
|
+
risk_map.values(),
|
|
268
|
+
key=lambda x: (0 if x["severity"] == "high" else 1, -len(x["flags"]), x["code"]),
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
"consensus_picks": consensus_picks[:12],
|
|
273
|
+
"sector_concentration": sector_concentration[:8],
|
|
274
|
+
"strategy_pattern_resonance": strategy_pattern_resonance[:10],
|
|
275
|
+
"risk_spotlight": risk_spotlight[:10],
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _strip_json_fences(raw: str) -> str:
|
|
280
|
+
cleaned = _THINK_CLOSED_RE.sub("", str(raw or "")).strip()
|
|
281
|
+
cleaned = _THINK_UNCLOSED_TAIL_RE.sub("", cleaned).strip()
|
|
282
|
+
if cleaned.startswith("```"):
|
|
283
|
+
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned, flags=re.IGNORECASE)
|
|
284
|
+
cleaned = re.sub(r"\s*```$", "", cleaned)
|
|
285
|
+
return cleaned.strip()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _parse_brief_json(raw: str) -> dict[str, Any]:
|
|
289
|
+
cleaned = _strip_json_fences(raw)
|
|
290
|
+
try:
|
|
291
|
+
parsed = json.loads(cleaned)
|
|
292
|
+
except ValueError:
|
|
293
|
+
start = cleaned.find("{")
|
|
294
|
+
end = cleaned.rfind("}")
|
|
295
|
+
if start < 0 or end <= start:
|
|
296
|
+
raise ValueError("no_json_object_in_brief_response") from None
|
|
297
|
+
parsed = json.loads(cleaned[start : end + 1])
|
|
298
|
+
if not isinstance(parsed, dict):
|
|
299
|
+
raise ValueError("brief_json_not_object")
|
|
300
|
+
|
|
301
|
+
headline = str(parsed.get("headline") or "").strip()
|
|
302
|
+
regime_interp = str(parsed.get("regime_interpretation") or "").strip()
|
|
303
|
+
consensus_edge = str(parsed.get("consensus_and_ai_edge") or "").strip()
|
|
304
|
+
if not headline or not regime_interp:
|
|
305
|
+
raise ValueError("brief_json_missing_required_fields")
|
|
306
|
+
|
|
307
|
+
warnings = [
|
|
308
|
+
str(x).strip()
|
|
309
|
+
for x in (parsed.get("risk_warnings") or [])
|
|
310
|
+
if str(x).strip()
|
|
311
|
+
][:5]
|
|
312
|
+
watches = [
|
|
313
|
+
str(x).strip()
|
|
314
|
+
for x in (parsed.get("watch_points") or [])
|
|
315
|
+
if str(x).strip()
|
|
316
|
+
][:5]
|
|
317
|
+
return {
|
|
318
|
+
"headline": headline[:140],
|
|
319
|
+
"regime_interpretation": regime_interp[:400],
|
|
320
|
+
"consensus_and_ai_edge": (consensus_edge or "多策略结果仅作同口径跟踪对照。")[:400],
|
|
321
|
+
"risk_warnings": warnings,
|
|
322
|
+
"watch_points": watches,
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _build_rule_daily_brief(
|
|
327
|
+
report: dict[str, Any],
|
|
328
|
+
*,
|
|
329
|
+
track_comparison: Sequence[dict[str, Any]] | None = None,
|
|
330
|
+
fallback_reason: str | None = None,
|
|
331
|
+
) -> dict[str, Any]:
|
|
332
|
+
reg = report.get("market_regime") or {}
|
|
333
|
+
stage_label = str(reg.get("regime_stage_label") or "-")
|
|
334
|
+
adv = float(reg.get("advance_ratio_pct") or 0.0)
|
|
335
|
+
med = reg.get("median_return_pct")
|
|
336
|
+
med_txt = f"中位数 {float(med):+.2f}%" if med is not None else "中位数待统计"
|
|
337
|
+
lu = int(reg.get("non_st_limit_up_count") or 0)
|
|
338
|
+
ld = int(reg.get("non_st_limit_down_count") or 0)
|
|
339
|
+
seal = reg.get("seal_rate_pct")
|
|
340
|
+
seal_txt = f"{float(seal):.1f}%" if seal is not None else "-"
|
|
341
|
+
prev_lu = reg.get("prev_limit_up_avg_return_pct")
|
|
342
|
+
prev_txt = f"{float(prev_lu):+.2f}%" if prev_lu is not None else "-"
|
|
343
|
+
max_streak = int(reg.get("max_consecutive_limit_up") or 0)
|
|
344
|
+
amt = reg.get("total_amount_yi")
|
|
345
|
+
amt_txt = f"{float(amt):.0f}亿" if amt is not None else "-"
|
|
346
|
+
|
|
347
|
+
syn = report.get("cross_strategy_synthesis") or build_cross_strategy_synthesis(report)
|
|
348
|
+
consensus = syn.get("consensus_picks") or []
|
|
349
|
+
sectors = syn.get("sector_concentration") or []
|
|
350
|
+
ann = report.get("announcement_risks") or {}
|
|
351
|
+
flagged = ann.get("flagged_items") or []
|
|
352
|
+
ai_hl = report.get("ai_highlights") or []
|
|
353
|
+
stale_prefix = "【旧包降级】" if report.get("pack_is_stale") else ""
|
|
354
|
+
|
|
355
|
+
headline = (
|
|
356
|
+
f"{stale_prefix}盘面处于{stage_label}阶段,上涨 {adv:.1f}%({med_txt}),"
|
|
357
|
+
f"涨跌停 {lu}/{ld}(封板率 {seal_txt})"
|
|
358
|
+
)
|
|
359
|
+
if flagged:
|
|
360
|
+
headline += f",公告排雷命中 {len(flagged)} 只预警"
|
|
361
|
+
elif consensus:
|
|
362
|
+
headline += f",跨策略共识 {len(consensus)} 只"
|
|
363
|
+
|
|
364
|
+
regime_interpretation = (
|
|
365
|
+
f"{report.get('trade_date', '-')} 全市场情绪处于「{stage_label}」阶段:"
|
|
366
|
+
f"全市场上涨占比 {adv:.1f}%、{med_txt},成交额 {amt_txt};"
|
|
367
|
+
f"非 ST 涨停 {lu} 只 / 跌停 {ld} 只,首板封板率 {seal_txt},连板最高 {max_streak} 板,昨涨停今日均表现 {prev_txt}。"
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
parts: list[str] = []
|
|
371
|
+
if consensus:
|
|
372
|
+
top_c = "、".join(
|
|
373
|
+
f"{c['code']}{c['name']}({c['strategy_count']}策略)" for c in consensus[:3]
|
|
374
|
+
)
|
|
375
|
+
parts.append(f"多策略共振标的前列:{top_c}")
|
|
376
|
+
else:
|
|
377
|
+
parts.append("当日各策略候选分散,未出现 ≥2 个策略共同命中的重合股")
|
|
378
|
+
if sectors:
|
|
379
|
+
top_s = "、".join(f"{s['industry']}({s['share_pct']}%)" for s in sectors[:3])
|
|
380
|
+
parts.append(f"行业主要集中在 {top_s}")
|
|
381
|
+
if ai_hl:
|
|
382
|
+
added_n = sum(len(h.get("added_by_ai") or []) for h in ai_hl if isinstance(h, dict))
|
|
383
|
+
dropped_n = sum(len(h.get("dropped_by_ai") or []) for h in ai_hl if isinstance(h, dict))
|
|
384
|
+
parts.append(f"AI 赛道当日调仓累计新增 {added_n} 只 / 剔除 {dropped_n} 只")
|
|
385
|
+
elif track_comparison:
|
|
386
|
+
cn_cmp = [c for c in track_comparison if c.get("market") == "cn"]
|
|
387
|
+
if cn_cmp:
|
|
388
|
+
parts.append(f"当前已追踪 {len(cn_cmp)} 组 CN 规则 vs AI 同日配对样本")
|
|
389
|
+
consensus_and_ai_edge = ";".join(parts) + "。"
|
|
390
|
+
|
|
391
|
+
risk_warnings: list[str] = []
|
|
392
|
+
if report.get("pack_is_stale"):
|
|
393
|
+
risk_warnings.append(
|
|
394
|
+
f"数据包滞后(包日期 {report.get('pack_trade_date')} < 目标日 {report.get('expected_trade_date')}),盘面与形态仅供参考。"
|
|
395
|
+
)
|
|
396
|
+
for item in flagged[:3]:
|
|
397
|
+
fl = "/".join(str(x) for x in (item.get("negative_event_flags") or [])[:2])
|
|
398
|
+
risk_warnings.append(f"公告预警:{item.get('code')} {item.get('name', '')} 命中 [{fl}]")
|
|
399
|
+
if not flagged and int(ann.get("checked_count") or 0) > 0:
|
|
400
|
+
risk_warnings.append(f"已抽检 {int(ann.get('checked_count') or 0)} 只核心候选,未触发减持/立案等负面关键词。")
|
|
401
|
+
if ld >= 20 or (seal is not None and float(seal) < 55.0):
|
|
402
|
+
risk_warnings.append(f"短线承接偏弱(非 ST 跌停 {ld} 只,封板率 {seal_txt}),警惕高位接力退潮风险。")
|
|
403
|
+
if not risk_warnings:
|
|
404
|
+
risk_warnings.append("关注次日开盘一字涨停导致的不可成交剔除以及市场成交额持续性。")
|
|
405
|
+
|
|
406
|
+
watch_points = [
|
|
407
|
+
f"观察次日上涨占比能否从 {adv:.1f}% 修复、跌停家数({ld} 只)是否收敛;",
|
|
408
|
+
f"跟踪昨日涨停溢价({prev_txt})与连板梯队({max_streak} 板)高度延续情况;",
|
|
409
|
+
]
|
|
410
|
+
if consensus:
|
|
411
|
+
watch_points.append(
|
|
412
|
+
f"复盘多策略共识标的({consensus[0]['code']} {consensus[0]['name']} 等)次日开盘承接与换手。"
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
return {
|
|
416
|
+
"mode": "rule_fallback",
|
|
417
|
+
"model": None,
|
|
418
|
+
"headline": headline[:140],
|
|
419
|
+
"regime_interpretation": regime_interpretation,
|
|
420
|
+
"consensus_and_ai_edge": consensus_and_ai_edge,
|
|
421
|
+
"risk_warnings": risk_warnings[:5],
|
|
422
|
+
"watch_points": watch_points[:4],
|
|
423
|
+
"disclaimer": BRIEF_DISCLAIMER,
|
|
424
|
+
"fallback_reason": fallback_reason,
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _build_brief_prompt(
|
|
429
|
+
report: dict[str, Any],
|
|
430
|
+
*,
|
|
431
|
+
synthesis: dict[str, Any],
|
|
432
|
+
track_comparison: Sequence[dict[str, Any]] | None = None,
|
|
433
|
+
) -> str:
|
|
434
|
+
reg = report.get("market_regime") or {}
|
|
435
|
+
mnews = report.get("market_news") or {}
|
|
436
|
+
strat_names = report.get("strategy_display_names") or resolve_strategy_display_names()
|
|
437
|
+
compact_news = [
|
|
438
|
+
{
|
|
439
|
+
"category": n.get("category"),
|
|
440
|
+
"source": n.get("source"),
|
|
441
|
+
"time": n.get("published_at"),
|
|
442
|
+
"title": n.get("title"),
|
|
443
|
+
}
|
|
444
|
+
for n in (mnews.get("items") or [])[:5]
|
|
445
|
+
if isinstance(n, dict) and n.get("title")
|
|
446
|
+
]
|
|
447
|
+
compact_context: dict[str, Any] = {
|
|
448
|
+
"trade_date": report.get("trade_date"),
|
|
449
|
+
"pack_trade_date": report.get("pack_trade_date"),
|
|
450
|
+
"pack_is_stale": bool(report.get("pack_is_stale", False)),
|
|
451
|
+
"strategy_display_names": strat_names,
|
|
452
|
+
"market_regime": {
|
|
453
|
+
"stage": reg.get("regime_stage"),
|
|
454
|
+
"stage_label": reg.get("regime_stage_label"),
|
|
455
|
+
"advance_ratio_pct": reg.get("advance_ratio_pct"),
|
|
456
|
+
"median_return_pct": reg.get("median_return_pct"),
|
|
457
|
+
"non_st_limit_up": reg.get("non_st_limit_up_count"),
|
|
458
|
+
"non_st_limit_down": reg.get("non_st_limit_down_count"),
|
|
459
|
+
"seal_rate_pct": reg.get("seal_rate_pct"),
|
|
460
|
+
"max_consecutive_limit_up": reg.get("max_consecutive_limit_up"),
|
|
461
|
+
"prev_limit_up_avg_return_pct": reg.get("prev_limit_up_avg_return_pct"),
|
|
462
|
+
"total_amount_yi": reg.get("total_amount_yi"),
|
|
463
|
+
"return_distribution": reg.get("return_distribution"),
|
|
464
|
+
},
|
|
465
|
+
"cross_strategy_synthesis": {
|
|
466
|
+
"consensus_picks": (synthesis.get("consensus_picks") or [])[:5],
|
|
467
|
+
"sector_concentration": (synthesis.get("sector_concentration") or [])[:5],
|
|
468
|
+
"strategy_pattern_resonance": (synthesis.get("strategy_pattern_resonance") or [])[:5],
|
|
469
|
+
"risk_spotlight": (synthesis.get("risk_spotlight") or [])[:5],
|
|
470
|
+
},
|
|
471
|
+
"ai_highlights": (report.get("ai_highlights") or [])[:4],
|
|
472
|
+
"announcement_flagged": ((report.get("announcement_risks") or {}).get("flagged_items") or [])[:5],
|
|
473
|
+
"paired_ai_track_summary": [
|
|
474
|
+
{
|
|
475
|
+
"strategy": item.get("strategy"),
|
|
476
|
+
"common_days": item.get("common_days"),
|
|
477
|
+
"t5": (item.get("windows") or {}).get("5"),
|
|
478
|
+
}
|
|
479
|
+
for item in (track_comparison or [])
|
|
480
|
+
if item.get("market") == "cn"
|
|
481
|
+
][:4],
|
|
482
|
+
}
|
|
483
|
+
if compact_news:
|
|
484
|
+
compact_context["market_news"] = compact_news
|
|
485
|
+
payload_json = json.dumps(compact_context, ensure_ascii=False)
|
|
486
|
+
return (
|
|
487
|
+
"你是 AlphaSift A 股量化观测系统的盘后投研编辑。请仅基于下面提供的结构化观测数据,"
|
|
488
|
+
"用克制、客观、信息密度高的专业中文撰写盘后简报。\n"
|
|
489
|
+
"严格约束:\n"
|
|
490
|
+
"1. 禁止编造任何数据中不存在的股票代码、价格、涨跌幅、公告或新闻内容、目标价;\n"
|
|
491
|
+
"2. 用中文策略名描述策略(使用 strategy_display_names),不输出系统内部英文代号;\n"
|
|
492
|
+
"3. 不给出任何买卖建议或收益承诺;\n"
|
|
493
|
+
"4. 仅返回纯 JSON 对象(不要输出思考过程或 Markdown 解释),包含字段:\n"
|
|
494
|
+
' {"headline": "不超过80字核心结论", '
|
|
495
|
+
'"regime_interpretation": "120-240字盘面宽度、情绪结构与市场快讯催化解读", '
|
|
496
|
+
'"consensus_and_ai_edge": "100-220字跨策略共识、行业集中与个股/AI观察解读", '
|
|
497
|
+
'"risk_warnings": ["风险提示1", "风险提示2"], '
|
|
498
|
+
'"watch_points": ["次日客观观察指标1", "次日客观观察指标2"]}\n\n'
|
|
499
|
+
f"结构化数据:\n{payload_json}\n"
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def generate_ai_daily_brief(
|
|
504
|
+
report: dict[str, Any],
|
|
505
|
+
*,
|
|
506
|
+
config: Config | None = None,
|
|
507
|
+
track_comparison: Sequence[dict[str, Any]] | None = None,
|
|
508
|
+
use_llm: str = "auto",
|
|
509
|
+
llm_caller: Callable[..., str] | None = None,
|
|
510
|
+
timeout_sec: float = 45.0,
|
|
511
|
+
) -> dict[str, Any]:
|
|
512
|
+
"""Generate structured AI daily brief with grounded deterministic fallback."""
|
|
513
|
+
mode = (use_llm or "auto").strip().lower()
|
|
514
|
+
if mode not in {"auto", "on", "off"}:
|
|
515
|
+
raise ValueError("use_llm must be 'auto', 'on', or 'off'")
|
|
516
|
+
|
|
517
|
+
if mode == "off":
|
|
518
|
+
return _build_rule_daily_brief(report, track_comparison=track_comparison, fallback_reason=None)
|
|
519
|
+
|
|
520
|
+
has_llm_cfg = bool(
|
|
521
|
+
config is not None
|
|
522
|
+
and (
|
|
523
|
+
config.has_usable_llm_config()
|
|
524
|
+
if hasattr(config, "has_usable_llm_config")
|
|
525
|
+
else (config.llm_api_key or config.llm_channels or config.llm_config_path)
|
|
526
|
+
)
|
|
527
|
+
)
|
|
528
|
+
if mode == "auto" and not has_llm_cfg and llm_caller is None:
|
|
529
|
+
return _build_rule_daily_brief(
|
|
530
|
+
report,
|
|
531
|
+
track_comparison=track_comparison,
|
|
532
|
+
fallback_reason="no_llm_configured",
|
|
533
|
+
)
|
|
534
|
+
if mode == "on" and not has_llm_cfg and llm_caller is None:
|
|
535
|
+
return _build_rule_daily_brief(
|
|
536
|
+
report,
|
|
537
|
+
track_comparison=track_comparison,
|
|
538
|
+
fallback_reason="llm_requested_but_not_configured",
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
synthesis = report.get("cross_strategy_synthesis") or build_cross_strategy_synthesis(report)
|
|
542
|
+
prompt = _build_brief_prompt(report, synthesis=synthesis, track_comparison=track_comparison)
|
|
543
|
+
model_name = config.llm_model if config is not None else "custom"
|
|
544
|
+
used_model = model_name
|
|
545
|
+
|
|
546
|
+
try:
|
|
547
|
+
if llm_caller is not None:
|
|
548
|
+
raw_text = llm_caller(prompt)
|
|
549
|
+
parsed = _parse_brief_json(raw_text)
|
|
550
|
+
else:
|
|
551
|
+
from alphasift.llm_client import DEFAULT_LLM_MAX_TOKENS
|
|
552
|
+
from alphasift.ranker import _call_llm_with_metadata
|
|
553
|
+
|
|
554
|
+
assert config is not None
|
|
555
|
+
brief_max_tokens = max(
|
|
556
|
+
1,
|
|
557
|
+
int(getattr(config, "llm_max_tokens", DEFAULT_LLM_MAX_TOKENS) or DEFAULT_LLM_MAX_TOKENS),
|
|
558
|
+
)
|
|
559
|
+
raw_text, used_model = _call_llm_with_metadata(
|
|
560
|
+
prompt,
|
|
561
|
+
api_key=config.llm_api_key,
|
|
562
|
+
model=config.llm_model,
|
|
563
|
+
base_url=config.llm_base_url,
|
|
564
|
+
fallback_models=config.llm_fallback_models,
|
|
565
|
+
temperature=0.2,
|
|
566
|
+
json_mode=True,
|
|
567
|
+
silent=True,
|
|
568
|
+
channels=config.llm_channels,
|
|
569
|
+
config_path=str(config.llm_config_path or ""),
|
|
570
|
+
timeout_sec=min(float(timeout_sec), float(config.llm_timeout_sec)),
|
|
571
|
+
max_tokens=brief_max_tokens,
|
|
572
|
+
reasoning_effort="low",
|
|
573
|
+
validator=_parse_brief_json,
|
|
574
|
+
)
|
|
575
|
+
parsed = _parse_brief_json(raw_text)
|
|
576
|
+
except Exception as exc: # noqa: BLE001
|
|
577
|
+
return _build_rule_daily_brief(
|
|
578
|
+
report,
|
|
579
|
+
track_comparison=track_comparison,
|
|
580
|
+
fallback_reason=f"llm_error:{type(exc).__name__}:{str(exc)[:120]}",
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
return {
|
|
584
|
+
"mode": "llm",
|
|
585
|
+
"model": used_model or model_name,
|
|
586
|
+
"headline": parsed["headline"],
|
|
587
|
+
"regime_interpretation": parsed["regime_interpretation"],
|
|
588
|
+
"consensus_and_ai_edge": parsed["consensus_and_ai_edge"],
|
|
589
|
+
"risk_warnings": parsed["risk_warnings"],
|
|
590
|
+
"watch_points": parsed["watch_points"],
|
|
591
|
+
"disclaimer": BRIEF_DISCLAIMER,
|
|
592
|
+
"fallback_reason": None,
|
|
593
|
+
}
|