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,431 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Vectorized daily technical and shape features over CN daily bar matrices."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Sequence
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from alphasift.daily import _DAILY_FEATURE_DEFAULTS
12
+ from alphasift.normalize import normalize_code
13
+ from alphasift.pack import DailyPack, forward_adjust
14
+
15
+ _FEATURE_COLUMNS = ["code", *list(_DAILY_FEATURE_DEFAULTS)]
16
+ _EMA12_ALPHA = 2.0 / (12.0 + 1.0)
17
+ _EMA26_ALPHA = 2.0 / (26.0 + 1.0)
18
+ _EMA9_ALPHA = 2.0 / (9.0 + 1.0)
19
+
20
+
21
+ def _normalize_pack_code(value: object) -> str:
22
+ return normalize_code(value, allow_ticker=False)
23
+
24
+
25
+ def _round_array(values: np.ndarray, valid: np.ndarray) -> list[float | None]:
26
+ out: list[float | None] = [None] * len(values)
27
+ for idx in np.flatnonzero(valid):
28
+ out[int(idx)] = round(float(values[idx]), 4)
29
+ return out
30
+
31
+
32
+ def compute_pack_daily_features(
33
+ daily_pack: DailyPack,
34
+ *,
35
+ codes: Sequence[str] | None = None,
36
+ as_of_index: int | None = None,
37
+ trade_date: str | None = None,
38
+ ) -> pd.DataFrame:
39
+ """Slice to ``trade_date``/``as_of_index`` BEFORE ``forward_adjust``, then compute features."""
40
+ dates = [str(d) for d in daily_pack.dates]
41
+ total_dates = len(dates)
42
+ if total_dates == 0 or len(daily_pack.codes) == 0:
43
+ return pd.DataFrame(columns=_FEATURE_COLUMNS)
44
+
45
+ if trade_date is not None:
46
+ if trade_date not in dates:
47
+ raise ValueError(f"trade_date {trade_date!r} not found in DailyPack ({dates[0]}..{dates[-1]})")
48
+ end_idx = dates.index(trade_date) + 1
49
+ elif as_of_index is not None:
50
+ end_idx = as_of_index + 1 if as_of_index >= 0 else total_dates + as_of_index + 1
51
+ if end_idx <= 0 or end_idx > total_dates:
52
+ raise IndexError(f"as_of_index {as_of_index} out of range for {total_dates} sessions")
53
+ else:
54
+ end_idx = total_dates
55
+
56
+ if end_idx < total_dates:
57
+ # Slice strictly BEFORE forward_adjust so future splits never rescale past MAs.
58
+ work_pack = DailyPack(
59
+ dates=daily_pack.dates[:end_idx],
60
+ codes=daily_pack.codes,
61
+ matrices={k: v[:end_idx] for k, v in daily_pack.matrices.items()},
62
+ meta=daily_pack.meta,
63
+ sources=daily_pack.sources,
64
+ manifest=daily_pack.manifest,
65
+ )
66
+ else:
67
+ work_pack = daily_pack
68
+
69
+ adjusted = forward_adjust(work_pack)
70
+ return compute_matrix_daily_features(
71
+ work_pack.codes,
72
+ adjusted,
73
+ selected_codes=codes,
74
+ as_of_index=None,
75
+ )
76
+
77
+
78
+ def compute_matrix_daily_features(
79
+ codes: np.ndarray,
80
+ matrices: dict[str, np.ndarray],
81
+ *,
82
+ selected_codes: Sequence[str] | None = None,
83
+ as_of_index: int | None = None,
84
+ ) -> pd.DataFrame:
85
+ """Compute ``daily.compute_daily_features`` columns across a date-by-code matrix.
86
+
87
+ Produces values matching ``alphasift.daily.compute_daily_features(pack.history(code))``
88
+ while handling per-stock listing gaps and suspension ``NaN``s via right-aligned
89
+ valid-bar compaction.
90
+ """
91
+ code_arr = np.asarray(codes, dtype=str)
92
+ close_full = np.asarray(matrices["close"], dtype=np.float64)
93
+ total_dates = close_full.shape[0]
94
+ if total_dates == 0 or len(code_arr) == 0:
95
+ return pd.DataFrame(columns=_FEATURE_COLUMNS)
96
+
97
+ if as_of_index is not None:
98
+ end_idx = as_of_index + 1 if as_of_index >= 0 else total_dates + as_of_index + 1
99
+ if end_idx <= 0 or end_idx > total_dates:
100
+ raise IndexError(f"as_of_index {as_of_index} out of range for {total_dates} sessions")
101
+ else:
102
+ end_idx = total_dates
103
+
104
+ if selected_codes is not None:
105
+ norm_selected = list(dict.fromkeys(_normalize_pack_code(item) for item in selected_codes if item is not None))
106
+ col_indices: list[int] = []
107
+ matched_codes: list[str] = []
108
+ for item in norm_selected:
109
+ if not item:
110
+ continue
111
+ pos = int(np.searchsorted(code_arr, item))
112
+ if pos < len(code_arr) and code_arr[pos] == item:
113
+ col_indices.append(pos)
114
+ matched_codes.append(item)
115
+ if not col_indices:
116
+ return pd.DataFrame(columns=_FEATURE_COLUMNS)
117
+ col_idx_arr = np.asarray(col_indices, dtype=np.intp)
118
+ target_codes = np.asarray(matched_codes, dtype=str)
119
+ else:
120
+ col_idx_arr = np.arange(len(code_arr), dtype=np.intp)
121
+ target_codes = code_arr
122
+
123
+ close_raw = close_full[:end_idx, col_idx_arr]
124
+ valid = np.isfinite(close_raw)
125
+ counts = valid.sum(axis=0).astype(np.int64)
126
+ active_mask = counts > 0
127
+ if not active_mask.any():
128
+ return pd.DataFrame(columns=_FEATURE_COLUMNS)
129
+
130
+ active_cols = col_idx_arr[active_mask]
131
+ active_codes = target_codes[active_mask]
132
+ k = counts[active_mask]
133
+ t_max = int(k.max())
134
+ m = len(active_codes)
135
+
136
+ valid_active = valid[:, active_mask]
137
+ order = np.argsort(valid_active, axis=0, kind="stable")[-t_max:, :]
138
+ close = np.take_along_axis(close_raw[:, active_mask], order, axis=0)
139
+
140
+ row_pos = np.arange(t_max, dtype=np.int64)[:, None]
141
+ start_row = t_max - k
142
+ is_valid_row = row_pos >= start_row[None, :]
143
+
144
+ def _compact_price(field: str) -> np.ndarray:
145
+ if field not in matrices:
146
+ return close.copy()
147
+ arr = np.asarray(matrices[field][:end_idx, active_cols], dtype=np.float64)
148
+ compacted = np.take_along_axis(arr, order, axis=0)
149
+ return np.where(is_valid_row & ~np.isfinite(compacted), close, compacted)
150
+
151
+ open_ = _compact_price("open")
152
+ high = _compact_price("high")
153
+ low = _compact_price("low")
154
+
155
+ has_volume = "volume" in matrices
156
+ if has_volume:
157
+ vol_raw = np.asarray(matrices["volume"][:end_idx, active_cols], dtype=np.float64)
158
+ volume = np.take_along_axis(vol_raw, order, axis=0)
159
+ else:
160
+ volume = np.full((t_max, m), np.nan, dtype=np.float64)
161
+
162
+ last_close = close[-1]
163
+ last_open = open_[-1]
164
+
165
+ # Moving averages
166
+ def _trailing_mean(window: int) -> tuple[np.ndarray, np.ndarray]:
167
+ ok = k >= window
168
+ vals = np.full(m, np.nan, dtype=np.float64)
169
+ if t_max >= window and ok.any():
170
+ vals[ok] = np.round(close[-window:, ok].mean(axis=0), 4)
171
+ return vals, ok
172
+
173
+ ma5_vals, ma5_ok = _trailing_mean(5)
174
+ ma20_vals, ma20_ok = _trailing_mean(20)
175
+ ma60_vals, ma60_ok = _trailing_mean(60)
176
+
177
+ # 60-day change: base row is max(0, len - 61) per stock
178
+ base_rows = np.maximum(start_row, t_max - 61)
179
+ base_close = close[base_rows, np.arange(m)]
180
+ change60_ok = np.isfinite(base_close) & (base_close > 0)
181
+ change_60d_raw = np.full(m, np.nan, dtype=np.float64)
182
+ change_60d_raw[change60_ok] = (last_close[change60_ok] / base_close[change60_ok] - 1.0) * 100.0
183
+
184
+ ma_bullish = ma5_ok & ma20_ok & ma60_ok & (ma5_vals >= ma20_vals) & (ma20_vals >= ma60_vals)
185
+ price_above_ma20 = ma20_ok & (last_close >= ma20_vals)
186
+
187
+ # MACD (vectorized across columns with >= 35 valid bars)
188
+ macd_status = np.full(m, "neutral", dtype=object)
189
+ macd_mask = k >= 35
190
+ if macd_mask.any():
191
+ sub_c = close[:, macd_mask]
192
+ sub_start = start_row[macd_mask]
193
+ min_start = int(sub_start.min())
194
+ n_macd = sub_c.shape[1]
195
+ ema12 = np.zeros(n_macd, dtype=np.float64)
196
+ ema26 = np.zeros(n_macd, dtype=np.float64)
197
+ dea = np.zeros(n_macd, dtype=np.float64)
198
+ diff = np.zeros(n_macd, dtype=np.float64)
199
+ for t in range(min_start, t_max):
200
+ init = sub_start == t
201
+ step = t > sub_start
202
+ if init.any():
203
+ c_t = sub_c[t]
204
+ ema12 = np.where(init, c_t, ema12)
205
+ ema26 = np.where(init, c_t, ema26)
206
+ dea = np.where(init, 0.0, dea)
207
+ if step.any():
208
+ c_t = sub_c[t]
209
+ ema12 = np.where(step, _EMA12_ALPHA * c_t + (1.0 - _EMA12_ALPHA) * ema12, ema12)
210
+ ema26 = np.where(step, _EMA26_ALPHA * c_t + (1.0 - _EMA26_ALPHA) * ema26, ema26)
211
+ diff = ema12 - ema26
212
+ dea = np.where(step, _EMA9_ALPHA * diff + (1.0 - _EMA9_ALPHA) * dea, dea)
213
+ sub_status = np.where(
214
+ (diff > dea) & (diff > 0),
215
+ "bullish",
216
+ np.where((diff < dea) & (diff < 0), "bearish", "neutral"),
217
+ )
218
+ macd_status[macd_mask] = sub_status
219
+
220
+ # RSI(14)
221
+ rsi_raw = np.full(m, np.nan, dtype=np.float64)
222
+ rsi_status = np.full(m, "neutral", dtype=object)
223
+ if t_max >= 15:
224
+ rsi_elig = k > 14
225
+ if rsi_elig.any():
226
+ diffs = np.diff(close[-15:, rsi_elig], axis=0)
227
+ gain = np.clip(diffs, 0.0, None).mean(axis=0)
228
+ loss = np.clip(-diffs, 0.0, None).mean(axis=0)
229
+ valid_loss = loss > 0
230
+ sub_rsi = np.full(rsi_elig.sum(), np.nan, dtype=np.float64)
231
+ sub_rsi[valid_loss] = 100.0 - (100.0 / (1.0 + gain[valid_loss] / loss[valid_loss]))
232
+ rsi_raw[rsi_elig] = sub_rsi
233
+ sub_status = np.where(
234
+ np.isfinite(sub_rsi) & (sub_rsi <= 35.0),
235
+ "oversold",
236
+ np.where(np.isfinite(sub_rsi) & (sub_rsi >= 70.0), "overbought", "neutral"),
237
+ )
238
+ rsi_status[rsi_elig] = sub_status
239
+ rsi_ok = np.isfinite(rsi_raw)
240
+
241
+ # Signal score
242
+ signal_score = np.full(m, 50.0, dtype=np.float64)
243
+ signal_score += np.where(ma_bullish, 14.0, 0.0)
244
+ signal_score += np.where(price_above_ma20, 10.0, 0.0)
245
+ signal_score += np.where(macd_status == "bullish", 12.0, np.where(macd_status == "bearish", -12.0, 0.0))
246
+ c60 = np.where(change60_ok, change_60d_raw, 0.0)
247
+ signal_score += np.where(
248
+ change60_ok & (c60 >= 0.0) & (c60 <= 35.0),
249
+ np.minimum(c60 * 0.35, 12.0),
250
+ np.where(
251
+ change60_ok & (c60 > 60.0),
252
+ -np.minimum((c60 - 60.0) * 0.20, 12.0),
253
+ np.where(change60_ok & (c60 < -25.0), -np.minimum(np.abs(c60 + 25.0) * 0.25, 10.0), 0.0),
254
+ ),
255
+ )
256
+ signal_score += np.where(rsi_status == "oversold", 4.0, np.where(rsi_status == "overbought", -6.0, 0.0))
257
+ signal_score = np.round(np.clip(signal_score, 0.0, 100.0), 4)
258
+
259
+ # Shape features
260
+ prev_high_20d_raw = np.full(m, np.nan, dtype=np.float64)
261
+ prev_ok = k >= 2
262
+ if t_max >= 2 and prev_ok.any():
263
+ prev_h_slice = high[max(0, t_max - 21) : t_max - 1, prev_ok]
264
+ prev_high_20d_raw[prev_ok] = np.nanmax(prev_h_slice, axis=0)
265
+ prev_high_ok = np.isfinite(prev_high_20d_raw)
266
+
267
+ breakout_ok = prev_high_ok & (prev_high_20d_raw > 0)
268
+ breakout_20d_raw = np.full(m, np.nan, dtype=np.float64)
269
+ breakout_20d_raw[breakout_ok] = (last_close[breakout_ok] / prev_high_20d_raw[breakout_ok] - 1.0) * 100.0
270
+
271
+ recent_h = high[-20:, :]
272
+ recent_l = low[-20:, :]
273
+ recent_h_max = np.nanmax(recent_h, axis=0)
274
+ recent_l_min = np.nanmin(recent_l, axis=0)
275
+ range_ok = np.isfinite(recent_h_max) & np.isfinite(recent_l_min) & (recent_l_min > 0)
276
+ range_20d_raw = np.full(m, np.nan, dtype=np.float64)
277
+ range_20d_raw[range_ok] = (recent_h_max[range_ok] / recent_l_min[range_ok] - 1.0) * 100.0
278
+
279
+ # Volume ratio 20d
280
+ vol_ratio_raw = np.full(m, np.nan, dtype=np.float64)
281
+ if has_volume and t_max >= 2:
282
+ last_vol = volume[-1]
283
+ vol_prev = volume[max(0, t_max - 21) : t_max - 1, :]
284
+ vol_prev_valid = np.isfinite(vol_prev)
285
+ vol_prev_cnt = vol_prev_valid.sum(axis=0)
286
+ vol_prev_sum = np.where(vol_prev_valid, vol_prev, 0.0).sum(axis=0)
287
+ vol_base = np.where(vol_prev_cnt > 0, vol_prev_sum / np.maximum(vol_prev_cnt, 1), np.nan)
288
+ vr_ok = prev_ok & np.isfinite(last_vol) & (vol_prev_cnt > 0) & (vol_base > 0)
289
+ vol_ratio_raw[vr_ok] = last_vol[vr_ok] / vol_base[vr_ok]
290
+ vol_ratio_ok = np.isfinite(vol_ratio_raw)
291
+
292
+ body_ok = np.isfinite(last_open) & (last_open > 0) & np.isfinite(last_close)
293
+ body_pct_raw = np.full(m, np.nan, dtype=np.float64)
294
+ body_pct_raw[body_ok] = (last_close[body_ok] / last_open[body_ok] - 1.0) * 100.0
295
+
296
+ pullback_ok = ma20_ok & (ma20_vals > 0)
297
+ pullback_raw = np.full(m, np.nan, dtype=np.float64)
298
+ pullback_raw[pullback_ok] = (last_close[pullback_ok] / ma20_vals[pullback_ok] - 1.0) * 100.0
299
+
300
+ # Consolidation days (20d)
301
+ consol_days: list[int | None] = [None] * m
302
+ if t_max >= 2 and prev_ok.any():
303
+ prev_len = np.minimum(k - 1, 20)
304
+ prev_h_all = high[max(0, t_max - 21) : t_max - 1, :]
305
+ prev_l_all = low[max(0, t_max - 21) : t_max - 1, :]
306
+ found_days = np.zeros(m, dtype=np.int64)
307
+ max_win = min(20, prev_h_all.shape[0])
308
+ for d in range(max_win, 1, -1):
309
+ elig = (found_days == 0) & (prev_len >= d)
310
+ if not elig.any():
311
+ continue
312
+ win_h = prev_h_all[-d:, elig].max(axis=0)
313
+ win_l = prev_l_all[-d:, elig].min(axis=0)
314
+ ok_d = (win_l > 0) & (((win_h / win_l - 1.0) * 100.0) <= 12.0)
315
+ if ok_d.any():
316
+ elig_idx = np.flatnonzero(elig)[ok_d]
317
+ found_days[elig_idx] = d
318
+ for idx in np.flatnonzero(prev_ok):
319
+ consol_days[int(idx)] = int(found_days[idx])
320
+
321
+ # Volatility 20d (requires >= 3 close bars => >= 2 returns)
322
+ vol20_raw = np.full(m, np.nan, dtype=np.float64)
323
+ if t_max >= 3:
324
+ c20 = close[-20:, :]
325
+ ret = (c20[1:, :] / c20[:-1, :]) - 1.0
326
+ ret_valid = np.isfinite(ret)
327
+ ret_cnt = ret_valid.sum(axis=0)
328
+ vol_elig = ret_cnt >= 2
329
+ if vol_elig.any():
330
+ sub_ret = ret[:, vol_elig]
331
+ sub_valid = ret_valid[:, vol_elig]
332
+ sub_cnt = ret_cnt[vol_elig]
333
+ mean_ret = np.where(sub_valid, sub_ret, 0.0).sum(axis=0) / sub_cnt
334
+ sq_diff = np.where(sub_valid, (sub_ret - mean_ret[None, :]) ** 2, 0.0).sum(axis=0)
335
+ std_ret = np.sqrt(sq_diff / (sub_cnt - 1))
336
+ vol20_raw[vol_elig] = std_ret * (252.0 ** 0.5) * 100.0
337
+ vol20_ok = np.isfinite(vol20_raw)
338
+
339
+ # Max drawdown 20d
340
+ c20 = close[-20:, :]
341
+ c20_valid = np.isfinite(c20)
342
+ running_high = np.maximum.accumulate(np.where(c20_valid, c20, -np.inf), axis=0)
343
+ dd20 = np.where(c20_valid & (running_high > 0), c20 / running_high - 1.0, 0.0)
344
+ mdd_raw = np.minimum(dd20.min(axis=0) * 100.0, 0.0)
345
+ mdd_ok = np.isfinite(mdd_raw)
346
+
347
+ # ATR 20 pct
348
+ prev_c_full = np.empty_like(close)
349
+ prev_c_full[0, :] = np.nan
350
+ if t_max > 1:
351
+ prev_c_full[1:, :] = close[:-1, :]
352
+ tr = np.fmax(high - low, np.fmax(np.abs(high - prev_c_full), np.abs(low - prev_c_full)))
353
+ tr20 = tr[-20:, :]
354
+ tr_valid = np.isfinite(tr20)
355
+ tr_cnt = tr_valid.sum(axis=0)
356
+ atr_ok = (tr_cnt > 0) & (last_close > 0)
357
+ atr_raw = np.full(m, np.nan, dtype=np.float64)
358
+ if atr_ok.any():
359
+ atr_mean = np.where(tr_valid[:, atr_ok], tr20[:, atr_ok], 0.0).sum(axis=0) / tr_cnt[atr_ok]
360
+ atr_raw[atr_ok] = atr_mean / last_close[atr_ok] * 100.0
361
+ atr_ok = np.isfinite(atr_raw)
362
+
363
+ # Quality score & flags
364
+ q_scores = np.full(m, 100.0, dtype=np.float64)
365
+ q_flags: list[list[str]] = [[] for _ in range(m)]
366
+ for idx in np.flatnonzero(k < 30):
367
+ q_scores[idx] -= 35.0
368
+ q_flags[int(idx)].append("short_history_lt30")
369
+ for idx in np.flatnonzero((k >= 30) & (k < 60)):
370
+ q_scores[idx] -= 15.0
371
+ q_flags[int(idx)].append("short_history_lt60")
372
+
373
+ if not has_volume:
374
+ q_scores -= 12.0
375
+ for flags in q_flags:
376
+ flags.append("missing_volume")
377
+ else:
378
+ missing_vol_ratio = (is_valid_row & ~np.isfinite(volume)).sum(axis=0) / k
379
+ for idx in np.flatnonzero(missing_vol_ratio > 0):
380
+ q_scores[idx] -= min(float(missing_vol_ratio[idx]) * 20.0, 10.0)
381
+ q_flags[int(idx)].append("incomplete_volume")
382
+ neg_vol = (is_valid_row & np.isfinite(volume) & (volume < 0)).any(axis=0)
383
+ for idx in np.flatnonzero(neg_vol):
384
+ q_scores[idx] -= 20.0
385
+ q_flags[int(idx)].append("negative_volume")
386
+
387
+ invalid_ohlc = (
388
+ is_valid_row
389
+ & ((high < low) | (high < open_) | (high < close) | (low > open_) | (low > close))
390
+ ).any(axis=0)
391
+ for idx in np.flatnonzero(invalid_ohlc):
392
+ q_scores[idx] -= 30.0
393
+ q_flags[int(idx)].append("invalid_ohlc")
394
+
395
+ non_pos = (
396
+ is_valid_row & ((open_ <= 0) | (high <= 0) | (low <= 0) | (close <= 0))
397
+ ).any(axis=0)
398
+ for idx in np.flatnonzero(non_pos):
399
+ q_scores[idx] -= 35.0
400
+ q_flags[int(idx)].append("non_positive_price")
401
+
402
+ q_scores = np.round(np.maximum(q_scores, 0.0), 4)
403
+ q_flag_strs = [";".join(flags) for flags in q_flags]
404
+
405
+ return pd.DataFrame({
406
+ "code": active_codes.tolist(),
407
+ "daily_data_points": k.tolist(),
408
+ "change_60d": _round_array(change_60d_raw, change60_ok),
409
+ "ma5": [float(v) if ok else None for v, ok in zip(ma5_vals, ma5_ok)],
410
+ "ma20": [float(v) if ok else None for v, ok in zip(ma20_vals, ma20_ok)],
411
+ "ma60": [float(v) if ok else None for v, ok in zip(ma60_vals, ma60_ok)],
412
+ "ma_bullish": ma_bullish.tolist(),
413
+ "price_above_ma20": price_above_ma20.tolist(),
414
+ "macd_status": macd_status.tolist(),
415
+ "rsi_status": rsi_status.tolist(),
416
+ "rsi14": _round_array(rsi_raw, rsi_ok),
417
+ "signal_score": signal_score.tolist(),
418
+ "prev_high_20d": _round_array(prev_high_20d_raw, prev_high_ok),
419
+ "range_20d_pct": _round_array(range_20d_raw, range_ok),
420
+ "breakout_20d_pct": _round_array(breakout_20d_raw, breakout_ok),
421
+ "volume_ratio_20d": _round_array(vol_ratio_raw, vol_ratio_ok),
422
+ "body_pct": _round_array(body_pct_raw, body_ok),
423
+ "pullback_to_ma20_pct": _round_array(pullback_raw, pullback_ok),
424
+ "consolidation_days_20d": consol_days,
425
+ "volatility_20d_pct": _round_array(vol20_raw, vol20_ok),
426
+ "max_drawdown_20d_pct": _round_array(mdd_raw, mdd_ok),
427
+ "atr_20_pct": _round_array(atr_raw, atr_ok),
428
+ "daily_quality_score": q_scores.tolist(),
429
+ "daily_quality_flags": q_flag_strs,
430
+ "daily_source": ["pack"] * m,
431
+ })