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/filter.py ADDED
@@ -0,0 +1,517 @@
1
+ # -*- coding: utf-8 -*-
2
+ """L1 hard filter — apply strategy hard_filters to snapshot DataFrame."""
3
+
4
+ import logging
5
+ import math
6
+ from dataclasses import replace
7
+
8
+ import pandas as pd
9
+
10
+ from alphasift.models import HardFilterConfig
11
+
12
+ logger = logging.getLogger(__name__)
13
+ _DAILY_FILTER_DEFAULTS = {
14
+ "change_60d_min": None,
15
+ "change_60d_max": None,
16
+ "require_ma_bullish": False,
17
+ "require_price_above_ma20": False,
18
+ "signal_score_min": None,
19
+ "macd_status_whitelist": None,
20
+ "rsi_status_whitelist": None,
21
+ "breakout_20d_pct_min": None,
22
+ "breakout_20d_pct_max": None,
23
+ "range_20d_pct_max": None,
24
+ "volume_ratio_20d_min": None,
25
+ "volume_ratio_20d_max": None,
26
+ "body_pct_min": None,
27
+ "body_pct_max": None,
28
+ "pullback_to_ma20_pct_min": None,
29
+ "pullback_to_ma20_pct_max": None,
30
+ "consolidation_days_20d_min": None,
31
+ "consolidation_days_20d_max": None,
32
+ "volatility_20d_pct_min": None,
33
+ "volatility_20d_pct_max": None,
34
+ "max_drawdown_20d_pct_min": None,
35
+ "max_drawdown_20d_pct_max": None,
36
+ "atr_20_pct_min": None,
37
+ "atr_20_pct_max": None,
38
+ }
39
+
40
+
41
+ class SnapshotFieldMissingError(ValueError):
42
+ """Raised when a configured hard filter cannot be evaluated safely."""
43
+
44
+
45
+ def _not_st_mask(names: pd.Series) -> pd.Series:
46
+ """True for rows that are not A-share ST / delisting names.
47
+
48
+ Matches CJK ST/delisting names as well as explicit asterisked romanized ST
49
+ prefixes (e.g. ``*ST Alpha``, ``S*ST Beta``) or standalone ``ST``, while
50
+ preserving ordinary English names like ``ST Engineering``, ``COST``,
51
+ ``STERIS``, or ``FIRST SOLAR``.
52
+ """
53
+ text = names.astype("string").fillna("")
54
+ has_cjk = text.str.contains(r"[\u4e00-\u9fff]", regex=True)
55
+ cjk_st = has_cjk & text.str.contains(r"ST|退", regex=True)
56
+ ascii_st_prefix = text.str.strip().str.contains(
57
+ r"^(?:S?\*ST(?:\b|\s|[A-Za-z0-9_])|S?ST$)",
58
+ case=True,
59
+ regex=True,
60
+ )
61
+ return ~(cjk_st | ascii_st_prefix)
62
+
63
+
64
+ def apply_hard_filters(df: pd.DataFrame, filters: HardFilterConfig) -> pd.DataFrame:
65
+ """Filter snapshot DataFrame by hard conditions. Returns filtered copy."""
66
+ result = df.copy()
67
+ if result.empty:
68
+ return result
69
+
70
+ mask = pd.Series(True, index=result.index)
71
+
72
+ if filters.exclude_st:
73
+ name_col = _find_col(result, ["name", "股票名称", "名称"]) if mask.any() else None
74
+ if not name_col:
75
+ raise SnapshotFieldMissingError(
76
+ "Missing required snapshot column for exclude_st filter: name"
77
+ )
78
+ mask &= _not_st_mask(result[name_col])
79
+
80
+ # Numeric filters — each is optional
81
+ mask = _filter_min(result, mask, ["amount", "成交额"], filters.amount_min)
82
+ mask = _filter_min(result, mask, ["avg_amount_usd"], filters.avg_amount_usd_min)
83
+ mask = _filter_min(result, mask, ["price", "最新价", "现价"], filters.price_min)
84
+ mask = _filter_max(result, mask, ["price", "最新价", "现价"], filters.price_max)
85
+ mask = _filter_min(result, mask, ["total_mv", "总市值"], filters.market_cap_min)
86
+ mask = _filter_max(result, mask, ["total_mv", "总市值"], filters.market_cap_max)
87
+ mask = _filter_min(result, mask, ["pe_ratio", "市盈率"], filters.pe_ttm_min)
88
+ mask = _filter_max(result, mask, ["pe_ratio", "市盈率"], filters.pe_ttm_max)
89
+ mask = _filter_min(result, mask, ["pb_ratio", "市净率"], filters.pb_min)
90
+ mask = _filter_max(result, mask, ["pb_ratio", "市净率"], filters.pb_max)
91
+ mask = _filter_min(result, mask, ["volume_ratio", "量比"], filters.volume_ratio_min)
92
+ mask = _filter_min(result, mask, ["turnover_rate", "换手率"], filters.turnover_rate_min)
93
+ mask = _filter_min(result, mask, ["change_pct", "涨跌幅"], filters.change_pct_min)
94
+ mask = _filter_max(result, mask, ["change_pct", "涨跌幅"], filters.change_pct_max)
95
+
96
+ mask = _filter_min(result, mask, ["change_60d"], filters.change_60d_min)
97
+ mask = _filter_max(result, mask, ["change_60d"], filters.change_60d_max)
98
+ mask = _filter_bool_true(result, mask, "ma_bullish", filters.require_ma_bullish)
99
+ mask = _filter_bool_true(result, mask, "price_above_ma20", filters.require_price_above_ma20)
100
+ mask = _filter_min(result, mask, ["signal_score"], filters.signal_score_min)
101
+ mask = _filter_in(result, mask, "macd_status", filters.macd_status_whitelist)
102
+ mask = _filter_in(result, mask, "rsi_status", filters.rsi_status_whitelist)
103
+ mask = _filter_min(result, mask, ["breakout_20d_pct"], filters.breakout_20d_pct_min)
104
+ mask = _filter_max(result, mask, ["breakout_20d_pct"], filters.breakout_20d_pct_max)
105
+ mask = _filter_max(result, mask, ["range_20d_pct"], filters.range_20d_pct_max)
106
+ mask = _filter_min(result, mask, ["volume_ratio_20d"], filters.volume_ratio_20d_min)
107
+ mask = _filter_max(result, mask, ["volume_ratio_20d"], filters.volume_ratio_20d_max)
108
+ mask = _filter_min(result, mask, ["body_pct"], filters.body_pct_min)
109
+ mask = _filter_max(result, mask, ["body_pct"], filters.body_pct_max)
110
+ mask = _filter_min(result, mask, ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_min)
111
+ mask = _filter_max(result, mask, ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_max)
112
+ mask = _filter_min(result, mask, ["consolidation_days_20d"], filters.consolidation_days_20d_min)
113
+ mask = _filter_max(result, mask, ["consolidation_days_20d"], filters.consolidation_days_20d_max)
114
+ mask = _filter_min(result, mask, ["volatility_20d_pct"], filters.volatility_20d_pct_min)
115
+ mask = _filter_max(result, mask, ["volatility_20d_pct"], filters.volatility_20d_pct_max)
116
+ mask = _filter_min(result, mask, ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_min)
117
+ mask = _filter_max(result, mask, ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_max)
118
+ mask = _filter_min(result, mask, ["atr_20_pct"], filters.atr_20_pct_min)
119
+ mask = _filter_max(result, mask, ["atr_20_pct"], filters.atr_20_pct_max)
120
+
121
+ return result.loc[mask].copy()
122
+
123
+
124
+ def hard_filter_rejection_summary(
125
+ df: pd.DataFrame,
126
+ filters: HardFilterConfig,
127
+ *,
128
+ limit: int = 8,
129
+ ) -> list[str]:
130
+ """Return compact sequential hard-filter rejection counts."""
131
+ if df.empty or limit <= 0:
132
+ return []
133
+
134
+ mask = pd.Series(True, index=df.index)
135
+ diagnostics: list[str] = []
136
+
137
+ def record(label: str, next_mask: pd.Series) -> None:
138
+ nonlocal mask
139
+ before = int(mask.sum())
140
+ after = int(next_mask.sum())
141
+ removed = before - after
142
+ if removed > 0 and len(diagnostics) < limit:
143
+ diagnostics.append(f"{label} removed {removed} ({before}->{after})")
144
+ mask = next_mask
145
+
146
+ if filters.exclude_st:
147
+ name_col = _find_col(df, ["name", "股票名称", "名称"]) if mask.any() else None
148
+ if not name_col:
149
+ raise SnapshotFieldMissingError(
150
+ "Missing required snapshot column for exclude_st filter: name"
151
+ )
152
+ record("exclude_st", mask & _not_st_mask(df[name_col]))
153
+
154
+ def record_min(label: str, columns: list[str], value: float | None) -> None:
155
+ if value is not None:
156
+ record(label, _filter_min(df, mask, columns, value))
157
+
158
+ def record_max(label: str, columns: list[str], value: float | None) -> None:
159
+ if value is not None:
160
+ record(label, _filter_max(df, mask, columns, value))
161
+
162
+ record_min("amount_min", ["amount", "成交额"], filters.amount_min)
163
+ record_min("avg_amount_usd_min", ["avg_amount_usd"], filters.avg_amount_usd_min)
164
+ record_min("price_min", ["price", "最新价", "现价"], filters.price_min)
165
+ record_max("price_max", ["price", "最新价", "现价"], filters.price_max)
166
+ record_min("market_cap_min", ["total_mv", "总市值"], filters.market_cap_min)
167
+ record_max("market_cap_max", ["total_mv", "总市值"], filters.market_cap_max)
168
+ record_min("pe_ttm_min", ["pe_ratio", "市盈率"], filters.pe_ttm_min)
169
+ record_max("pe_ttm_max", ["pe_ratio", "市盈率"], filters.pe_ttm_max)
170
+ record_min("pb_min", ["pb_ratio", "市净率"], filters.pb_min)
171
+ record_max("pb_max", ["pb_ratio", "市净率"], filters.pb_max)
172
+ record_min("volume_ratio_min", ["volume_ratio", "量比"], filters.volume_ratio_min)
173
+ record_min("turnover_rate_min", ["turnover_rate", "换手率"], filters.turnover_rate_min)
174
+ record_min("change_pct_min", ["change_pct", "涨跌幅"], filters.change_pct_min)
175
+ record_max("change_pct_max", ["change_pct", "涨跌幅"], filters.change_pct_max)
176
+ record_min("change_60d_min", ["change_60d"], filters.change_60d_min)
177
+ record_max("change_60d_max", ["change_60d"], filters.change_60d_max)
178
+
179
+ if filters.require_ma_bullish:
180
+ record("require_ma_bullish", _filter_bool_true(df, mask, "ma_bullish", True))
181
+ if filters.require_price_above_ma20:
182
+ record("require_price_above_ma20", _filter_bool_true(df, mask, "price_above_ma20", True))
183
+
184
+ record_min("signal_score_min", ["signal_score"], filters.signal_score_min)
185
+ if filters.macd_status_whitelist:
186
+ record("macd_status_whitelist", _filter_in(df, mask, "macd_status", filters.macd_status_whitelist))
187
+ if filters.rsi_status_whitelist:
188
+ record("rsi_status_whitelist", _filter_in(df, mask, "rsi_status", filters.rsi_status_whitelist))
189
+ record_min("breakout_20d_pct_min", ["breakout_20d_pct"], filters.breakout_20d_pct_min)
190
+ record_max("breakout_20d_pct_max", ["breakout_20d_pct"], filters.breakout_20d_pct_max)
191
+ record_max("range_20d_pct_max", ["range_20d_pct"], filters.range_20d_pct_max)
192
+ record_min("volume_ratio_20d_min", ["volume_ratio_20d"], filters.volume_ratio_20d_min)
193
+ record_max("volume_ratio_20d_max", ["volume_ratio_20d"], filters.volume_ratio_20d_max)
194
+ record_min("body_pct_min", ["body_pct"], filters.body_pct_min)
195
+ record_max("body_pct_max", ["body_pct"], filters.body_pct_max)
196
+ record_min("pullback_to_ma20_pct_min", ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_min)
197
+ record_max("pullback_to_ma20_pct_max", ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_max)
198
+ record_min("consolidation_days_20d_min", ["consolidation_days_20d"], filters.consolidation_days_20d_min)
199
+ record_max("consolidation_days_20d_max", ["consolidation_days_20d"], filters.consolidation_days_20d_max)
200
+ record_min("volatility_20d_pct_min", ["volatility_20d_pct"], filters.volatility_20d_pct_min)
201
+ record_max("volatility_20d_pct_max", ["volatility_20d_pct"], filters.volatility_20d_pct_max)
202
+ record_min("max_drawdown_20d_pct_min", ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_min)
203
+ record_max("max_drawdown_20d_pct_max", ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_max)
204
+ record_min("atr_20_pct_min", ["atr_20_pct"], filters.atr_20_pct_min)
205
+ record_max("atr_20_pct_max", ["atr_20_pct"], filters.atr_20_pct_max)
206
+
207
+ return diagnostics
208
+
209
+
210
+ def _step_quantiles(
211
+ df: pd.DataFrame,
212
+ active_mask: pd.Series,
213
+ value_columns: list[str] | None,
214
+ ) -> dict[str, float | int] | None:
215
+ col = _find_col(df, list(value_columns or []))
216
+ if not col or not active_mask.any():
217
+ return None
218
+ raw = df.loc[active_mask, col]
219
+ if pd.api.types.is_bool_dtype(raw):
220
+ return None
221
+ if any(isinstance(v, bool) for v in raw.dropna()):
222
+ return None
223
+ nums = pd.to_numeric(raw, errors="coerce")
224
+ if pd.api.types.is_bool_dtype(nums):
225
+ return None
226
+ nums = nums.astype("float64").replace([float("inf"), float("-inf")], float("nan")).dropna()
227
+ if nums.empty:
228
+ return None
229
+ q25, q50, q75 = nums.quantile([0.25, 0.50, 0.75]).tolist()
230
+ return {
231
+ "p25": round(float(q25), 4),
232
+ "p50": round(float(q50), 4),
233
+ "p75": round(float(q75), 4),
234
+ "valid_count": int(len(nums)),
235
+ }
236
+
237
+
238
+ def hard_filter_waterfall(
239
+ df: pd.DataFrame,
240
+ filters: HardFilterConfig,
241
+ *,
242
+ sample_limit: int = 3,
243
+ include_quantiles: bool = False,
244
+ ) -> list[dict[str, object]]:
245
+ """Return sequential hard-filter counts plus optional quantile diagnostics and rejected row samples."""
246
+ if df.empty:
247
+ return []
248
+
249
+ mask = pd.Series(True, index=df.index)
250
+ steps: list[dict[str, object]] = []
251
+
252
+ def record(
253
+ label: str,
254
+ next_mask: pd.Series,
255
+ value_columns: list[str] | None = None,
256
+ *,
257
+ threshold: float | int | None = None,
258
+ bound: str = "",
259
+ ) -> None:
260
+ nonlocal mask
261
+ before = int(mask.sum())
262
+ after = int(next_mask.sum())
263
+ removed = before - after
264
+ quantiles = (
265
+ _step_quantiles(df, mask, value_columns)
266
+ if include_quantiles and threshold is not None and before > 0 and value_columns
267
+ else None
268
+ )
269
+ step: dict[str, object] = {
270
+ "filter": label,
271
+ "before": before,
272
+ "after": after,
273
+ "removed": removed,
274
+ "removed_pct": round((removed / before * 100.0), 4) if before else 0.0,
275
+ }
276
+ if include_quantiles and threshold is not None:
277
+ step["threshold"] = threshold
278
+ if quantiles is not None:
279
+ step["quantiles"] = quantiles
280
+ if removed > 0 and sample_limit > 0:
281
+ step["samples"] = _rejection_samples(
282
+ df.loc[mask & ~next_mask],
283
+ value_columns=value_columns or [],
284
+ limit=sample_limit,
285
+ )
286
+ suggestion = _waterfall_suggestion(label, before, after, removed)
287
+ if include_quantiles and before > 0 and (removed / before >= 0.90 or after == 0) and quantiles is not None and threshold is not None:
288
+ q_note = (
289
+ f"分布 p25={quantiles['p25']}, p50={quantiles['p50']}, p75={quantiles['p75']} "
290
+ f"(阈值 {bound or 'limit'}={threshold})"
291
+ )
292
+ suggestion = f"{suggestion}; {q_note}" if suggestion else f"当前阈值过严: {q_note}"
293
+ if suggestion:
294
+ step["suggestion"] = suggestion
295
+ steps.append(step)
296
+ mask = next_mask
297
+
298
+ if filters.exclude_st:
299
+ name_col = _find_col(df, ["name", "股票名称", "名称"]) if mask.any() else None
300
+ if not name_col:
301
+ raise SnapshotFieldMissingError(
302
+ "Missing required snapshot column for exclude_st filter: name"
303
+ )
304
+ record("exclude_st", mask & _not_st_mask(df[name_col]), [name_col])
305
+
306
+ def record_min(label: str, columns: list[str], value: float | None) -> None:
307
+ if value is not None:
308
+ record(label, _filter_min(df, mask, columns, value), columns, threshold=value, bound="min")
309
+
310
+ def record_max(label: str, columns: list[str], value: float | None) -> None:
311
+ if value is not None:
312
+ record(label, _filter_max(df, mask, columns, value), columns, threshold=value, bound="max")
313
+
314
+ record_min("amount_min", ["amount", "成交额"], filters.amount_min)
315
+ record_min("avg_amount_usd_min", ["avg_amount_usd"], filters.avg_amount_usd_min)
316
+ record_min("price_min", ["price", "最新价", "现价"], filters.price_min)
317
+ record_max("price_max", ["price", "最新价", "现价"], filters.price_max)
318
+ record_min("market_cap_min", ["total_mv", "总市值"], filters.market_cap_min)
319
+ record_max("market_cap_max", ["total_mv", "总市值"], filters.market_cap_max)
320
+ record_min("pe_ttm_min", ["pe_ratio", "市盈率"], filters.pe_ttm_min)
321
+ record_max("pe_ttm_max", ["pe_ratio", "市盈率"], filters.pe_ttm_max)
322
+ record_min("pb_min", ["pb_ratio", "市净率"], filters.pb_min)
323
+ record_max("pb_max", ["pb_ratio", "市净率"], filters.pb_max)
324
+ record_min("volume_ratio_min", ["volume_ratio", "量比"], filters.volume_ratio_min)
325
+ record_min("turnover_rate_min", ["turnover_rate", "换手率"], filters.turnover_rate_min)
326
+ record_min("change_pct_min", ["change_pct", "涨跌幅"], filters.change_pct_min)
327
+ record_max("change_pct_max", ["change_pct", "涨跌幅"], filters.change_pct_max)
328
+ record_min("change_60d_min", ["change_60d"], filters.change_60d_min)
329
+ record_max("change_60d_max", ["change_60d"], filters.change_60d_max)
330
+
331
+ if filters.require_ma_bullish:
332
+ record("require_ma_bullish", _filter_bool_true(df, mask, "ma_bullish", True), ["ma_bullish"])
333
+ if filters.require_price_above_ma20:
334
+ record("require_price_above_ma20", _filter_bool_true(df, mask, "price_above_ma20", True), ["price_above_ma20"])
335
+
336
+ record_min("signal_score_min", ["signal_score"], filters.signal_score_min)
337
+ if filters.macd_status_whitelist:
338
+ record("macd_status_whitelist", _filter_in(df, mask, "macd_status", filters.macd_status_whitelist), ["macd_status"])
339
+ if filters.rsi_status_whitelist:
340
+ record("rsi_status_whitelist", _filter_in(df, mask, "rsi_status", filters.rsi_status_whitelist), ["rsi_status"])
341
+ record_min("breakout_20d_pct_min", ["breakout_20d_pct"], filters.breakout_20d_pct_min)
342
+ record_max("breakout_20d_pct_max", ["breakout_20d_pct"], filters.breakout_20d_pct_max)
343
+ record_max("range_20d_pct_max", ["range_20d_pct"], filters.range_20d_pct_max)
344
+ record_min("volume_ratio_20d_min", ["volume_ratio_20d"], filters.volume_ratio_20d_min)
345
+ record_max("volume_ratio_20d_max", ["volume_ratio_20d"], filters.volume_ratio_20d_max)
346
+ record_min("body_pct_min", ["body_pct"], filters.body_pct_min)
347
+ record_max("body_pct_max", ["body_pct"], filters.body_pct_max)
348
+ record_min("pullback_to_ma20_pct_min", ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_min)
349
+ record_max("pullback_to_ma20_pct_max", ["pullback_to_ma20_pct"], filters.pullback_to_ma20_pct_max)
350
+ record_min("consolidation_days_20d_min", ["consolidation_days_20d"], filters.consolidation_days_20d_min)
351
+ record_max("consolidation_days_20d_max", ["consolidation_days_20d"], filters.consolidation_days_20d_max)
352
+ record_min("volatility_20d_pct_min", ["volatility_20d_pct"], filters.volatility_20d_pct_min)
353
+ record_max("volatility_20d_pct_max", ["volatility_20d_pct"], filters.volatility_20d_pct_max)
354
+ record_min("max_drawdown_20d_pct_min", ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_min)
355
+ record_max("max_drawdown_20d_pct_max", ["max_drawdown_20d_pct"], filters.max_drawdown_20d_pct_max)
356
+ record_min("atr_20_pct_min", ["atr_20_pct"], filters.atr_20_pct_min)
357
+ record_max("atr_20_pct_max", ["atr_20_pct"], filters.atr_20_pct_max)
358
+
359
+ return steps
360
+
361
+
362
+ def requires_daily_features(filters: HardFilterConfig) -> bool:
363
+ """Return whether a hard-filter config needs daily K-line features."""
364
+ return any([
365
+ filters.change_60d_min is not None,
366
+ filters.change_60d_max is not None,
367
+ filters.require_ma_bullish,
368
+ filters.require_price_above_ma20,
369
+ filters.signal_score_min is not None,
370
+ bool(filters.macd_status_whitelist),
371
+ bool(filters.rsi_status_whitelist),
372
+ filters.breakout_20d_pct_min is not None,
373
+ filters.breakout_20d_pct_max is not None,
374
+ filters.range_20d_pct_max is not None,
375
+ filters.volume_ratio_20d_min is not None,
376
+ filters.volume_ratio_20d_max is not None,
377
+ filters.body_pct_min is not None,
378
+ filters.body_pct_max is not None,
379
+ filters.pullback_to_ma20_pct_min is not None,
380
+ filters.pullback_to_ma20_pct_max is not None,
381
+ filters.consolidation_days_20d_min is not None,
382
+ filters.consolidation_days_20d_max is not None,
383
+ filters.volatility_20d_pct_min is not None,
384
+ filters.volatility_20d_pct_max is not None,
385
+ filters.max_drawdown_20d_pct_min is not None,
386
+ filters.max_drawdown_20d_pct_max is not None,
387
+ filters.atr_20_pct_min is not None,
388
+ filters.atr_20_pct_max is not None,
389
+ ])
390
+
391
+
392
+ def without_daily_filters(filters: HardFilterConfig) -> HardFilterConfig:
393
+ """Return a copy with daily K-line filters disabled."""
394
+ return replace(filters, **_DAILY_FILTER_DEFAULTS)
395
+
396
+
397
+ def _find_col(df: pd.DataFrame, candidates: list[str]) -> str | None:
398
+ for c in candidates:
399
+ if c in df.columns:
400
+ return c
401
+ return None
402
+
403
+
404
+ def _filter_min(
405
+ df: pd.DataFrame,
406
+ mask: pd.Series,
407
+ col_names: list[str],
408
+ value: float | None,
409
+ ) -> pd.Series:
410
+ if value is None:
411
+ return mask
412
+ if not mask.any():
413
+ return mask
414
+ col = _find_col(df, col_names)
415
+ if not col:
416
+ raise SnapshotFieldMissingError(
417
+ f"Missing required snapshot column for min filter {col_names}: "
418
+ f"configured value={value}"
419
+ )
420
+ series = pd.to_numeric(df[col], errors="coerce")
421
+ return mask & series.ge(value) & series.notna()
422
+
423
+
424
+ def _filter_max(
425
+ df: pd.DataFrame,
426
+ mask: pd.Series,
427
+ col_names: list[str],
428
+ value: float | None,
429
+ ) -> pd.Series:
430
+ if value is None:
431
+ return mask
432
+ if not mask.any():
433
+ return mask
434
+ col = _find_col(df, col_names)
435
+ if not col:
436
+ raise SnapshotFieldMissingError(
437
+ f"Missing required snapshot column for max filter {col_names}: "
438
+ f"configured value={value}"
439
+ )
440
+ series = pd.to_numeric(df[col], errors="coerce")
441
+ return mask & series.le(value) & series.notna()
442
+
443
+
444
+ def _filter_bool_true(
445
+ df: pd.DataFrame,
446
+ mask: pd.Series,
447
+ col_name: str,
448
+ enabled: bool,
449
+ ) -> pd.Series:
450
+ if not enabled:
451
+ return mask
452
+ if not mask.any():
453
+ return mask
454
+ if col_name not in df.columns:
455
+ raise SnapshotFieldMissingError(
456
+ f"Missing required daily feature column for bool filter: {col_name}"
457
+ )
458
+ return mask & (df[col_name] == True) # noqa: E712
459
+
460
+
461
+ def _filter_in(
462
+ df: pd.DataFrame,
463
+ mask: pd.Series,
464
+ col_name: str,
465
+ allowed: list[str] | None,
466
+ ) -> pd.Series:
467
+ if not allowed:
468
+ return mask
469
+ if not mask.any():
470
+ return mask
471
+ if col_name not in df.columns:
472
+ raise SnapshotFieldMissingError(
473
+ f"Missing required daily feature column for whitelist filter: {col_name}"
474
+ )
475
+ allowed_set = {str(item) for item in allowed}
476
+ return mask & df[col_name].astype(str).isin(allowed_set)
477
+
478
+
479
+
480
+ def _rejection_samples(
481
+ df: pd.DataFrame,
482
+ *,
483
+ value_columns: list[str],
484
+ limit: int,
485
+ ) -> list[dict[str, object]]:
486
+ samples: list[dict[str, object]] = []
487
+ name_col = _find_col(df, ["name", "股票名称", "名称"])
488
+ code_col = _find_col(df, ["code", "代码", "symbol"])
489
+ value_col = _find_col(df, value_columns)
490
+ for _, row in df.head(limit).iterrows():
491
+ item: dict[str, object] = {}
492
+ if code_col:
493
+ item["code"] = str(row.get(code_col, ""))
494
+ if name_col:
495
+ item["name"] = str(row.get(name_col, ""))
496
+ if value_col:
497
+ value = row.get(value_col)
498
+ if hasattr(value, "item") and callable(getattr(value, "item")):
499
+ value = value.item()
500
+ if pd.isna(value):
501
+ item["value"] = None
502
+ elif isinstance(value, (int, float)) and not isinstance(value, bool):
503
+ item["value"] = value if math.isfinite(float(value)) else None
504
+ else:
505
+ item["value"] = value
506
+ samples.append(item)
507
+ return samples
508
+
509
+
510
+ def _waterfall_suggestion(label: str, before: int, after: int, removed: int) -> str:
511
+ if before <= 0 or removed <= 0:
512
+ return ""
513
+ if after == 0:
514
+ return f"{label} eliminated all remaining candidates; inspect threshold or data availability."
515
+ if removed / before >= 0.9:
516
+ return f"{label} removed over 90% of remaining candidates; consider reviewing this threshold."
517
+ return ""