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
@@ -0,0 +1,578 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Objective CN market-breadth, limit-up ladder, and regime-stage statistics.
3
+
4
+ All metrics and stage labels here are reporting and evaluation-slicing metadata
5
+ only; they never alter strategy scoring or weights.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import asdict, dataclass, field
11
+ from datetime import date
12
+ import re
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ from alphasift.normalize import normalize_code
19
+ from alphasift.pack import DailyPack
20
+
21
+ _ST_PREFIXES = ("ST", "*ST", "SST", "S*ST")
22
+ _ISO_DATE_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
23
+ _COMPACT_DATE_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})$")
24
+
25
+ REGIME_STAGE_LABELS: dict[str, str] = {
26
+ "freezing": "冰点",
27
+ "startup": "启动",
28
+ "main_up": "主升",
29
+ "divergence": "分歧",
30
+ "ebb": "退潮",
31
+ "neutral": "震荡",
32
+ }
33
+ REGIME_STAGE_ORDER: tuple[str, ...] = (
34
+ "freezing",
35
+ "startup",
36
+ "main_up",
37
+ "divergence",
38
+ "ebb",
39
+ "neutral",
40
+ )
41
+
42
+
43
+ @dataclass
44
+ class MarketRegimeSnapshot:
45
+ """Single-session CN market breadth, limit-up ladder, and stage snapshot."""
46
+
47
+ trade_date: str
48
+ traded_count: int
49
+ advancing_count: int
50
+ declining_count: int
51
+ flat_count: int
52
+ advance_ratio_pct: float
53
+ limit_up_count: int
54
+ non_st_limit_up_count: int
55
+ one_price_limit_up_count: int
56
+ broken_board_count: int
57
+ non_st_broken_board_count: int
58
+ seal_rate_pct: float | None
59
+ limit_down_count: int
60
+ non_st_limit_down_count: int
61
+ one_price_limit_down_count: int
62
+ max_consecutive_limit_up: int
63
+ consecutive_board_ladder: dict[int, int]
64
+ prev_limit_up_count: int
65
+ prev_limit_up_avg_return_pct: float | None
66
+ prev_limit_up_open_premium_pct: float | None
67
+ prev_limit_up_win_rate_pct: float | None
68
+ prev_limit_up_promoted_count: int
69
+ prev_limit_up_promotion_rate_pct: float | None
70
+ total_amount_yi: float | None
71
+ amount_is_proxy: bool
72
+ regime_stage: str
73
+ regime_stage_label: str
74
+ regime_reasons: list[str]
75
+ usage_policy: str = "reporting_and_slice_only"
76
+ median_return_pct: float | None = None
77
+ return_distribution: dict[str, int] = field(default_factory=dict)
78
+
79
+ def to_dict(self) -> dict[str, Any]:
80
+ payload = asdict(self)
81
+ payload["consecutive_board_ladder"] = {
82
+ str(k): int(v) for k, v in self.consecutive_board_ladder.items()
83
+ }
84
+ return payload
85
+
86
+
87
+ def cn_price_limit_pct(code: str, *, is_st: bool = False, name: str = "") -> float:
88
+ """Return CN daily price-limit ratio (0.10, 0.20, 0.30, or main-board ST 0.05)."""
89
+ norm = normalize_code(code, allow_ticker=False) or str(code or "").strip()
90
+ if norm.startswith(("300", "301", "688", "689")):
91
+ return 0.20
92
+ if norm.startswith(("4", "8", "920")):
93
+ return 0.30
94
+ upper_name = str(name or "").strip().upper()
95
+ if is_st or upper_name.startswith(_ST_PREFIXES):
96
+ return 0.05
97
+ return 0.10
98
+
99
+
100
+ def round_cn_tick(values: np.ndarray | float) -> np.ndarray | float:
101
+ """Vectorized half-up rounding to CN tick size (0.01 yuan)."""
102
+ return np.floor(np.asarray(values, dtype=np.float64) * 100.0 + 0.5 + 1e-9) / 100.0
103
+
104
+
105
+ def _normalize_date_str(value: object) -> str | None:
106
+ if value is None or (isinstance(value, float) and np.isnan(value)):
107
+ return None
108
+ text = str(value).strip()
109
+ if not text or text.lower() in {"nan", "nat", "none", "<na>"}:
110
+ return None
111
+ if _ISO_DATE_RE.match(text):
112
+ return text
113
+ match = _COMPACT_DATE_RE.match(text)
114
+ if match:
115
+ return f"{match.group(1)}-{match.group(2)}-{match.group(3)}"
116
+ try:
117
+ return date.fromisoformat(text[:10]).isoformat()
118
+ except ValueError:
119
+ return None
120
+
121
+
122
+ def _aligned_meta(pack: DailyPack) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
123
+ """Align is_st, limit_pct, and normalized list_date arrays to ``pack.codes``."""
124
+ n = len(pack.codes)
125
+ codes = np.asarray([normalize_code(c, allow_ticker=False) or str(c) for c in pack.codes], dtype=str)
126
+ st_map: dict[str, bool] = {}
127
+ name_map: dict[str, str] = {}
128
+ list_map: dict[str, str] = {}
129
+
130
+ if pack.meta is not None and not pack.meta.empty and "code" in pack.meta.columns:
131
+ for row in pack.meta.itertuples(index=False):
132
+ raw_code = getattr(row, "code", "")
133
+ code = normalize_code(raw_code, allow_ticker=False) or str(raw_code).strip()
134
+ if not code:
135
+ continue
136
+ name_val = getattr(row, "name", "")
137
+ name_str = "" if name_val is None or pd.isna(name_val) else str(name_val).strip()
138
+ name_map[code] = name_str
139
+ is_st_val = getattr(row, "is_st", False)
140
+ is_st_flag = bool(False if pd.isna(is_st_val) else is_st_val)
141
+ if name_str.upper().startswith(_ST_PREFIXES):
142
+ is_st_flag = True
143
+ st_map[code] = is_st_flag
144
+ list_norm = _normalize_date_str(getattr(row, "list_date", None))
145
+ if list_norm:
146
+ list_map[code] = list_norm
147
+
148
+ is_st = np.zeros(n, dtype=bool)
149
+ limit_pct = np.empty(n, dtype=np.float64)
150
+ list_dates = np.empty(n, dtype=object)
151
+ for j, code in enumerate(codes):
152
+ st_flag = st_map.get(code, False)
153
+ name_str = name_map.get(code, "")
154
+ is_st[j] = st_flag
155
+ limit_pct[j] = cn_price_limit_pct(code, is_st=st_flag, name=name_str)
156
+ list_dates[j] = list_map.get(code)
157
+ return is_st, limit_pct, list_dates
158
+
159
+
160
+ def compute_limit_masks(
161
+ daily_pack: DailyPack,
162
+ *,
163
+ end_index: int | None = None,
164
+ ) -> dict[str, np.ndarray]:
165
+ """Compute vectorized CN price-limit, broken-board, and streak masks over ``daily_pack``."""
166
+ total_dates = len(daily_pack.dates)
167
+ if total_dates == 0 or len(daily_pack.codes) == 0:
168
+ empty_bool = np.zeros((0, len(daily_pack.codes)), dtype=bool)
169
+ empty_float = np.zeros((0, len(daily_pack.codes)), dtype=np.float64)
170
+ return {
171
+ "active": empty_bool,
172
+ "is_st": np.zeros(len(daily_pack.codes), dtype=bool),
173
+ "limit_pct": np.zeros(len(daily_pack.codes), dtype=np.float64),
174
+ "pre_close": empty_float,
175
+ "up_limit": empty_float,
176
+ "down_limit": empty_float,
177
+ "has_price_limit": empty_bool,
178
+ "is_limit_up": empty_bool,
179
+ "is_limit_down": empty_bool,
180
+ "is_one_price_limit_up": empty_bool,
181
+ "is_one_price_limit_down": empty_bool,
182
+ "is_broken_board": empty_bool,
183
+ "consecutive_limit_up": np.zeros((0, len(daily_pack.codes)), dtype=np.int32),
184
+ "proxy_amount": empty_float,
185
+ "has_real_amount": empty_bool,
186
+ }
187
+
188
+ if end_index is None:
189
+ end_idx = total_dates
190
+ else:
191
+ end_idx = end_index + 1 if end_index >= 0 else total_dates + end_index + 1
192
+ if end_idx <= 0 or end_idx > total_dates:
193
+ raise IndexError(f"end_index {end_index} out of range for {total_dates} sessions")
194
+
195
+ dates = np.asarray(daily_pack.dates[:end_idx], dtype=str)
196
+ t_len = len(dates)
197
+ n_codes = len(daily_pack.codes)
198
+
199
+ open_ = np.asarray(daily_pack.matrices["open"][:end_idx], dtype=np.float64)
200
+ high = np.asarray(daily_pack.matrices["high"][:end_idx], dtype=np.float64)
201
+ low = np.asarray(daily_pack.matrices["low"][:end_idx], dtype=np.float64)
202
+ close = np.asarray(daily_pack.matrices["close"][:end_idx], dtype=np.float64)
203
+ pc_raw = np.asarray(daily_pack.matrices["pre_close"][:end_idx], dtype=np.float64)
204
+ vol = np.asarray(daily_pack.matrices["volume"][:end_idx], dtype=np.float64)
205
+ amt = np.asarray(daily_pack.matrices["amount"][:end_idx], dtype=np.float64)
206
+
207
+ is_st, limit_pct, list_dates = _aligned_meta(daily_pack)
208
+ bar_valid = np.isfinite(close) & (close > 0) & (~np.isfinite(vol) | (vol > 0))
209
+
210
+ prev_c_row = np.full((t_len, n_codes), np.nan, dtype=np.float64)
211
+ last_close = np.full(n_codes, np.nan, dtype=np.float64)
212
+ for t in range(t_len):
213
+ prev_c_row[t] = last_close
214
+ valid_t = bar_valid[t]
215
+ if valid_t.any():
216
+ last_close = np.where(valid_t, close[t], last_close)
217
+
218
+ pre_close = np.where(np.isfinite(pc_raw) & (pc_raw > 0), pc_raw, prev_c_row)
219
+ active = bar_valid & np.isfinite(pre_close) & (pre_close > 0)
220
+
221
+ up_limit = round_cn_tick(pre_close * (1.0 + limit_pct[None, :]))
222
+ down_limit = round_cn_tick(pre_close * (1.0 - limit_pct[None, :]))
223
+
224
+ # Exclude no-limit IPO / resumption bars (and historical ST-transition outliers).
225
+ out_of_band = (
226
+ (close > up_limit + 0.02)
227
+ | (np.isfinite(high) & (high > up_limit + 0.02))
228
+ | (close < down_limit - 0.02)
229
+ | (np.isfinite(low) & (low < down_limit - 0.02))
230
+ )
231
+ has_price_limit = active & ~out_of_band
232
+
233
+ # When list_date falls inside or just before the pack window, exclude first-5-day
234
+ # registration-IPO no-limit sessions (BSE: first session only).
235
+ first_date = str(dates[0])
236
+ cum_bars = np.cumsum(bar_valid, axis=0)
237
+ is_bj = np.asarray(
238
+ [(normalize_code(c, allow_ticker=False) or str(c)).startswith(("4", "8", "920")) for c in daily_pack.codes],
239
+ dtype=bool,
240
+ )
241
+ for j in range(n_codes):
242
+ ld = list_dates[j]
243
+ if ld is not None and ld >= first_date:
244
+ no_limit_days = 1 if is_bj[j] else 5
245
+ on_or_after = dates >= ld
246
+ ipo_window = on_or_after & bar_valid[:, j] & (cum_bars[:, j] <= no_limit_days)
247
+ has_price_limit[ipo_window, j] = False
248
+
249
+ tol = 0.00500001
250
+ is_limit_up = has_price_limit & (close >= up_limit - tol)
251
+ is_limit_down = has_price_limit & (close <= down_limit + tol)
252
+ is_one_price_limit_up = (
253
+ is_limit_up
254
+ & np.isfinite(open_)
255
+ & np.isfinite(low)
256
+ & (np.abs(open_ - up_limit) <= tol)
257
+ & (np.abs(open_ - low) <= 1e-6)
258
+ )
259
+ is_one_price_limit_down = (
260
+ is_limit_down
261
+ & np.isfinite(open_)
262
+ & np.isfinite(high)
263
+ & (np.abs(open_ - down_limit) <= tol)
264
+ & (np.abs(open_ - high) <= 1e-6)
265
+ )
266
+ is_broken_board = has_price_limit & (~is_limit_up) & np.isfinite(high) & (high >= up_limit - tol)
267
+
268
+ streak = np.zeros((t_len, n_codes), dtype=np.int32)
269
+ running = np.zeros(n_codes, dtype=np.int32)
270
+ for t in range(t_len):
271
+ act_t = active[t]
272
+ lu_t = is_limit_up[t]
273
+ running = np.where(act_t, np.where(lu_t, running + 1, 0), running)
274
+ streak[t] = np.where(act_t & lu_t, running, 0)
275
+
276
+ has_real_amount = active & np.isfinite(amt) & (amt > 0)
277
+ proxy_amount = np.where(
278
+ has_real_amount,
279
+ amt,
280
+ np.where(active & np.isfinite(vol) & (vol > 0), close * vol, np.nan),
281
+ )
282
+
283
+ return {
284
+ "dates": dates,
285
+ "active": active,
286
+ "is_st": is_st,
287
+ "limit_pct": limit_pct,
288
+ "open": open_,
289
+ "high": high,
290
+ "low": low,
291
+ "close": close,
292
+ "pre_close": pre_close,
293
+ "up_limit": up_limit,
294
+ "down_limit": down_limit,
295
+ "has_price_limit": has_price_limit,
296
+ "is_limit_up": is_limit_up,
297
+ "is_limit_down": is_limit_down,
298
+ "is_one_price_limit_up": is_one_price_limit_up,
299
+ "is_one_price_limit_down": is_one_price_limit_down,
300
+ "is_broken_board": is_broken_board,
301
+ "consecutive_limit_up": streak,
302
+ "proxy_amount": proxy_amount,
303
+ "has_real_amount": has_real_amount,
304
+ }
305
+
306
+
307
+ def classify_regime_stage(
308
+ *,
309
+ advance_ratio_pct: float,
310
+ non_st_limit_up_count: int,
311
+ non_st_limit_down_count: int,
312
+ non_st_broken_board_count: int,
313
+ seal_rate_pct: float | None,
314
+ max_consecutive_limit_up: int,
315
+ prev_limit_up_avg_return_pct: float | None,
316
+ ) -> tuple[str, str, list[str]]:
317
+ """Rule-based CN regime stage classification for reporting & evaluation slices only."""
318
+ prev_ret = prev_limit_up_avg_return_pct
319
+ seal = seal_rate_pct
320
+
321
+ if (
322
+ (advance_ratio_pct < 25.0 and non_st_limit_down_count >= 25)
323
+ or (advance_ratio_pct < 20.0 and non_st_limit_up_count < 35)
324
+ or (non_st_limit_up_count < 25 and prev_ret is not None and prev_ret < -1.0)
325
+ ):
326
+ reasons = [
327
+ f"上涨占比 {advance_ratio_pct:.1f}%",
328
+ f"非ST涨停 {non_st_limit_up_count} / 跌停 {non_st_limit_down_count}",
329
+ ]
330
+ if prev_ret is not None:
331
+ reasons.append(f"昨涨停溢价 {prev_ret:+.2f}%")
332
+ return "freezing", REGIME_STAGE_LABELS["freezing"], reasons
333
+
334
+ if (
335
+ (non_st_limit_down_count >= 20 and prev_ret is not None and prev_ret < -0.5)
336
+ or (seal is not None and seal < 60.0 and advance_ratio_pct < 40.0 and non_st_limit_down_count >= 10)
337
+ or (prev_ret is not None and prev_ret <= -1.5 and advance_ratio_pct < 45.0)
338
+ ):
339
+ reasons = [f"非ST跌停 {non_st_limit_down_count}", f"上涨占比 {advance_ratio_pct:.1f}%"]
340
+ if seal is not None:
341
+ reasons.append(f"封板率 {seal:.1f}%")
342
+ if prev_ret is not None:
343
+ reasons.append(f"昨涨停溢价 {prev_ret:+.2f}%")
344
+ return "ebb", REGIME_STAGE_LABELS["ebb"], reasons
345
+
346
+ if (
347
+ advance_ratio_pct >= 60.0
348
+ and non_st_limit_up_count >= 65
349
+ and (seal is None or seal >= 72.0)
350
+ and (prev_ret is None or prev_ret >= 1.0)
351
+ ):
352
+ reasons = [
353
+ f"上涨占比 {advance_ratio_pct:.1f}%",
354
+ f"非ST涨停 {non_st_limit_up_count}",
355
+ ]
356
+ if seal is not None:
357
+ reasons.append(f"封板率 {seal:.1f}%")
358
+ if prev_ret is not None:
359
+ reasons.append(f"昨涨停溢价 {prev_ret:+.2f}%")
360
+ return "main_up", REGIME_STAGE_LABELS["main_up"], reasons
361
+
362
+ if (
363
+ (advance_ratio_pct >= 58.0 and non_st_limit_up_count >= 45 and non_st_limit_down_count <= 10)
364
+ or (advance_ratio_pct >= 50.0 and prev_ret is not None and prev_ret >= 2.0 and non_st_limit_up_count >= 50)
365
+ ):
366
+ reasons = [
367
+ f"上涨占比 {advance_ratio_pct:.1f}%",
368
+ f"非ST涨停 {non_st_limit_up_count}",
369
+ ]
370
+ if prev_ret is not None:
371
+ reasons.append(f"昨涨停溢价 {prev_ret:+.2f}%")
372
+ return "startup", REGIME_STAGE_LABELS["startup"], reasons
373
+
374
+ if (
375
+ (non_st_limit_up_count >= 45 and seal is not None and seal < 70.0)
376
+ or (non_st_broken_board_count >= 30 and non_st_limit_up_count >= 40)
377
+ or (max_consecutive_limit_up >= 5 and advance_ratio_pct < 45.0)
378
+ ):
379
+ reasons = [
380
+ f"非ST涨停 {non_st_limit_up_count} / 炸板 {non_st_broken_board_count}",
381
+ f"最高连板 {max_consecutive_limit_up}",
382
+ ]
383
+ if seal is not None:
384
+ reasons.append(f"封板率 {seal:.1f}%")
385
+ return "divergence", REGIME_STAGE_LABELS["divergence"], reasons
386
+
387
+ reasons = [
388
+ f"上涨占比 {advance_ratio_pct:.1f}%",
389
+ f"非ST涨停 {non_st_limit_up_count} / 跌停 {non_st_limit_down_count}",
390
+ ]
391
+ return "neutral", REGIME_STAGE_LABELS["neutral"], reasons
392
+
393
+
394
+ def _snapshot_at_index(masks: dict[str, np.ndarray], t: int) -> MarketRegimeSnapshot:
395
+ dates = masks["dates"]
396
+ is_st = masks["is_st"]
397
+ non_st = ~is_st
398
+
399
+ act = masks["active"][t]
400
+ close_t = masks["close"][t]
401
+ open_t = masks["open"][t]
402
+ pc_t = masks["pre_close"][t]
403
+
404
+ traded_count = int(act.sum())
405
+ ret_t = np.where(act, close_t / pc_t - 1.0, np.nan)
406
+ advancing_count = int((act & (close_t > pc_t + 1e-6)).sum())
407
+ declining_count = int((act & (close_t < pc_t - 1e-6)).sum())
408
+ flat_count = max(0, traded_count - advancing_count - declining_count)
409
+ advance_ratio_pct = round((advancing_count / traded_count) * 100.0, 2) if traded_count > 0 else 0.0
410
+ valid_pcts = ret_t[act] * 100.0
411
+ valid_pcts = valid_pcts[np.isfinite(valid_pcts)]
412
+ median_return_pct = round(float(np.median(valid_pcts)), 2) if valid_pcts.size > 0 else None
413
+ return_distribution = {
414
+ "le_neg7": int((valid_pcts <= -7.0).sum()),
415
+ "neg7_neg3": int(((valid_pcts > -7.0) & (valid_pcts <= -3.0)).sum()),
416
+ "neg3_0": int(((valid_pcts > -3.0) & (valid_pcts < -1e-4)).sum()),
417
+ "flat": int((np.abs(valid_pcts) <= 1e-4).sum()),
418
+ "pos0_3": int(((valid_pcts > 1e-4) & (valid_pcts < 3.0)).sum()),
419
+ "pos3_7": int(((valid_pcts >= 3.0) & (valid_pcts < 7.0)).sum()),
420
+ "ge_pos7": int((valid_pcts >= 7.0).sum()),
421
+ }
422
+
423
+ lu = masks["is_limit_up"][t]
424
+ lu_non_st = lu & non_st
425
+ ld = masks["is_limit_down"][t]
426
+ ld_non_st = ld & non_st
427
+ bb = masks["is_broken_board"][t]
428
+ bb_non_st = bb & non_st
429
+ one_lu = masks["is_one_price_limit_up"][t]
430
+ one_ld = masks["is_one_price_limit_down"][t]
431
+
432
+ limit_up_count = int(lu.sum())
433
+ non_st_limit_up_count = int(lu_non_st.sum())
434
+ one_price_limit_up_count = int(one_lu.sum())
435
+ broken_board_count = int(bb.sum())
436
+ non_st_broken_board_count = int(bb_non_st.sum())
437
+
438
+ seal_den = non_st_limit_up_count + non_st_broken_board_count
439
+ seal_rate_pct = round((non_st_limit_up_count / seal_den) * 100.0, 2) if seal_den > 0 else None
440
+
441
+ limit_down_count = int(ld.sum())
442
+ non_st_limit_down_count = int(ld_non_st.sum())
443
+ one_price_limit_down_count = int(one_ld.sum())
444
+
445
+ streak_t = masks["consecutive_limit_up"][t]
446
+ lu_streaks = streak_t[lu_non_st]
447
+ max_consecutive_limit_up = int(lu_streaks.max()) if lu_streaks.size > 0 else 0
448
+ ladder: dict[int, int] = {}
449
+ if lu_streaks.size > 0:
450
+ unique_boards, counts = np.unique(lu_streaks, return_counts=True)
451
+ for board_cnt, n_stocks in zip(unique_boards.tolist(), counts.tolist()):
452
+ if int(board_cnt) >= 2:
453
+ ladder[int(board_cnt)] = int(n_stocks)
454
+
455
+ prev_lu_count = 0
456
+ prev_lu_avg_ret: float | None = None
457
+ prev_lu_open_prem: float | None = None
458
+ prev_lu_win_rate: float | None = None
459
+ prev_lu_promoted = 0
460
+ prev_lu_promo_rate: float | None = None
461
+
462
+ if t > 0:
463
+ prev_pool = masks["is_limit_up"][t - 1] & non_st & act
464
+ prev_lu_count = int(prev_pool.sum())
465
+ if prev_lu_count > 0:
466
+ prev_rets = ret_t[prev_pool] * 100.0
467
+ prev_lu_avg_ret = round(float(np.mean(prev_rets)), 2)
468
+ prev_lu_win_rate = round(float((prev_rets > 0).mean() * 100.0), 2)
469
+ open_mask = prev_pool & np.isfinite(open_t) & (open_t > 0)
470
+ if open_mask.any():
471
+ prev_lu_open_prem = round(
472
+ float(np.mean((open_t[open_mask] / pc_t[open_mask] - 1.0) * 100.0)),
473
+ 2,
474
+ )
475
+ prev_lu_promoted = int((prev_pool & lu_non_st).sum())
476
+ prev_lu_promo_rate = round((prev_lu_promoted / prev_lu_count) * 100.0, 2)
477
+
478
+ real_amt_cnt = int(masks["has_real_amount"][t].sum())
479
+ amount_is_proxy = real_amt_cnt < int(0.8 * max(1, traded_count))
480
+ amt_t = masks["proxy_amount"][t]
481
+ valid_amt = act & np.isfinite(amt_t) & (amt_t > 0)
482
+ total_amount_yi = round(float(amt_t[valid_amt].sum() / 1e8), 2) if valid_amt.any() else None
483
+
484
+ stage, stage_label, reasons = classify_regime_stage(
485
+ advance_ratio_pct=advance_ratio_pct,
486
+ non_st_limit_up_count=non_st_limit_up_count,
487
+ non_st_limit_down_count=non_st_limit_down_count,
488
+ non_st_broken_board_count=non_st_broken_board_count,
489
+ seal_rate_pct=seal_rate_pct,
490
+ max_consecutive_limit_up=max_consecutive_limit_up,
491
+ prev_limit_up_avg_return_pct=prev_lu_avg_ret,
492
+ )
493
+
494
+ return MarketRegimeSnapshot(
495
+ trade_date=str(dates[t]),
496
+ traded_count=traded_count,
497
+ advancing_count=advancing_count,
498
+ declining_count=declining_count,
499
+ flat_count=flat_count,
500
+ advance_ratio_pct=advance_ratio_pct,
501
+ limit_up_count=limit_up_count,
502
+ non_st_limit_up_count=non_st_limit_up_count,
503
+ one_price_limit_up_count=one_price_limit_up_count,
504
+ broken_board_count=broken_board_count,
505
+ non_st_broken_board_count=non_st_broken_board_count,
506
+ seal_rate_pct=seal_rate_pct,
507
+ limit_down_count=limit_down_count,
508
+ non_st_limit_down_count=non_st_limit_down_count,
509
+ one_price_limit_down_count=one_price_limit_down_count,
510
+ max_consecutive_limit_up=max_consecutive_limit_up,
511
+ consecutive_board_ladder=ladder,
512
+ prev_limit_up_count=prev_lu_count,
513
+ prev_limit_up_avg_return_pct=prev_lu_avg_ret,
514
+ prev_limit_up_open_premium_pct=prev_lu_open_prem,
515
+ prev_limit_up_win_rate_pct=prev_lu_win_rate,
516
+ prev_limit_up_promoted_count=prev_lu_promoted,
517
+ prev_limit_up_promotion_rate_pct=prev_lu_promo_rate,
518
+ total_amount_yi=total_amount_yi,
519
+ amount_is_proxy=amount_is_proxy,
520
+ regime_stage=stage,
521
+ regime_stage_label=stage_label,
522
+ regime_reasons=reasons,
523
+ median_return_pct=median_return_pct,
524
+ return_distribution=return_distribution,
525
+ )
526
+
527
+
528
+ def compute_market_regime_series(
529
+ daily_pack: DailyPack,
530
+ *,
531
+ end_index: int | None = None,
532
+ masks: dict[str, np.ndarray] | None = None,
533
+ ) -> list[MarketRegimeSnapshot]:
534
+ """Compute objective market-regime statistics across all sessions up to ``end_index``."""
535
+ resolved_masks = masks if masks is not None else compute_limit_masks(daily_pack, end_index=end_index)
536
+ t_len = len(resolved_masks["dates"])
537
+ return [_snapshot_at_index(resolved_masks, t) for t in range(t_len)]
538
+
539
+
540
+ def compute_market_regime(
541
+ daily_pack: DailyPack,
542
+ *,
543
+ as_of_index: int = -1,
544
+ trade_date: str | None = None,
545
+ ) -> MarketRegimeSnapshot:
546
+ """Compute point-in-time CN market regime statistics at ``as_of_index`` or ``trade_date``."""
547
+ dates = [str(d) for d in daily_pack.dates]
548
+ if not dates:
549
+ raise ValueError("DailyPack contains no sessions")
550
+ if trade_date is not None:
551
+ norm_day = _normalize_date_str(trade_date)
552
+ if not norm_day or norm_day not in dates:
553
+ raise ValueError(f"trade_date {trade_date!r} not found in DailyPack ({dates[0]}..{dates[-1]})")
554
+ idx = dates.index(norm_day)
555
+ else:
556
+ idx = as_of_index if as_of_index >= 0 else len(dates) + as_of_index
557
+ if idx < 0 or idx >= len(dates):
558
+ raise IndexError(f"as_of_index {as_of_index} out of range for {len(dates)} sessions")
559
+
560
+ # Compute strictly up to ``idx`` so no future metadata or bars leak into history.
561
+ masks = compute_limit_masks(daily_pack, end_index=idx)
562
+ return _snapshot_at_index(masks, idx)
563
+
564
+
565
+ def summarize_regime_distribution(snapshots: list[MarketRegimeSnapshot]) -> dict[str, dict[str, Any]]:
566
+ """Aggregate session counts and shares across the 6 regime stage buckets."""
567
+ total = len(snapshots)
568
+ counts = {stage: 0 for stage in REGIME_STAGE_ORDER}
569
+ for snap in snapshots:
570
+ counts[snap.regime_stage] = counts.get(snap.regime_stage, 0) + 1
571
+ return {
572
+ stage: {
573
+ "label": REGIME_STAGE_LABELS[stage],
574
+ "days": counts[stage],
575
+ "share_pct": round((counts[stage] / total) * 100.0, 2) if total > 0 else 0.0,
576
+ }
577
+ for stage in REGIME_STAGE_ORDER
578
+ }