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/scorer.py ADDED
@@ -0,0 +1,597 @@
1
+ # -*- coding: utf-8 -*-
2
+ """screen_score calculation."""
3
+
4
+ import math
5
+ import re
6
+
7
+ import pandas as pd
8
+
9
+ from alphasift.models import ScreeningConfig
10
+
11
+ _FACTOR_COLUMNS = {
12
+ "value": "factor_value_score",
13
+ "liquidity": "factor_liquidity_score",
14
+ "momentum": "factor_momentum_score",
15
+ "reversal": "factor_reversal_score",
16
+ "activity": "factor_activity_score",
17
+ "stability": "factor_stability_score",
18
+ "size": "factor_size_score",
19
+ "theme_heat": "factor_theme_heat_score",
20
+ "topic_alignment": "factor_topic_alignment_score",
21
+ }
22
+ _RANK_BLENDABLE_FACTORS = frozenset({"momentum", "reversal", "activity", "stability"})
23
+ _DEFAULT_SCORING_PROFILE = {
24
+ "momentum_base": 60.0,
25
+ "momentum_intraday_slope": 5.0,
26
+ "momentum_chase_start_pct": 5.0,
27
+ "momentum_chase_penalty_slope": 10.0,
28
+ "momentum_downside_start_pct": -2.0,
29
+ "momentum_downside_penalty_slope": 3.0,
30
+ "momentum_60d_base": 55.0,
31
+ "momentum_60d_slope": 0.9,
32
+ "momentum_60d_overheat_pct": 45.0,
33
+ "momentum_60d_overheat_penalty_slope": 0.8,
34
+ "momentum_60d_breakdown_pct": -20.0,
35
+ "momentum_60d_breakdown_penalty_slope": 0.7,
36
+ "macd_bullish_bonus": 6.0,
37
+ "macd_bearish_penalty": 8.0,
38
+ "reversal_ideal_change_pct": -3.0,
39
+ "reversal_distance_penalty_slope": 13.0,
40
+ "reversal_collapse_start_pct": -8.0,
41
+ "reversal_collapse_penalty_slope": 10.0,
42
+ "reversal_chase_start_pct": 1.0,
43
+ "reversal_chase_penalty_slope": 8.0,
44
+ "rsi_oversold_bonus": 10.0,
45
+ "rsi_overbought_penalty": 14.0,
46
+ "activity_ideal_volume_ratio": 2.0,
47
+ "activity_volume_ratio_distance_slope": 15.0,
48
+ "activity_high_volume_ratio": 5.0,
49
+ "activity_high_volume_ratio_penalty_slope": 8.0,
50
+ "activity_ideal_turnover_rate": 4.0,
51
+ "activity_turnover_distance_slope": 8.0,
52
+ "activity_high_turnover_rate": 12.0,
53
+ "activity_high_turnover_penalty_slope": 5.0,
54
+ "stability_base": 78.0,
55
+ "stability_change_abs_penalty_slope": 3.0,
56
+ "stability_hot_change_pct": 7.0,
57
+ "stability_hot_change_penalty_slope": 5.0,
58
+ "stability_high_turnover_rate": 10.0,
59
+ "stability_high_turnover_penalty_slope": 2.0,
60
+ "stability_high_volume_ratio": 5.0,
61
+ "stability_high_volume_ratio_penalty_slope": 4.0,
62
+ "stability_invalid_pe_penalty": 18.0,
63
+ "stability_high_volatility_pct": 45.0,
64
+ "stability_high_volatility_penalty_slope": 0.45,
65
+ "stability_max_drawdown_floor_pct": -12.0,
66
+ "stability_drawdown_penalty_slope": 1.2,
67
+ "stability_high_atr_pct": 6.0,
68
+ "stability_high_atr_penalty_slope": 2.0,
69
+ "stability_low_daily_quality_score": 80.0,
70
+ "stability_low_daily_quality_penalty_slope": 0.35,
71
+ "stability_bad_daily_quality_flag_penalty": 8.0,
72
+ "theme_heat_unknown_score": 50.0,
73
+ "theme_heat_change_slope": 6.0,
74
+ "theme_heat_rank_bonus": 10.0,
75
+ "theme_heat_trend_min_observations": 2.0,
76
+ "theme_heat_trend_slope": 0.8,
77
+ "theme_heat_trend_bonus_cap": 10.0,
78
+ "theme_heat_cooling_penalty_slope": 0.8,
79
+ "theme_heat_cooling_penalty_cap": 12.0,
80
+ "theme_heat_persistence_min_score": 60.0,
81
+ "theme_heat_persistence_slope": 0.08,
82
+ "theme_heat_persistence_bonus_cap": 6.0,
83
+ "theme_heat_cooling_score_penalty_slope": 0.6,
84
+ "theme_heat_cooling_score_penalty_cap": 10.0,
85
+ "theme_heat_overheat_score": 88.0,
86
+ "theme_heat_overheat_penalty_slope": 0.5,
87
+ "topic_alignment_unknown_score": 50.0,
88
+ "topic_alignment_match_bonus": 25.0,
89
+ "topic_alignment_heat_weight": 0.25,
90
+ "topic_alignment_unmatched_penalty": 12.0,
91
+ "factor_rank_blend": 0.0,
92
+ }
93
+
94
+
95
+ def _effective_rank_blend(raw_blend: object, sample_size: int) -> float:
96
+ """Compute sample-size-tapered rank blend weight in [0.0, 1.0]."""
97
+ if raw_blend is None or isinstance(raw_blend, bool):
98
+ return 0.0
99
+ try:
100
+ val = float(raw_blend)
101
+ except (TypeError, ValueError):
102
+ return 0.0
103
+ if not math.isfinite(val):
104
+ return 0.0
105
+ clamped = min(max(val, 0.0), 1.0)
106
+ if clamped <= 0.0 or sample_size <= 5:
107
+ return 0.0
108
+ if sample_size >= 30:
109
+ return clamped
110
+ return clamped * ((sample_size - 5) / 25.0)
111
+
112
+
113
+ def _blend_factor_rank(series: pd.Series, effective_blend: float) -> pd.Series:
114
+ """Blend a raw continuous factor score with its cross-sectional rank percentile."""
115
+ if effective_blend <= 0.0:
116
+ return series
117
+ numeric = pd.to_numeric(series, errors="coerce")
118
+ if numeric.nunique(dropna=True) <= 1:
119
+ return series
120
+ ranked = _rank_score(numeric, lower_is_better=False, na_score=50.0)
121
+ return ((1.0 - effective_blend) * numeric.fillna(50.0) + effective_blend * ranked).clip(0, 100)
122
+
123
+
124
+ def compute_screen_scores(df: pd.DataFrame, config: ScreeningConfig) -> pd.DataFrame:
125
+ """Compute screen_score for each candidate row.
126
+
127
+ Adds a 'screen_score' column (0-100). Higher is better.
128
+ """
129
+ result = df.copy()
130
+ factors = _compute_factor_scores(result, config)
131
+ for name, series in factors.items():
132
+ result[_FACTOR_COLUMNS[name]] = series.round(4)
133
+
134
+ profile = _scoring_profile(config)
135
+ effective_blend = _effective_rank_blend(profile.get("factor_rank_blend", 0.0), len(result))
136
+ weights = _normalized_factor_weights(config)
137
+ result["screen_score"] = 0.0
138
+ for factor, weight in weights.items():
139
+ if factor in factors:
140
+ component = (
141
+ _blend_factor_rank(factors[factor], effective_blend)
142
+ if factor in _RANK_BLENDABLE_FACTORS and effective_blend > 0.0
143
+ else factors[factor]
144
+ )
145
+ result["screen_score"] += component * weight
146
+
147
+ result["screen_score"] = result["screen_score"].clip(0, 100)
148
+
149
+ return result
150
+
151
+
152
+ def factor_score_columns() -> dict[str, str]:
153
+ """Return the stable factor-score column mapping used in Pick output."""
154
+ return dict(_FACTOR_COLUMNS)
155
+
156
+
157
+ def _normalized_factor_weights(config: ScreeningConfig) -> dict[str, float]:
158
+ """Use explicit factor weights, or derive a sane legacy default from tech_weight."""
159
+ raw_weights = config.factor_weights or {
160
+ "value": (1 - config.tech_weight) * 0.50,
161
+ "liquidity": (1 - config.tech_weight) * 0.25,
162
+ "stability": (1 - config.tech_weight) * 0.25,
163
+ "momentum": config.tech_weight * 0.55,
164
+ "activity": config.tech_weight * 0.45,
165
+ }
166
+ weights = {
167
+ factor: max(float(weight), 0.0)
168
+ for factor, weight in raw_weights.items()
169
+ if factor in _FACTOR_COLUMNS
170
+ }
171
+ total = sum(weights.values())
172
+ if total <= 0:
173
+ return {"value": 0.4, "liquidity": 0.2, "momentum": 0.2, "activity": 0.2}
174
+ return {factor: weight / total for factor, weight in weights.items()}
175
+
176
+
177
+ def _compute_factor_scores(df: pd.DataFrame, config: ScreeningConfig | None = None) -> dict[str, pd.Series]:
178
+ config = config or ScreeningConfig()
179
+ profile = _scoring_profile(config)
180
+ return {
181
+ "value": _compute_value_score(df),
182
+ "liquidity": _compute_liquidity_score(df),
183
+ "momentum": _compute_momentum_score(df, profile),
184
+ "reversal": _compute_reversal_score(df, profile),
185
+ "activity": _compute_activity_score(df, profile),
186
+ "stability": _compute_stability_score(df, profile),
187
+ "size": _compute_size_score(df),
188
+ "theme_heat": _compute_theme_heat_score(df, profile),
189
+ "topic_alignment": _compute_topic_alignment_score(df, profile),
190
+ }
191
+
192
+
193
+ def _scoring_profile(config: ScreeningConfig) -> dict[str, float]:
194
+ profile = dict(_DEFAULT_SCORING_PROFILE)
195
+ for key, value in (config.scoring_profile or {}).items():
196
+ if key not in profile or value is None or isinstance(value, bool):
197
+ continue
198
+ try:
199
+ numeric = float(value)
200
+ except (TypeError, ValueError):
201
+ continue
202
+ if math.isfinite(numeric):
203
+ profile[key] = numeric
204
+ return profile
205
+
206
+
207
+ def _compute_snapshot_score(df: pd.DataFrame) -> pd.Series:
208
+ """Score based on snapshot fundamentals (0-100).
209
+
210
+ Components:
211
+ - PE ratio: lower is better (for value), normalized
212
+ - PB ratio: lower is better, normalized
213
+ - Turnover rate: moderate is best
214
+ - Amount (liquidity): higher is better, log-scaled
215
+ - Change pct: near zero or moderate positive preferred
216
+ """
217
+ factors = _compute_factor_scores(df)
218
+ return (
219
+ factors["value"] * 0.50
220
+ + factors["liquidity"] * 0.25
221
+ + factors["stability"] * 0.25
222
+ ).clip(0, 100)
223
+
224
+
225
+ def _compute_tech_score(df: pd.DataFrame) -> pd.Series:
226
+ """Score based on technical features (0-100).
227
+
228
+ Uses available columns like volume_ratio, change_pct patterns.
229
+ Full tech scoring (MA structure, MACD/RSI) needs daily data,
230
+ which is not in the snapshot — scored conservatively here.
231
+ """
232
+ factors = _compute_factor_scores(df)
233
+ return (factors["momentum"] * 0.55 + factors["activity"] * 0.45).clip(0, 100)
234
+
235
+
236
+ def _compute_value_score(df: pd.DataFrame) -> pd.Series:
237
+ score = pd.Series(50.0, index=df.index)
238
+
239
+ if "pe_ratio" in df.columns:
240
+ pe = pd.to_numeric(df["pe_ratio"], errors="coerce")
241
+ pe_score = _rank_score(pe.where((pe > 0) & (pe < 500)), lower_is_better=True, na_score=25)
242
+ score = score * 0.35 + pe_score * 0.65
243
+
244
+ if "pb_ratio" in df.columns:
245
+ pb = pd.to_numeric(df["pb_ratio"], errors="coerce")
246
+ pb_score = _rank_score(pb.where((pb > 0) & (pb < 50)), lower_is_better=True, na_score=25)
247
+ score = score * 0.55 + pb_score * 0.45
248
+
249
+ return score.clip(0, 100)
250
+
251
+
252
+ def _compute_liquidity_score(df: pd.DataFrame) -> pd.Series:
253
+ if "amount" not in df.columns:
254
+ return pd.Series(50.0, index=df.index)
255
+
256
+ import numpy as np
257
+
258
+ amount = pd.to_numeric(df["amount"], errors="coerce")
259
+ log_amount = np.log10(amount.clip(lower=1))
260
+ return _rank_score(log_amount.where(amount > 0), lower_is_better=False, na_score=20)
261
+
262
+
263
+ def _compute_momentum_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
264
+ score = pd.Series(50.0, index=df.index)
265
+
266
+ if "change_pct" in df.columns:
267
+ change = pd.to_numeric(df["change_pct"], errors="coerce").fillna(0)
268
+ # Prefer constructive positive moves, but penalize chase-risk near limit-up.
269
+ intraday_score = profile["momentum_base"] + change * profile["momentum_intraday_slope"]
270
+ intraday_score = intraday_score - (
271
+ change - profile["momentum_chase_start_pct"]
272
+ ).clip(lower=0) * profile["momentum_chase_penalty_slope"]
273
+ intraday_score = intraday_score - (
274
+ -change + profile["momentum_downside_start_pct"]
275
+ ).clip(lower=0) * profile["momentum_downside_penalty_slope"]
276
+ score = score * 0.35 + intraday_score.clip(5, 100) * 0.65
277
+
278
+ if "change_60d" in df.columns:
279
+ change_60d = pd.to_numeric(df["change_60d"], errors="coerce").fillna(0)
280
+ trend_score = profile["momentum_60d_base"] + change_60d * profile["momentum_60d_slope"]
281
+ trend_score = trend_score - (
282
+ change_60d - profile["momentum_60d_overheat_pct"]
283
+ ).clip(lower=0) * profile["momentum_60d_overheat_penalty_slope"]
284
+ trend_score = trend_score - (
285
+ -change_60d + profile["momentum_60d_breakdown_pct"]
286
+ ).clip(lower=0) * profile["momentum_60d_breakdown_penalty_slope"]
287
+ score = score * 0.60 + trend_score.clip(5, 100) * 0.40
288
+
289
+ if "signal_score" in df.columns:
290
+ signal = pd.to_numeric(df["signal_score"], errors="coerce").fillna(50)
291
+ score = score * 0.70 + signal.clip(0, 100) * 0.30
292
+
293
+ if "macd_status" in df.columns:
294
+ macd = df["macd_status"].astype(str)
295
+ score = score + macd.map({
296
+ "bullish": profile["macd_bullish_bonus"],
297
+ "bearish": -profile["macd_bearish_penalty"],
298
+ }).fillna(0)
299
+
300
+ return score.clip(5, 100)
301
+
302
+
303
+ def _compute_reversal_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
304
+ if "change_pct" not in df.columns:
305
+ return pd.Series(50.0, index=df.index)
306
+
307
+ change = pd.to_numeric(df["change_pct"], errors="coerce").fillna(0)
308
+ # Reversal setups prefer controlled weakness, not collapse.
309
+ score = 100 - (
310
+ change - profile["reversal_ideal_change_pct"]
311
+ ).abs() * profile["reversal_distance_penalty_slope"]
312
+ score = score - (
313
+ -change + profile["reversal_collapse_start_pct"]
314
+ ).clip(lower=0) * profile["reversal_collapse_penalty_slope"]
315
+ score = score - (
316
+ change - profile["reversal_chase_start_pct"]
317
+ ).clip(lower=0) * profile["reversal_chase_penalty_slope"]
318
+
319
+ if "rsi_status" in df.columns:
320
+ rsi = df["rsi_status"].astype(str)
321
+ score = score + rsi.map({
322
+ "oversold": profile["rsi_oversold_bonus"],
323
+ "overbought": -profile["rsi_overbought_penalty"],
324
+ }).fillna(0)
325
+ if "change_60d" in df.columns:
326
+ change_60d = pd.to_numeric(df["change_60d"], errors="coerce").fillna(0)
327
+ score = score - (change_60d - 35).clip(lower=0) * 0.5
328
+ score = score - (-change_60d - 35).clip(lower=0) * 0.8
329
+ return score.clip(5, 100)
330
+
331
+
332
+ def _compute_activity_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
333
+ score = pd.Series(50.0, index=df.index)
334
+
335
+ if "volume_ratio" in df.columns:
336
+ volume_ratio = pd.to_numeric(df["volume_ratio"], errors="coerce").fillna(1.0)
337
+ vr_score = 100 - (
338
+ volume_ratio - profile["activity_ideal_volume_ratio"]
339
+ ).abs() * profile["activity_volume_ratio_distance_slope"]
340
+ vr_score = vr_score - (
341
+ volume_ratio - profile["activity_high_volume_ratio"]
342
+ ).clip(lower=0) * profile["activity_high_volume_ratio_penalty_slope"]
343
+ score = score * 0.45 + vr_score.clip(5, 100) * 0.55
344
+
345
+ if "turnover_rate" in df.columns:
346
+ turnover = pd.to_numeric(df["turnover_rate"], errors="coerce").fillna(0)
347
+ turnover_score = 100 - (
348
+ turnover - profile["activity_ideal_turnover_rate"]
349
+ ).abs() * profile["activity_turnover_distance_slope"]
350
+ turnover_score = turnover_score - (
351
+ turnover - profile["activity_high_turnover_rate"]
352
+ ).clip(lower=0) * profile["activity_high_turnover_penalty_slope"]
353
+ turnover_score = turnover_score.where(turnover > 0, 40)
354
+ score = score * 0.55 + turnover_score.clip(5, 100) * 0.45
355
+
356
+ return score.clip(0, 100)
357
+
358
+
359
+ def _compute_stability_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
360
+ score = pd.Series(profile["stability_base"], index=df.index)
361
+
362
+ if "change_pct" in df.columns:
363
+ change = pd.to_numeric(df["change_pct"], errors="coerce").fillna(0)
364
+ score -= change.abs().clip(upper=10) * profile["stability_change_abs_penalty_slope"]
365
+ score -= (
366
+ change - profile["stability_hot_change_pct"]
367
+ ).clip(lower=0) * profile["stability_hot_change_penalty_slope"]
368
+
369
+ if "turnover_rate" in df.columns:
370
+ turnover = pd.to_numeric(df["turnover_rate"], errors="coerce").fillna(0)
371
+ score -= (
372
+ turnover - profile["stability_high_turnover_rate"]
373
+ ).clip(lower=0) * profile["stability_high_turnover_penalty_slope"]
374
+
375
+ if "volume_ratio" in df.columns:
376
+ volume_ratio = pd.to_numeric(df["volume_ratio"], errors="coerce").fillna(1)
377
+ score -= (
378
+ volume_ratio - profile["stability_high_volume_ratio"]
379
+ ).clip(lower=0) * profile["stability_high_volume_ratio_penalty_slope"]
380
+
381
+ if "pe_ratio" in df.columns:
382
+ pe = pd.to_numeric(df["pe_ratio"], errors="coerce")
383
+ score = score.where((pe.isna()) | (pe > 0), score - profile["stability_invalid_pe_penalty"])
384
+
385
+ if "signal_score" in df.columns:
386
+ signal = pd.to_numeric(df["signal_score"], errors="coerce").fillna(50)
387
+ score = score + (signal - 50) * 0.12
388
+
389
+ if "volatility_20d_pct" in df.columns:
390
+ volatility = pd.to_numeric(df["volatility_20d_pct"], errors="coerce")
391
+ score -= (
392
+ volatility - profile["stability_high_volatility_pct"]
393
+ ).clip(lower=0).fillna(0) * profile["stability_high_volatility_penalty_slope"]
394
+
395
+ if "max_drawdown_20d_pct" in df.columns:
396
+ drawdown = pd.to_numeric(df["max_drawdown_20d_pct"], errors="coerce")
397
+ score -= (
398
+ profile["stability_max_drawdown_floor_pct"] - drawdown
399
+ ).clip(lower=0).fillna(0) * profile["stability_drawdown_penalty_slope"]
400
+
401
+ if "atr_20_pct" in df.columns:
402
+ atr = pd.to_numeric(df["atr_20_pct"], errors="coerce")
403
+ score -= (
404
+ atr - profile["stability_high_atr_pct"]
405
+ ).clip(lower=0).fillna(0) * profile["stability_high_atr_penalty_slope"]
406
+
407
+ if "daily_quality_score" in df.columns:
408
+ quality = pd.to_numeric(df["daily_quality_score"], errors="coerce")
409
+ score -= (
410
+ profile["stability_low_daily_quality_score"] - quality
411
+ ).clip(lower=0).fillna(0) * profile["stability_low_daily_quality_penalty_slope"]
412
+
413
+ if "daily_quality_flags" in df.columns:
414
+ flags = df["daily_quality_flags"].fillna("").astype(str)
415
+ severe_flags = flags.str.contains("invalid_ohlc|non_positive_price|negative_volume|stale_cache")
416
+ score -= severe_flags.astype(float) * profile["stability_bad_daily_quality_flag_penalty"]
417
+
418
+ return score.clip(0, 100)
419
+
420
+
421
+ def _compute_size_score(df: pd.DataFrame) -> pd.Series:
422
+ if "total_mv" not in df.columns:
423
+ return pd.Series(50.0, index=df.index)
424
+
425
+ import numpy as np
426
+
427
+ mv = pd.to_numeric(df["total_mv"], errors="coerce")
428
+ log_mv = np.log10(mv.clip(lower=1))
429
+ return _rank_score(log_mv.where(mv > 0), lower_is_better=False, na_score=35)
430
+
431
+
432
+ def _compute_theme_heat_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
433
+ base = pd.Series(profile["theme_heat_unknown_score"], index=df.index)
434
+ if "board_heat_score" in df.columns:
435
+ score = pd.to_numeric(df["board_heat_score"], errors="coerce").fillna(base)
436
+ elif "industry_heat_score" in df.columns or "concept_heat_score" in df.columns:
437
+ industry = _numeric_column(df, "industry_heat_score")
438
+ concept = _numeric_column(df, "concept_heat_score")
439
+ score = pd.concat([industry, concept], axis=1).max(axis=1).fillna(base)
440
+ elif "industry_change_pct" in df.columns:
441
+ change = pd.to_numeric(df["industry_change_pct"], errors="coerce").fillna(0)
442
+ score = base + change * profile["theme_heat_change_slope"]
443
+ if "industry_rank" in df.columns:
444
+ rank = pd.to_numeric(df["industry_rank"], errors="coerce")
445
+ score += (
446
+ (profile["theme_heat_rank_bonus"] - rank.clip(lower=1, upper=10))
447
+ .clip(lower=0)
448
+ .fillna(0)
449
+ )
450
+ else:
451
+ return base.clip(0, 100)
452
+
453
+ if "board_heat_trend_score" in df.columns:
454
+ trend = pd.to_numeric(df["board_heat_trend_score"], errors="coerce").fillna(0)
455
+ if "board_heat_observations" in df.columns:
456
+ observations = pd.to_numeric(df["board_heat_observations"], errors="coerce").fillna(0)
457
+ else:
458
+ observations = pd.Series(profile["theme_heat_trend_min_observations"], index=df.index)
459
+ trend_is_reliable = observations >= profile["theme_heat_trend_min_observations"]
460
+ trend_bonus = (trend.clip(lower=0) * profile["theme_heat_trend_slope"]).clip(
461
+ upper=profile["theme_heat_trend_bonus_cap"]
462
+ )
463
+ cooling_penalty = ((-trend).clip(lower=0) * profile["theme_heat_cooling_penalty_slope"]).clip(
464
+ upper=profile["theme_heat_cooling_penalty_cap"]
465
+ )
466
+ score = score + (trend_bonus - cooling_penalty).where(trend_is_reliable, 0)
467
+
468
+ if "board_heat_persistence_score" in df.columns:
469
+ persistence = pd.to_numeric(df["board_heat_persistence_score"], errors="coerce").fillna(0)
470
+ persistence_bonus = (
471
+ (persistence - profile["theme_heat_persistence_min_score"]).clip(lower=0)
472
+ * profile["theme_heat_persistence_slope"]
473
+ ).clip(upper=profile["theme_heat_persistence_bonus_cap"])
474
+ score = score + persistence_bonus
475
+
476
+ if "board_heat_cooling_score" in df.columns:
477
+ cooling = pd.to_numeric(df["board_heat_cooling_score"], errors="coerce").fillna(0)
478
+ cooling_penalty = (cooling * profile["theme_heat_cooling_score_penalty_slope"]).clip(
479
+ upper=profile["theme_heat_cooling_score_penalty_cap"]
480
+ )
481
+ score = score - cooling_penalty
482
+
483
+ overheat = (score - profile["theme_heat_overheat_score"]).clip(lower=0)
484
+ score = score - overheat * profile["theme_heat_overheat_penalty_slope"]
485
+ return score.clip(0, 100)
486
+
487
+
488
+ def _compute_topic_alignment_score(df: pd.DataFrame, profile: dict[str, float]) -> pd.Series:
489
+ """Score whether industry/concept labels align with hotspot route summaries."""
490
+ base = pd.Series(profile["topic_alignment_unknown_score"], index=df.index)
491
+ if not {"industry", "concepts", "board_heat_summary"} & set(df.columns):
492
+ return base
493
+
494
+ scores = []
495
+ for _, row in df.iterrows():
496
+ candidate_topics = _topic_tokens(row.get("industry")) | _topic_tokens(row.get("concepts"))
497
+ route_topics = _topic_tokens(row.get("board_heat_summary"))
498
+ if not candidate_topics or not route_topics:
499
+ scores.append(float(profile["topic_alignment_unknown_score"]))
500
+ continue
501
+ overlap = candidate_topics & route_topics
502
+ score = float(profile["topic_alignment_unknown_score"])
503
+ if overlap:
504
+ score += float(profile["topic_alignment_match_bonus"])
505
+ heat = pd.to_numeric(row.get("board_heat_score"), errors="coerce")
506
+ if pd.notna(heat):
507
+ score += max(float(heat) - 50.0, 0.0) * float(profile["topic_alignment_heat_weight"])
508
+ else:
509
+ score -= float(profile["topic_alignment_unmatched_penalty"])
510
+ scores.append(score)
511
+ return pd.Series(scores, index=df.index).clip(0, 100)
512
+
513
+
514
+ def explain_topic_alignment(
515
+ industry: object,
516
+ concepts: object,
517
+ board_heat_summary: object,
518
+ ) -> dict[str, object]:
519
+ """Return deterministic topic alignment metadata for one candidate."""
520
+ ind_tokens = _topic_tokens(industry)
521
+ con_tokens = _topic_tokens(concepts)
522
+ cand_tokens = ind_tokens | con_tokens
523
+ route_tokens = _topic_tokens(board_heat_summary)
524
+ if not cand_tokens or not route_tokens:
525
+ return {
526
+ "status": "unassessed",
527
+ "role": "none" if cand_tokens else "",
528
+ "reason": "缺少题材或热点路线标签,无法评估对齐",
529
+ "matched_topics": [],
530
+ "unmatched_topics": sorted(route_tokens),
531
+ }
532
+ matched = sorted(cand_tokens & route_tokens)
533
+ unmatched = sorted(route_tokens - cand_tokens)
534
+ if matched:
535
+ direct_ind = bool(ind_tokens & route_tokens)
536
+ role = "direct_industry" if direct_ind else "concept_match"
537
+ reason = f"{'直接行业' if direct_ind else '概念题材'}命中热点路线: {', '.join(matched[:4])}"
538
+ return {
539
+ "status": "aligned",
540
+ "role": role,
541
+ "reason": reason,
542
+ "matched_topics": matched,
543
+ "unmatched_topics": unmatched,
544
+ }
545
+ return {
546
+ "status": "unmatched",
547
+ "role": "none",
548
+ "reason": f"候选标签({', '.join(sorted(cand_tokens)[:3])})未命中当前热点({', '.join(unmatched[:3])})",
549
+ "matched_topics": [],
550
+ "unmatched_topics": unmatched,
551
+ }
552
+
553
+
554
+ def _topic_tokens(value: object) -> set[str]:
555
+ if value is None:
556
+ return set()
557
+ try:
558
+ if bool(pd.isna(value)):
559
+ return set()
560
+ except (TypeError, ValueError):
561
+ pass
562
+ text = str(value).strip()
563
+ if not text or text.lower() in {"nan", "none", "<na>"}:
564
+ return set()
565
+ tokens = set()
566
+ for part in re.split(r"[|,,;;/\n、]+", text):
567
+ raw = " ".join(part.split()).strip()
568
+ if not raw:
569
+ continue
570
+ token = raw.split(":", 1)[0].strip()
571
+ if token and token.lower() not in {"rank", "nan", "none", "<na>"}:
572
+ tokens.add(token)
573
+ return tokens
574
+
575
+
576
+ def _numeric_column(df: pd.DataFrame, column: str) -> pd.Series:
577
+ if column not in df.columns:
578
+ return pd.Series(pd.NA, index=df.index)
579
+ return pd.to_numeric(df[column], errors="coerce")
580
+
581
+
582
+ def _rank_score(
583
+ series: pd.Series,
584
+ *,
585
+ lower_is_better: bool,
586
+ na_score: float = 50.0,
587
+ ) -> pd.Series:
588
+ numeric = pd.to_numeric(series, errors="coerce")
589
+ if numeric.notna().sum() == 0:
590
+ return pd.Series(float(na_score), index=series.index)
591
+
592
+ ranks = numeric.rank(
593
+ ascending=not lower_is_better,
594
+ na_option="keep",
595
+ pct=True,
596
+ ) * 100
597
+ return ranks.fillna(float(na_score)).clip(0, 100)