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/risk.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Independent risk overlay for shortlisted picks."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from alphasift.models import Pick
|
|
7
|
+
|
|
8
|
+
_DEFAULT_RISK_PROFILE = {
|
|
9
|
+
"chase_change_pct": 8.0,
|
|
10
|
+
"chase_points": 4.0,
|
|
11
|
+
"breakdown_change_pct": -7.0,
|
|
12
|
+
"breakdown_points": 3.5,
|
|
13
|
+
"abnormal_volume_ratio": 6.0,
|
|
14
|
+
"abnormal_volume_ratio_points": 3.0,
|
|
15
|
+
"high_turnover_rate": 15.0,
|
|
16
|
+
"high_turnover_points": 3.0,
|
|
17
|
+
"invalid_pe_points": 3.0,
|
|
18
|
+
"high_pb": 8.0,
|
|
19
|
+
"high_pb_points": 2.0,
|
|
20
|
+
"weak_signal_score": 45.0,
|
|
21
|
+
"weak_signal_points": 2.5,
|
|
22
|
+
"macd_bearish_points": 2.0,
|
|
23
|
+
"rsi_overbought_points": 1.5,
|
|
24
|
+
"low_llm_confidence": 0.35,
|
|
25
|
+
"low_llm_confidence_points": 1.5,
|
|
26
|
+
"llm_risk_points": 1.2,
|
|
27
|
+
"llm_risk_points_cap": 4.0,
|
|
28
|
+
"deep_risk_points": 1.5,
|
|
29
|
+
"deep_risk_points_cap": 4.5,
|
|
30
|
+
"low_daily_quality_score": 70.0,
|
|
31
|
+
"low_daily_quality_points": 2.0,
|
|
32
|
+
"bad_daily_quality_flag_points": 3.0,
|
|
33
|
+
"stale_daily_cache_points": 2.5,
|
|
34
|
+
"fallback_daily_errors_points": 1.5,
|
|
35
|
+
"fetch_failed_daily_points": 6.0,
|
|
36
|
+
}
|
|
37
|
+
_DEFAULT_PORTFOLIO_BUCKETS = {
|
|
38
|
+
"金融": ("券商", "银行", "保险", "金融"),
|
|
39
|
+
"地产链": ("地产", "房地产", "建材", "家居", "物业"),
|
|
40
|
+
"新能源": ("新能源", "光伏", "锂电", "电池", "储能"),
|
|
41
|
+
"AI算力": ("AI算力", "算力", "数据中心", "服务器", "光模块"),
|
|
42
|
+
"消费": ("白酒", "食品", "家电", "零售", "消费"),
|
|
43
|
+
"医药": ("医药", "医疗", "创新药"),
|
|
44
|
+
"半导体": ("半导体", "芯片"),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def apply_risk_overlay(
|
|
49
|
+
picks: list[Pick],
|
|
50
|
+
*,
|
|
51
|
+
max_penalty: float = 12.0,
|
|
52
|
+
veto_high_risk: bool = False,
|
|
53
|
+
profile: dict[str, object] | None = None,
|
|
54
|
+
) -> tuple[list[Pick], list[str]]:
|
|
55
|
+
"""Attach risk flags and subtract a bounded penalty from final_score."""
|
|
56
|
+
if not picks:
|
|
57
|
+
return picks, []
|
|
58
|
+
|
|
59
|
+
max_penalty = max(float(max_penalty), 0.0)
|
|
60
|
+
degradation: list[str] = []
|
|
61
|
+
kept: list[Pick] = []
|
|
62
|
+
risk_profile = _risk_profile(profile)
|
|
63
|
+
|
|
64
|
+
for pick in picks:
|
|
65
|
+
points, flags = assess_pick_risk(pick, profile=risk_profile)
|
|
66
|
+
penalty = min(points, max_penalty)
|
|
67
|
+
pick.risk_penalty = round(penalty, 4)
|
|
68
|
+
pick.risk_score = round(0.0 if max_penalty == 0 else min(points / max_penalty * 100, 100), 4)
|
|
69
|
+
pick.risk_level = _risk_level(points, max_penalty)
|
|
70
|
+
pick.risk_flags = _unique([*pick.risk_flags, *flags])
|
|
71
|
+
pick.final_score = round(float(pick.final_score) - penalty, 4)
|
|
72
|
+
pick.excluded_by_risk = veto_high_risk and pick.risk_level == "high"
|
|
73
|
+
if pick.excluded_by_risk:
|
|
74
|
+
degradation.append(f"Risk veto excluded {pick.code}: {', '.join(pick.risk_flags)}")
|
|
75
|
+
continue
|
|
76
|
+
kept.append(pick)
|
|
77
|
+
|
|
78
|
+
kept.sort(key=lambda item: item.final_score, reverse=True)
|
|
79
|
+
for i, pick in enumerate(kept, start=1):
|
|
80
|
+
pick.rank = i
|
|
81
|
+
return kept, degradation
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
PORTFOLIO_DIVERSITY_SKIPPED_NOTE = (
|
|
85
|
+
"Portfolio diversity skipped: no candidate has an industry or LLM sector label"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def apply_portfolio_overlay(
|
|
90
|
+
picks: list[Pick],
|
|
91
|
+
*,
|
|
92
|
+
max_same_sector: int = 1,
|
|
93
|
+
concentration_penalty: float = 4.0,
|
|
94
|
+
profile: dict[str, object] | None = None,
|
|
95
|
+
) -> tuple[list[Pick], list[str]]:
|
|
96
|
+
"""Penalize repeated sectors so Top N is not only one crowded trade.
|
|
97
|
+
|
|
98
|
+
``portfolio_profile.mode`` selects how strict this is:
|
|
99
|
+
|
|
100
|
+
- ``soft`` (default): bounded score penalties; a large score gap can still
|
|
101
|
+
leave several picks from one bucket at the top.
|
|
102
|
+
- ``hard_cap``: after penalties, picks beyond ``max_same_bucket`` per bucket
|
|
103
|
+
move behind every within-cap pick, so they only reach Top N when there
|
|
104
|
+
are not enough alternatives. Unlabelled picks are not capped.
|
|
105
|
+
"""
|
|
106
|
+
if not picks:
|
|
107
|
+
return picks, []
|
|
108
|
+
|
|
109
|
+
portfolio_profile = profile or {}
|
|
110
|
+
max_same_sector = max(int(portfolio_profile.get("max_same_bucket", max_same_sector)), 1)
|
|
111
|
+
penalty_step = max(float(portfolio_profile.get("concentration_penalty", concentration_penalty)), 0.0)
|
|
112
|
+
hard_cap = str(portfolio_profile.get("mode", "soft")).strip().lower() == "hard_cap"
|
|
113
|
+
if penalty_step == 0 and not hard_cap:
|
|
114
|
+
return picks, []
|
|
115
|
+
|
|
116
|
+
ordered = sorted(picks, key=lambda item: item.final_score, reverse=True)
|
|
117
|
+
if not any(_canonical_sector(_pick_sector(pick)) for pick in ordered):
|
|
118
|
+
return ordered, [PORTFOLIO_DIVERSITY_SKIPPED_NOTE]
|
|
119
|
+
|
|
120
|
+
bucket_counts: dict[str, int] = {}
|
|
121
|
+
bucket_penalties: dict[str, list[tuple[str, str, float]]] = {}
|
|
122
|
+
for pick in ordered:
|
|
123
|
+
sector, bucket = _pick_bucket(pick, buckets=portfolio_profile.get("buckets"))
|
|
124
|
+
if not sector:
|
|
125
|
+
continue
|
|
126
|
+
bucket_counts[bucket] = bucket_counts.get(bucket, 0) + 1
|
|
127
|
+
excess = bucket_counts[bucket] - max_same_sector
|
|
128
|
+
if excess <= 0:
|
|
129
|
+
continue
|
|
130
|
+
|
|
131
|
+
penalty = min(penalty_step * excess, penalty_step * 3)
|
|
132
|
+
flag = f"portfolio_sector_concentration:{bucket}"
|
|
133
|
+
pick.portfolio_penalty = round(float(pick.portfolio_penalty) + penalty, 4)
|
|
134
|
+
pick.portfolio_flags = _unique([*pick.portfolio_flags, flag])
|
|
135
|
+
pick.risk_flags = _unique([*pick.risk_flags, flag])
|
|
136
|
+
pick.final_score = round(float(pick.final_score) - penalty, 4)
|
|
137
|
+
bucket_penalties.setdefault(bucket, []).append((pick.code, sector, penalty))
|
|
138
|
+
|
|
139
|
+
ordered.sort(key=lambda item: item.final_score, reverse=True)
|
|
140
|
+
notes = [
|
|
141
|
+
(
|
|
142
|
+
f"Portfolio concentration bucket={bucket}: "
|
|
143
|
+
f"penalized={len(items)}, "
|
|
144
|
+
f"codes={_format_penalty_codes(items)}"
|
|
145
|
+
)
|
|
146
|
+
for bucket, items in bucket_penalties.items()
|
|
147
|
+
]
|
|
148
|
+
if hard_cap:
|
|
149
|
+
ordered, cap_notes = _apply_bucket_hard_cap(
|
|
150
|
+
ordered,
|
|
151
|
+
max_same_bucket=max_same_sector,
|
|
152
|
+
buckets=portfolio_profile.get("buckets"),
|
|
153
|
+
)
|
|
154
|
+
notes.extend(cap_notes)
|
|
155
|
+
for i, pick in enumerate(ordered, start=1):
|
|
156
|
+
pick.rank = i
|
|
157
|
+
return ordered, notes
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _apply_bucket_hard_cap(
|
|
161
|
+
ordered: list[Pick],
|
|
162
|
+
*,
|
|
163
|
+
max_same_bucket: int,
|
|
164
|
+
buckets: object = None,
|
|
165
|
+
) -> tuple[list[Pick], list[str]]:
|
|
166
|
+
within: list[Pick] = []
|
|
167
|
+
overflow: list[Pick] = []
|
|
168
|
+
counts: dict[str, int] = {}
|
|
169
|
+
deferred: dict[str, list[str]] = {}
|
|
170
|
+
for pick in ordered:
|
|
171
|
+
sector, bucket = _pick_bucket(pick, buckets=buckets)
|
|
172
|
+
if not sector:
|
|
173
|
+
within.append(pick)
|
|
174
|
+
continue
|
|
175
|
+
counts[bucket] = counts.get(bucket, 0) + 1
|
|
176
|
+
if counts[bucket] <= max_same_bucket:
|
|
177
|
+
within.append(pick)
|
|
178
|
+
continue
|
|
179
|
+
flag = f"portfolio_sector_cap:{bucket}"
|
|
180
|
+
pick.portfolio_flags = _unique([*pick.portfolio_flags, flag])
|
|
181
|
+
overflow.append(pick)
|
|
182
|
+
deferred.setdefault(bucket, []).append(pick.code)
|
|
183
|
+
notes = [
|
|
184
|
+
f"Portfolio hard cap bucket={bucket}: max={max_same_bucket}, deferred={','.join(codes)}"
|
|
185
|
+
for bucket, codes in deferred.items()
|
|
186
|
+
]
|
|
187
|
+
return within + overflow, notes
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def assess_pick_risk(
|
|
191
|
+
pick: Pick,
|
|
192
|
+
*,
|
|
193
|
+
profile: dict[str, float] | None = None,
|
|
194
|
+
) -> tuple[float, list[str]]:
|
|
195
|
+
"""Return risk points and human-readable flags for one pick."""
|
|
196
|
+
profile = _risk_profile(profile)
|
|
197
|
+
points = 0.0
|
|
198
|
+
flags: list[str] = []
|
|
199
|
+
|
|
200
|
+
if pick.change_pct >= profile["chase_change_pct"]:
|
|
201
|
+
points += profile["chase_points"]
|
|
202
|
+
flags.append("single_day_chase_risk")
|
|
203
|
+
elif pick.change_pct <= profile["breakdown_change_pct"]:
|
|
204
|
+
points += profile["breakdown_points"]
|
|
205
|
+
flags.append("single_day_breakdown_risk")
|
|
206
|
+
|
|
207
|
+
if pick.volume_ratio is not None and pick.volume_ratio >= profile["abnormal_volume_ratio"]:
|
|
208
|
+
points += profile["abnormal_volume_ratio_points"]
|
|
209
|
+
flags.append("abnormal_volume_ratio")
|
|
210
|
+
if pick.turnover_rate is not None and pick.turnover_rate >= profile["high_turnover_rate"]:
|
|
211
|
+
points += profile["high_turnover_points"]
|
|
212
|
+
flags.append("high_turnover")
|
|
213
|
+
if pick.pe_ratio is not None and pick.pe_ratio <= 0:
|
|
214
|
+
points += profile["invalid_pe_points"]
|
|
215
|
+
flags.append("negative_or_invalid_pe")
|
|
216
|
+
if pick.pb_ratio is not None and pick.pb_ratio >= profile["high_pb"]:
|
|
217
|
+
points += profile["high_pb_points"]
|
|
218
|
+
flags.append("high_pb")
|
|
219
|
+
if pick.signal_score is not None and pick.signal_score < profile["weak_signal_score"]:
|
|
220
|
+
points += profile["weak_signal_points"]
|
|
221
|
+
flags.append("weak_daily_signal")
|
|
222
|
+
if pick.macd_status == "bearish":
|
|
223
|
+
points += profile["macd_bearish_points"]
|
|
224
|
+
flags.append("macd_bearish")
|
|
225
|
+
if pick.rsi_status == "overbought":
|
|
226
|
+
points += profile["rsi_overbought_points"]
|
|
227
|
+
flags.append("rsi_overbought")
|
|
228
|
+
if pick.llm_confidence is not None and pick.llm_confidence < profile["low_llm_confidence"]:
|
|
229
|
+
points += profile["low_llm_confidence_points"]
|
|
230
|
+
flags.append("low_llm_confidence")
|
|
231
|
+
|
|
232
|
+
daily_points, daily_flags = _assess_daily_data_risk(pick, profile)
|
|
233
|
+
points += daily_points
|
|
234
|
+
flags.extend(daily_flags)
|
|
235
|
+
|
|
236
|
+
llm_risks = [risk for risk in pick.llm_risks if risk]
|
|
237
|
+
if llm_risks:
|
|
238
|
+
points += min(len(llm_risks) * profile["llm_risk_points"], profile["llm_risk_points_cap"])
|
|
239
|
+
flags.extend(llm_risks)
|
|
240
|
+
|
|
241
|
+
if pick.deep_analysis_risk_flags:
|
|
242
|
+
points += min(
|
|
243
|
+
len(pick.deep_analysis_risk_flags) * profile["deep_risk_points"],
|
|
244
|
+
profile["deep_risk_points_cap"],
|
|
245
|
+
)
|
|
246
|
+
flags.extend(pick.deep_analysis_risk_flags)
|
|
247
|
+
|
|
248
|
+
return points, _unique(flags)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _assess_daily_data_risk(pick: Pick, profile: dict[str, float]) -> tuple[float, list[str]]:
|
|
252
|
+
"""Convert row-level daily-history quality metadata into risk points."""
|
|
253
|
+
points = 0.0
|
|
254
|
+
flags: list[str] = []
|
|
255
|
+
|
|
256
|
+
if pick.daily_quality_score is not None and pick.daily_quality_score < profile["low_daily_quality_score"]:
|
|
257
|
+
points += profile["low_daily_quality_points"]
|
|
258
|
+
flags.append("low_daily_quality")
|
|
259
|
+
|
|
260
|
+
quality_flags = _daily_quality_flag_set(pick.daily_quality_flags)
|
|
261
|
+
if "fetch_failed" in quality_flags:
|
|
262
|
+
points += profile["fetch_failed_daily_points"]
|
|
263
|
+
flags.append("daily_fetch_failed")
|
|
264
|
+
if "stale_cache" in quality_flags:
|
|
265
|
+
points += profile["stale_daily_cache_points"]
|
|
266
|
+
flags.append("daily_stale_cache")
|
|
267
|
+
if "fallback_errors" in quality_flags:
|
|
268
|
+
points += profile["fallback_daily_errors_points"]
|
|
269
|
+
flags.append("daily_source_fallback_errors")
|
|
270
|
+
|
|
271
|
+
severe_quality_flags = {"invalid_ohlc", "non_positive_price", "negative_volume"}
|
|
272
|
+
if quality_flags & severe_quality_flags:
|
|
273
|
+
points += profile["bad_daily_quality_flag_points"]
|
|
274
|
+
flags.append("bad_daily_quality_flags")
|
|
275
|
+
|
|
276
|
+
return points, flags
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _daily_quality_flag_set(value: str) -> set[str]:
|
|
280
|
+
text = str(value or "").strip()
|
|
281
|
+
if not text or text.lower() in {"nan", "none", "<na>"}:
|
|
282
|
+
return set()
|
|
283
|
+
normalized = text
|
|
284
|
+
for separator in (",", ",", "|", " "):
|
|
285
|
+
normalized = normalized.replace(separator, ";")
|
|
286
|
+
return {item.strip() for item in normalized.split(";") if item.strip()}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _risk_level(points: float, max_penalty: float) -> str:
|
|
290
|
+
if max_penalty <= 0:
|
|
291
|
+
return "low"
|
|
292
|
+
if points >= max_penalty * 0.66:
|
|
293
|
+
return "high"
|
|
294
|
+
if points >= max_penalty * 0.33:
|
|
295
|
+
return "medium"
|
|
296
|
+
return "low"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def summarize_portfolio_exposure(
|
|
300
|
+
selected_picks: list[Pick],
|
|
301
|
+
*,
|
|
302
|
+
candidate_pool: list[Pick] | None = None,
|
|
303
|
+
max_same_bucket: int = 1,
|
|
304
|
+
buckets: object = None,
|
|
305
|
+
replacement_limit: int = 5,
|
|
306
|
+
) -> tuple[dict[str, dict[str, object]], list[str], list[dict[str, object]]]:
|
|
307
|
+
"""Compute portfolio bucket concentration and non-overcrowded replacement candidates."""
|
|
308
|
+
total = len(selected_picks)
|
|
309
|
+
if total == 0:
|
|
310
|
+
return {}, [], []
|
|
311
|
+
|
|
312
|
+
limit = max(1, int(max_same_bucket))
|
|
313
|
+
bucket_picks: dict[str, list[Pick]] = {}
|
|
314
|
+
selected_codes = {p.code for p in selected_picks}
|
|
315
|
+
for pick in selected_picks:
|
|
316
|
+
_, bucket = _pick_bucket(pick, buckets=buckets)
|
|
317
|
+
bucket_picks.setdefault(bucket, []).append(pick)
|
|
318
|
+
|
|
319
|
+
exposure: dict[str, dict[str, object]] = {}
|
|
320
|
+
overconcentrated: list[str] = []
|
|
321
|
+
for bucket, group in sorted(bucket_picks.items(), key=lambda kv: (-len(kv[1]), kv[0])):
|
|
322
|
+
cnt = len(group)
|
|
323
|
+
is_over = bucket != "unclassified" and cnt > limit
|
|
324
|
+
exposure[bucket] = {
|
|
325
|
+
"count": cnt,
|
|
326
|
+
"share_pct": round(cnt / total * 100.0, 2),
|
|
327
|
+
"codes": [p.code for p in group],
|
|
328
|
+
"overconcentrated": is_over,
|
|
329
|
+
}
|
|
330
|
+
if is_over:
|
|
331
|
+
overconcentrated.append(bucket)
|
|
332
|
+
|
|
333
|
+
limit_count = max(0, int(replacement_limit))
|
|
334
|
+
replacements: list[dict[str, object]] = []
|
|
335
|
+
if limit_count > 0:
|
|
336
|
+
seen_codes = set(selected_codes)
|
|
337
|
+
active_buckets = set(bucket_picks.keys()) - {"unclassified"}
|
|
338
|
+
ordered_pool = sorted(
|
|
339
|
+
candidate_pool or [],
|
|
340
|
+
key=lambda p: (0 if _pick_bucket(p, buckets=buckets)[1] not in active_buckets else 1, -float(p.final_score), p.code),
|
|
341
|
+
)
|
|
342
|
+
for cand in ordered_pool:
|
|
343
|
+
if cand.code in seen_codes:
|
|
344
|
+
continue
|
|
345
|
+
seen_codes.add(cand.code)
|
|
346
|
+
c_sector, c_bucket = _pick_bucket(cand, buckets=buckets)
|
|
347
|
+
if c_bucket in overconcentrated or (
|
|
348
|
+
c_bucket != "unclassified" and len(bucket_picks.get(c_bucket, [])) >= limit
|
|
349
|
+
):
|
|
350
|
+
continue
|
|
351
|
+
replacements.append({
|
|
352
|
+
"code": cand.code,
|
|
353
|
+
"name": cand.name,
|
|
354
|
+
"bucket": c_bucket,
|
|
355
|
+
"sector": c_sector,
|
|
356
|
+
"final_score": round(float(cand.final_score), 4),
|
|
357
|
+
})
|
|
358
|
+
if len(replacements) >= limit_count:
|
|
359
|
+
break
|
|
360
|
+
|
|
361
|
+
return exposure, overconcentrated, replacements
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _canonical_sector(label: str) -> str:
|
|
365
|
+
cleaned = str(label or "").strip()[:40]
|
|
366
|
+
if not cleaned:
|
|
367
|
+
return ""
|
|
368
|
+
aliases = {
|
|
369
|
+
"券商": ("券商", "证券"),
|
|
370
|
+
"银行": ("银行",),
|
|
371
|
+
"保险": ("保险",),
|
|
372
|
+
"地产": ("地产", "房地产"),
|
|
373
|
+
"医药": ("医药", "医疗", "创新药"),
|
|
374
|
+
"白酒": ("白酒", "酿酒"),
|
|
375
|
+
"半导体": ("半导体", "芯片"),
|
|
376
|
+
"AI算力": ("AI算力", "算力", "数据中心"),
|
|
377
|
+
"新能源": ("新能源", "光伏", "锂电", "电池"),
|
|
378
|
+
}
|
|
379
|
+
for canonical, needles in aliases.items():
|
|
380
|
+
if any(needle in cleaned for needle in needles):
|
|
381
|
+
return canonical
|
|
382
|
+
return cleaned
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _pick_sector(pick: Pick) -> str:
|
|
386
|
+
return pick.llm_sector or pick.industry
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _pick_bucket(pick: Pick, *, buckets: object = None) -> tuple[str, str]:
|
|
390
|
+
sector = _canonical_sector(_pick_sector(pick))
|
|
391
|
+
if not sector:
|
|
392
|
+
return "", "unclassified"
|
|
393
|
+
return sector, _portfolio_bucket(sector, pick.llm_theme, buckets=buckets)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _risk_profile(profile: dict[str, object] | None) -> dict[str, float]:
|
|
397
|
+
result = dict(_DEFAULT_RISK_PROFILE)
|
|
398
|
+
for key, value in (profile or {}).items():
|
|
399
|
+
if key in result:
|
|
400
|
+
result[key] = float(value)
|
|
401
|
+
return result
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _portfolio_bucket(
|
|
405
|
+
sector: str,
|
|
406
|
+
theme: str = "",
|
|
407
|
+
*,
|
|
408
|
+
buckets: object = None,
|
|
409
|
+
) -> str:
|
|
410
|
+
text = f"{sector} {theme or ''}"
|
|
411
|
+
bucket_map = _portfolio_buckets(buckets)
|
|
412
|
+
for bucket, needles in bucket_map.items():
|
|
413
|
+
if any(needle in text for needle in needles):
|
|
414
|
+
return bucket
|
|
415
|
+
return sector
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _portfolio_buckets(custom_buckets: object = None) -> dict[str, tuple[str, ...]]:
|
|
419
|
+
bucket_map = {key: tuple(value) for key, value in _DEFAULT_PORTFOLIO_BUCKETS.items()}
|
|
420
|
+
if not isinstance(custom_buckets, dict):
|
|
421
|
+
return bucket_map
|
|
422
|
+
for bucket, needles in custom_buckets.items():
|
|
423
|
+
if isinstance(needles, str):
|
|
424
|
+
items = [needles]
|
|
425
|
+
elif isinstance(needles, list):
|
|
426
|
+
items = [str(item) for item in needles]
|
|
427
|
+
else:
|
|
428
|
+
continue
|
|
429
|
+
if items:
|
|
430
|
+
bucket_map[str(bucket)] = tuple(items)
|
|
431
|
+
return bucket_map
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _format_penalty_codes(items: list[tuple[str, str, float]], limit: int = 5) -> str:
|
|
435
|
+
shown = [
|
|
436
|
+
f"{code}:{sector}(-{penalty:.1f})"
|
|
437
|
+
for code, sector, penalty in items[:limit]
|
|
438
|
+
]
|
|
439
|
+
if len(items) > limit:
|
|
440
|
+
shown.append(f"+{len(items) - limit} more")
|
|
441
|
+
return ",".join(shown)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _unique(items: list[str]) -> list[str]:
|
|
445
|
+
seen = set()
|
|
446
|
+
result = []
|
|
447
|
+
for item in items:
|
|
448
|
+
key = str(item).strip()
|
|
449
|
+
if key and key not in seen:
|
|
450
|
+
seen.add(key)
|
|
451
|
+
result.append(key)
|
|
452
|
+
return result
|
alphasift/run_history.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Saved-run history summaries for UI and agent integrations."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from alphasift.store import list_saved_runs
|
|
10
|
+
from alphasift.timeutil import MIN_TIMESTAMP, parse_timestamp
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_strategy_run_summary(
|
|
14
|
+
*,
|
|
15
|
+
data_dir: Path,
|
|
16
|
+
limit: int = 100,
|
|
17
|
+
strategy: str | None = None,
|
|
18
|
+
) -> dict[str, object]:
|
|
19
|
+
"""Summarize saved runs by strategy without loading full run payloads."""
|
|
20
|
+
runs = list_saved_runs(data_dir=data_dir, limit=limit, strategy=strategy)
|
|
21
|
+
strategy_rows = [_strategy_summary(item) for item in _group_runs_by_strategy(runs).values()]
|
|
22
|
+
strategy_rows.sort(
|
|
23
|
+
key=lambda item: (
|
|
24
|
+
_parse_created_at(str(item.get("latest_created_at") or "")),
|
|
25
|
+
str(item.get("strategy") or ""),
|
|
26
|
+
),
|
|
27
|
+
reverse=True,
|
|
28
|
+
)
|
|
29
|
+
return {
|
|
30
|
+
"schema_version": 1,
|
|
31
|
+
"run_count": len(runs),
|
|
32
|
+
"strategy_count": len(strategy_rows),
|
|
33
|
+
"limit": int(limit),
|
|
34
|
+
"strategy_filter": strategy or "",
|
|
35
|
+
"summary": _run_history_summary(runs),
|
|
36
|
+
"strategies": strategy_rows,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _group_runs_by_strategy(runs: list[dict[str, object]]) -> dict[str, list[dict[str, object]]]:
|
|
41
|
+
groups: dict[str, list[dict[str, object]]] = {}
|
|
42
|
+
for item in runs:
|
|
43
|
+
strategy_name = str(item.get("strategy") or "unknown")
|
|
44
|
+
groups.setdefault(strategy_name, []).append(item)
|
|
45
|
+
return groups
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _strategy_summary(runs: list[dict[str, object]]) -> dict[str, object]:
|
|
49
|
+
ordered = sorted(runs, key=_run_sort_key, reverse=True)
|
|
50
|
+
latest = ordered[0] if ordered else {}
|
|
51
|
+
llm_values = [
|
|
52
|
+
float(item["llm_coverage"])
|
|
53
|
+
for item in ordered
|
|
54
|
+
if isinstance(item.get("llm_coverage"), (int, float))
|
|
55
|
+
]
|
|
56
|
+
return {
|
|
57
|
+
"strategy": str(latest.get("strategy") or "unknown"),
|
|
58
|
+
"strategy_category": str(latest.get("strategy_category") or ""),
|
|
59
|
+
"run_count": len(ordered),
|
|
60
|
+
"latest_run_id": str(latest.get("run_id") or ""),
|
|
61
|
+
"latest_created_at": str(latest.get("created_at") or ""),
|
|
62
|
+
"latest_report_path": str(latest.get("report_path") or ""),
|
|
63
|
+
"latest_snapshot_source": str(latest.get("snapshot_source") or ""),
|
|
64
|
+
"total_picks": sum(_int_value(item.get("picks")) for item in ordered),
|
|
65
|
+
"average_picks": _average(_int_value(item.get("picks")) for item in ordered),
|
|
66
|
+
"snapshot_sources": _unique_values(item.get("snapshot_source") for item in ordered),
|
|
67
|
+
"runs_with_source_errors": sum(1 for item in ordered if _int_value(item.get("source_error_count")) > 0),
|
|
68
|
+
"source_error_count": sum(_int_value(item.get("source_error_count")) for item in ordered),
|
|
69
|
+
"source_error_samples": _sample_values(ordered, "source_errors"),
|
|
70
|
+
"runs_with_degradation": sum(1 for item in ordered if _int_value(item.get("degradation_count")) > 0),
|
|
71
|
+
"degradation_count": sum(_int_value(item.get("degradation_count")) for item in ordered),
|
|
72
|
+
"degradation_samples": _sample_values(ordered, "degradation"),
|
|
73
|
+
"llm_ranked_runs": sum(1 for item in ordered if bool(item.get("llm_ranked"))),
|
|
74
|
+
"average_llm_coverage": _average(llm_values),
|
|
75
|
+
"daily_enriched_runs": sum(1 for item in ordered if bool(item.get("daily_enriched"))),
|
|
76
|
+
"daily_enrich_count": sum(_int_value(item.get("daily_enrich_count")) for item in ordered),
|
|
77
|
+
"post_analyzers": _unique_post_analyzers(ordered),
|
|
78
|
+
"recent_runs": [_compact_run(item) for item in ordered[:5]],
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _run_history_summary(runs: list[dict[str, object]]) -> dict[str, object]:
|
|
83
|
+
ordered = sorted(runs, key=_run_sort_key, reverse=True)
|
|
84
|
+
return {
|
|
85
|
+
"runs_with_source_errors": sum(1 for item in runs if _int_value(item.get("source_error_count")) > 0),
|
|
86
|
+
"source_error_samples": _sample_values(ordered, "source_errors"),
|
|
87
|
+
"runs_with_degradation": sum(1 for item in runs if _int_value(item.get("degradation_count")) > 0),
|
|
88
|
+
"degradation_samples": _sample_values(ordered, "degradation"),
|
|
89
|
+
"llm_ranked_runs": sum(1 for item in runs if bool(item.get("llm_ranked"))),
|
|
90
|
+
"daily_enriched_runs": sum(1 for item in runs if bool(item.get("daily_enriched"))),
|
|
91
|
+
"total_picks": sum(_int_value(item.get("picks")) for item in runs),
|
|
92
|
+
"latest_run": _compact_run(ordered[0]) if ordered else {},
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _compact_run(item: dict[str, object]) -> dict[str, object]:
|
|
97
|
+
return {
|
|
98
|
+
"run_id": str(item.get("run_id") or ""),
|
|
99
|
+
"strategy": str(item.get("strategy") or ""),
|
|
100
|
+
"created_at": str(item.get("created_at") or ""),
|
|
101
|
+
"picks": _int_value(item.get("picks")),
|
|
102
|
+
"snapshot_source": str(item.get("snapshot_source") or ""),
|
|
103
|
+
"source_error_count": _int_value(item.get("source_error_count")),
|
|
104
|
+
"source_errors": _sample_list(item.get("source_errors"), limit=3),
|
|
105
|
+
"degradation_count": _int_value(item.get("degradation_count")),
|
|
106
|
+
"degradation": _sample_list(item.get("degradation"), limit=3),
|
|
107
|
+
"report_path": str(item.get("report_path") or ""),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _unique_post_analyzers(runs: list[dict[str, object]]) -> list[str]:
|
|
112
|
+
values: list[str] = []
|
|
113
|
+
for item in runs:
|
|
114
|
+
raw = item.get("post_analyzers") or []
|
|
115
|
+
if isinstance(raw, list):
|
|
116
|
+
values.extend(str(value) for value in raw if str(value))
|
|
117
|
+
return list(dict.fromkeys(values))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _unique_values(values) -> list[str]:
|
|
121
|
+
return list(dict.fromkeys(str(value) for value in values if str(value or "")))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _sample_values(
|
|
125
|
+
runs: list[dict[str, object]],
|
|
126
|
+
field: str,
|
|
127
|
+
*,
|
|
128
|
+
limit: int = 5,
|
|
129
|
+
) -> list[str]:
|
|
130
|
+
values: list[str] = []
|
|
131
|
+
for item in runs:
|
|
132
|
+
values.extend(_sample_list(item.get(field), limit=limit))
|
|
133
|
+
return list(dict.fromkeys(values))[:limit]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _sample_list(value: object, *, limit: int) -> list[str]:
|
|
137
|
+
if isinstance(value, list):
|
|
138
|
+
return [str(item) for item in value if str(item)][:limit]
|
|
139
|
+
if isinstance(value, str) and value:
|
|
140
|
+
return [item.strip() for item in value.split(",") if item.strip()][:limit]
|
|
141
|
+
return []
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _average(values) -> float | None:
|
|
145
|
+
items = [float(value) for value in values]
|
|
146
|
+
if not items:
|
|
147
|
+
return None
|
|
148
|
+
return round(sum(items) / len(items), 4)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _int_value(value: object) -> int:
|
|
152
|
+
try:
|
|
153
|
+
return int(value or 0)
|
|
154
|
+
except (TypeError, ValueError):
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _run_sort_key(item: dict[str, object]) -> tuple[datetime, str]:
|
|
159
|
+
return (_parse_created_at(str(item.get("created_at") or "")), str(item.get("run_id") or ""))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _parse_created_at(value: str) -> datetime:
|
|
163
|
+
# Aware for both old naive and new offset timestamps, so they sort together.
|
|
164
|
+
return parse_timestamp(value) or MIN_TIMESTAMP
|