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/patterns.py ADDED
@@ -0,0 +1,1233 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Stateless CN daily-matrix pattern engine with strict schema validation.
3
+
4
+ All patterns operate on CN A-share DailyPack matrices via atomic vectorized
5
+ operators and stateless observe/confirm lookback (no persistent state machine).
6
+ ``overhead_supply_10pct`` is attached as an observation feature only and never
7
+ acts as a hard veto.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+ from dataclasses import asdict, dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ import yaml
20
+
21
+ from alphasift.market_regime import (
22
+ MarketRegimeSnapshot,
23
+ compute_limit_masks,
24
+ compute_market_regime,
25
+ )
26
+ from alphasift.normalize import normalize_code
27
+ from alphasift.pack import DailyPack, forward_adjust
28
+
29
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent
30
+ _BUNDLED_PATTERNS_DIR = Path(__file__).resolve().parent / "patterns"
31
+
32
+ VALID_FAMILIES = frozenset({"bottom_reversal", "trend_continuation", "breakout"})
33
+ VALID_STATUSES = frozenset({"active", "experimental"})
34
+ VALID_MODES = frozenset({"direct", "observe_confirm"})
35
+
36
+ _TOP_LEVEL_KEYS = {
37
+ "name",
38
+ "display_name",
39
+ "family",
40
+ "status",
41
+ "version",
42
+ "description",
43
+ "aligned_strategy",
44
+ "tags",
45
+ "market_scope",
46
+ "min_history_days",
47
+ "cooldown_days",
48
+ "universe",
49
+ "mode",
50
+ "conditions",
51
+ "observe",
52
+ "confirm",
53
+ "lookback_days",
54
+ "min_wait_days",
55
+ "invalidation",
56
+ }
57
+ _UNIVERSE_KEYS = {
58
+ "exclude_st",
59
+ "exclude_one_price_limit_up",
60
+ "proxy_amount_min",
61
+ "close_min",
62
+ }
63
+ _CONDITION_KEYS = {"feature", "min", "max", "equals", "lag", "params"}
64
+ _INVALIDATION_KEYS = {"rule", "tolerance_atr"}
65
+ _INVALIDATION_RULES = {
66
+ "none",
67
+ "close_below_observe_low",
68
+ "low_below_observe_low",
69
+ "close_below_observe_open",
70
+ "close_below_observe_mid",
71
+ }
72
+
73
+ _STATIC_FEATURES = {
74
+ "valid_bars",
75
+ "valid_streak",
76
+ "bull_streak",
77
+ "close_higher_streak",
78
+ "open_in_prev_body",
79
+ "body_ratio_vs_prev",
80
+ "is_bull_bar",
81
+ "is_bear_bar",
82
+ "is_limit_up",
83
+ "not_one_price_limit_up",
84
+ "ma_bullish",
85
+ "ma20_above_ma60",
86
+ "price_above_ma20",
87
+ "price_above_ma60",
88
+ "prev_close_above_ma20",
89
+ "ma20_slope_5d_pct",
90
+ "pos_in_60d",
91
+ "drawdown_from_60d_high_pct",
92
+ "prior_60d_decline_pct",
93
+ "change_pct",
94
+ "ret_limit_ratio",
95
+ "ret_3d_limit_ratio",
96
+ "body_pct",
97
+ "body_atr",
98
+ "body_limit_ratio",
99
+ "bar_range_atr",
100
+ "upper_shadow_atr",
101
+ "lower_shadow_atr",
102
+ "upper_shadow_to_range",
103
+ "close_pos_in_bar",
104
+ "atr20_pct",
105
+ "vol_ratio_1d",
106
+ "vol_ratio_5d",
107
+ "vol_ratio_20d",
108
+ "prev_range_20d_pct",
109
+ "prev_range_20d_atr",
110
+ "breakout_20d_pct",
111
+ "breakout_20d_atr",
112
+ "prev_below_prev_high_20d",
113
+ "pullback_to_ma20_pct",
114
+ "pullback_to_ma20_atr",
115
+ "low_to_ma20_atr",
116
+ "double_bottom_neckline_breakout",
117
+ }
118
+ _OBSERVE_RELATIVE_FEATURES = {
119
+ "close_above_observe_high",
120
+ "close_above_observe_close",
121
+ "close_above_observe_mid",
122
+ "hold_above_observe_low",
123
+ "volume_below_observe_ratio",
124
+ "range_ratio_vs_observe",
125
+ }
126
+ _ALL_FEATURES = _STATIC_FEATURES | _OBSERVE_RELATIVE_FEATURES
127
+
128
+
129
+ @dataclass
130
+ class PatternSpec:
131
+ """Validated pattern definition loaded from YAML."""
132
+
133
+ name: str
134
+ display_name: str
135
+ family: str
136
+ status: str
137
+ version: str
138
+ description: str
139
+ mode: str
140
+ market_scope: tuple[str, ...] = ("cn",)
141
+ aligned_strategy: str | None = None
142
+ tags: tuple[str, ...] = ()
143
+ min_history_days: int = 60
144
+ universe: dict[str, Any] = field(default_factory=dict)
145
+ conditions: list[dict[str, Any]] = field(default_factory=list)
146
+ observe: list[dict[str, Any]] = field(default_factory=list)
147
+ confirm: list[dict[str, Any]] = field(default_factory=list)
148
+ lookback_days: int = 5
149
+ min_wait_days: int = 1
150
+ invalidation: dict[str, Any] = field(default_factory=lambda: {"rule": "none", "tolerance_atr": 0.0})
151
+ cooldown_days: int = 0
152
+
153
+
154
+ @dataclass
155
+ class PatternSignal:
156
+ """Single point-in-time CN pattern match."""
157
+
158
+ pattern: str
159
+ display_name: str
160
+ family: str
161
+ status: str
162
+ code: str
163
+ name: str
164
+ industry: str
165
+ trade_date: str
166
+ close: float
167
+ change_pct: float
168
+ proxy_amount: float | None
169
+ atr20_pct: float | None
170
+ vol_ratio_20d: float | None
171
+ overhead_supply_10pct: float | None
172
+ observe_date: str | None = None
173
+ observe_lag_days: int | None = None
174
+ aligned_strategy: str | None = None
175
+
176
+ def to_dict(self) -> dict[str, Any]:
177
+ return asdict(self)
178
+
179
+
180
+ @dataclass
181
+ class PatternScanResult:
182
+ """Scan output across one or more patterns for a single CN session."""
183
+
184
+ trade_date: str
185
+ pack_trade_date: str
186
+ universe_count: int
187
+ patterns_evaluated: list[str]
188
+ market_regime: MarketRegimeSnapshot
189
+ signals_by_pattern: dict[str, list[PatternSignal]]
190
+ counts_by_pattern: dict[str, int]
191
+ usage_policy: str = "cn_only_regime_slice_only"
192
+
193
+ def to_dict(self) -> dict[str, Any]:
194
+ return {
195
+ "trade_date": self.trade_date,
196
+ "pack_trade_date": self.pack_trade_date,
197
+ "universe_count": self.universe_count,
198
+ "patterns_evaluated": list(self.patterns_evaluated),
199
+ "market_regime": self.market_regime.to_dict(),
200
+ "counts_by_pattern": dict(self.counts_by_pattern),
201
+ "signals_by_pattern": {
202
+ name: [sig.to_dict() for sig in items]
203
+ for name, items in self.signals_by_pattern.items()
204
+ },
205
+ "usage_policy": self.usage_policy,
206
+ }
207
+
208
+
209
+ @dataclass
210
+ class PatternMatrixContext:
211
+ """Precomputed vectorized (T, N) feature matrices for CN pattern matching."""
212
+
213
+ dates: np.ndarray
214
+ codes: np.ndarray
215
+ names: np.ndarray
216
+ industries: np.ndarray
217
+ valid: np.ndarray
218
+ valid_count: np.ndarray
219
+ open: np.ndarray
220
+ high: np.ndarray
221
+ low: np.ndarray
222
+ close: np.ndarray
223
+ raw_close: np.ndarray
224
+ volume: np.ndarray
225
+ proxy_amount: np.ndarray
226
+ is_st: np.ndarray
227
+ is_one_price_limit_up: np.ndarray
228
+ limit_pct: np.ndarray
229
+ features: dict[str, np.ndarray]
230
+ double_bottom_cache: dict[tuple[tuple[str, Any], ...], np.ndarray] = field(default_factory=dict)
231
+
232
+
233
+ def _validate_pattern_dir_sync(patterns_dir: Path) -> None:
234
+ resolved = patterns_dir.resolve()
235
+ repo_dir = (_PROJECT_ROOT / "patterns").resolve()
236
+ bundled_dir = _BUNDLED_PATTERNS_DIR.resolve()
237
+ if resolved != repo_dir or not bundled_dir.is_dir():
238
+ return
239
+ repo_files = {f.name: f for f in repo_dir.glob("*.yaml")}
240
+ bundled_files = {f.name: f for f in bundled_dir.glob("*.yaml")}
241
+ missing_from_repo = bundled_files.keys() - repo_files.keys()
242
+ if missing_from_repo:
243
+ raise RuntimeError(
244
+ "Pattern directories are out of sync: bundled patterns are missing from "
245
+ f"patterns/: {', '.join(sorted(missing_from_repo))}."
246
+ )
247
+ for name, bundled_file in bundled_files.items():
248
+ if repo_files[name].read_bytes() != bundled_file.read_bytes():
249
+ raise RuntimeError(
250
+ f"Pattern directories are out of sync: patterns/{name} does not match alphasift/patterns/{name}."
251
+ )
252
+
253
+
254
+ def _resolve_patterns_dir(patterns_dir: Path | None) -> Path:
255
+ if patterns_dir is not None:
256
+ resolved = Path(patterns_dir)
257
+ _validate_pattern_dir_sync(resolved)
258
+ return resolved
259
+ repo_dir = _PROJECT_ROOT / "patterns"
260
+ if repo_dir.is_dir():
261
+ _validate_pattern_dir_sync(repo_dir)
262
+ return repo_dir
263
+ if _BUNDLED_PATTERNS_DIR.is_dir():
264
+ return _BUNDLED_PATTERNS_DIR
265
+ raise FileNotFoundError("Pattern directory not found")
266
+
267
+
268
+ def _validate_condition_list(
269
+ items: Any,
270
+ *,
271
+ section: str,
272
+ filepath: Path,
273
+ allow_observe_relative: bool,
274
+ ) -> list[dict[str, Any]]:
275
+ if items is None:
276
+ return []
277
+ if not isinstance(items, list):
278
+ raise ValueError(f"Expected list for {section} in {filepath.name}")
279
+ allowed_feats = _ALL_FEATURES if allow_observe_relative else _STATIC_FEATURES
280
+ validated: list[dict[str, Any]] = []
281
+ for idx, entry in enumerate(items):
282
+ if not isinstance(entry, dict):
283
+ raise ValueError(f"Condition #{idx} in {section} of {filepath.name} must be a mapping")
284
+ unknown = sorted(set(entry.keys()) - _CONDITION_KEYS)
285
+ if unknown:
286
+ raise ValueError(f"Unknown keys in {section}[{idx}] of {filepath.name}: {', '.join(unknown)}")
287
+ feat = entry.get("feature")
288
+ if not isinstance(feat, str) or feat not in allowed_feats:
289
+ raise ValueError(f"Invalid or disallowed feature {feat!r} in {section}[{idx}] of {filepath.name}")
290
+ has_bound = any(k in entry for k in ("min", "max", "equals"))
291
+ if not has_bound:
292
+ raise ValueError(f"Condition {feat!r} in {section}[{idx}] of {filepath.name} needs min/max/equals")
293
+ lag = entry.get("lag")
294
+ if lag is not None and (not isinstance(lag, int) or isinstance(lag, bool) or lag < 0 or lag > 10):
295
+ raise ValueError(f"lag in {section}[{idx}] of {filepath.name} must be an int in 0..10")
296
+ params = entry.get("params")
297
+ if params is not None and not isinstance(params, dict):
298
+ raise ValueError(f"params in {section}[{idx}] of {filepath.name} must be a mapping")
299
+ validated.append(dict(entry))
300
+ return validated
301
+
302
+
303
+ def load_pattern(name_or_path: str | Path, *, patterns_dir: Path | None = None) -> PatternSpec:
304
+ """Load and strictly validate a pattern YAML file."""
305
+ candidate = Path(name_or_path)
306
+ if candidate.is_file():
307
+ filepath = candidate
308
+ else:
309
+ directory = _resolve_patterns_dir(patterns_dir)
310
+ stem = str(name_or_path).removesuffix(".yaml")
311
+ filepath = directory / f"{stem}.yaml"
312
+ if not filepath.is_file():
313
+ raise FileNotFoundError(f"Pattern YAML not found: {filepath}")
314
+
315
+ data = yaml.safe_load(filepath.read_text(encoding="utf-8"))
316
+ if not isinstance(data, dict):
317
+ raise ValueError(f"Pattern YAML {filepath.name} must be a mapping")
318
+
319
+ unknown = sorted(set(data.keys()) - _TOP_LEVEL_KEYS)
320
+ if unknown:
321
+ raise ValueError(f"Unknown top-level keys in {filepath.name}: {', '.join(unknown)}")
322
+
323
+ name = str(data.get("name") or filepath.stem).strip()
324
+ display_name = str(data.get("display_name") or name).strip()
325
+ family = str(data.get("family") or "").strip()
326
+ if family not in VALID_FAMILIES:
327
+ raise ValueError(
328
+ f"Invalid family {family!r} in {filepath.name}; expected one of {sorted(VALID_FAMILIES)}"
329
+ )
330
+ status = str(data.get("status") or "experimental").strip()
331
+ if status not in VALID_STATUSES:
332
+ raise ValueError(
333
+ f"Invalid status {status!r} in {filepath.name}; expected one of {sorted(VALID_STATUSES)}"
334
+ )
335
+ mode = str(data.get("mode") or "direct").strip()
336
+ if mode not in VALID_MODES:
337
+ raise ValueError(
338
+ f"Invalid mode {mode!r} in {filepath.name}; expected one of {sorted(VALID_MODES)}"
339
+ )
340
+
341
+ scope_raw = data.get("market_scope", ["cn"])
342
+ if not isinstance(scope_raw, list) or [str(x).lower() for x in scope_raw] != ["cn"]:
343
+ raise ValueError(f"Pattern {filepath.name} market_scope must be ['cn']")
344
+
345
+ min_hist = int(data.get("min_history_days", 60))
346
+ if min_hist < 2:
347
+ raise ValueError(f"min_history_days must be >= 2 in {filepath.name}")
348
+ cooldown_days = int(data.get("cooldown_days", 0))
349
+ if cooldown_days < 0 or cooldown_days > 20:
350
+ raise ValueError(f"cooldown_days must be in 0..20 in {filepath.name}")
351
+
352
+ universe = data.get("universe") or {}
353
+ if not isinstance(universe, dict):
354
+ raise ValueError(f"universe must be a mapping in {filepath.name}")
355
+ unknown_uni = sorted(set(universe.keys()) - _UNIVERSE_KEYS)
356
+ if unknown_uni:
357
+ raise ValueError(f"Unknown universe keys in {filepath.name}: {', '.join(unknown_uni)}")
358
+
359
+ inv = data.get("invalidation") or {"rule": "none", "tolerance_atr": 0.0}
360
+ if not isinstance(inv, dict):
361
+ raise ValueError(f"invalidation must be a mapping in {filepath.name}")
362
+ unknown_inv = sorted(set(inv.keys()) - _INVALIDATION_KEYS)
363
+ if unknown_inv:
364
+ raise ValueError(f"Unknown invalidation keys in {filepath.name}: {', '.join(unknown_inv)}")
365
+ inv_rule = str(inv.get("rule", "none"))
366
+ if inv_rule not in _INVALIDATION_RULES:
367
+ raise ValueError(f"Invalid invalidation rule {inv_rule!r} in {filepath.name}")
368
+
369
+ conditions = _validate_condition_list(
370
+ data.get("conditions"), section="conditions", filepath=filepath, allow_observe_relative=False
371
+ )
372
+ observe = _validate_condition_list(
373
+ data.get("observe"), section="observe", filepath=filepath, allow_observe_relative=False
374
+ )
375
+ confirm = _validate_condition_list(
376
+ data.get("confirm"), section="confirm", filepath=filepath, allow_observe_relative=True
377
+ )
378
+
379
+ lookback_days = int(data.get("lookback_days", 5))
380
+ min_wait_days = int(data.get("min_wait_days", 1))
381
+ if mode == "direct":
382
+ if not conditions:
383
+ raise ValueError(f"Direct pattern {filepath.name} must define conditions")
384
+ if observe or confirm:
385
+ raise ValueError(f"Direct pattern {filepath.name} must not define observe/confirm")
386
+ else:
387
+ if not observe or not confirm:
388
+ raise ValueError(f"observe_confirm pattern {filepath.name} must define both observe and confirm")
389
+ if conditions:
390
+ raise ValueError(f"observe_confirm pattern {filepath.name} must not define top-level conditions")
391
+ if min_wait_days < 1 or lookback_days < min_wait_days or lookback_days > 20:
392
+ raise ValueError(
393
+ f"Invalid wait window ({min_wait_days}..{lookback_days}) in {filepath.name}"
394
+ )
395
+
396
+ aligned = data.get("aligned_strategy")
397
+ return PatternSpec(
398
+ name=name,
399
+ display_name=display_name,
400
+ family=family,
401
+ status=status,
402
+ version=str(data.get("version", "1.0")),
403
+ description=str(data.get("description", "")).strip(),
404
+ mode=mode,
405
+ market_scope=("cn",),
406
+ aligned_strategy=str(aligned).strip() if aligned else None,
407
+ tags=tuple(str(t).strip() for t in (data.get("tags") or [])),
408
+ min_history_days=min_hist,
409
+ universe=dict(universe),
410
+ conditions=conditions,
411
+ observe=observe,
412
+ confirm=confirm,
413
+ lookback_days=lookback_days,
414
+ min_wait_days=min_wait_days,
415
+ invalidation={"rule": inv_rule, "tolerance_atr": float(inv.get("tolerance_atr", 0.0))},
416
+ cooldown_days=cooldown_days,
417
+ )
418
+
419
+
420
+ def list_patterns(
421
+ *,
422
+ include_experimental: bool = True,
423
+ patterns_dir: Path | None = None,
424
+ ) -> list[PatternSpec]:
425
+ """List validated CN pattern specs sorted by family and name."""
426
+ directory = _resolve_patterns_dir(patterns_dir)
427
+ specs = [load_pattern(path, patterns_dir=directory) for path in sorted(directory.glob("*.yaml"))]
428
+ if not include_experimental:
429
+ specs = [spec for spec in specs if spec.status == "active"]
430
+ return specs
431
+
432
+
433
+ def _rolling_mean_valid(
434
+ arr: np.ndarray,
435
+ valid: np.ndarray,
436
+ window: int,
437
+ *,
438
+ min_valid: int | None = None,
439
+ ) -> np.ndarray:
440
+ t_len, n_codes = arr.shape
441
+ req = min_valid if min_valid is not None else max(1, int(np.ceil(window * 0.8)))
442
+ clean_val = np.where(valid, arr, 0.0)
443
+ clean_cnt = valid.astype(np.int64)
444
+
445
+ cs_val = np.zeros((t_len + 1, n_codes), dtype=np.float64)
446
+ cs_cnt = np.zeros((t_len + 1, n_codes), dtype=np.int64)
447
+ cs_val[1:] = np.cumsum(clean_val, axis=0)
448
+ cs_cnt[1:] = np.cumsum(clean_cnt, axis=0)
449
+
450
+ idx = np.arange(1, t_len + 1, dtype=np.intp)
451
+ lo = np.maximum(0, idx - window)
452
+ win_sum = cs_val[idx] - cs_val[lo]
453
+ win_cnt = cs_cnt[idx] - cs_cnt[lo]
454
+
455
+ out = np.full((t_len, n_codes), np.nan, dtype=np.float64)
456
+ ok = win_cnt >= req
457
+ out[ok] = win_sum[ok] / win_cnt[ok]
458
+ return out
459
+
460
+
461
+ def _shift_rows(arr: np.ndarray, lag: int = 1, fill: float = np.nan) -> np.ndarray:
462
+ out = np.full_like(arr, fill)
463
+ if lag < arr.shape[0]:
464
+ out[lag:] = arr[:-lag]
465
+ return out
466
+
467
+
468
+ def _rolling_extrema(
469
+ high: np.ndarray,
470
+ low: np.ndarray,
471
+ valid: np.ndarray,
472
+ window: int,
473
+ *,
474
+ strict_prior: bool = False,
475
+ min_valid: int | None = None,
476
+ ) -> tuple[np.ndarray, np.ndarray]:
477
+ t_len, n_codes = high.shape
478
+ req = min_valid if min_valid is not None else max(2, int(np.ceil(window * 0.75)))
479
+ hi_out = np.full((t_len, n_codes), np.nan, dtype=np.float64)
480
+ lo_out = np.full((t_len, n_codes), np.nan, dtype=np.float64)
481
+
482
+ h_pos = np.where(valid, high, -np.inf)
483
+ l_pos = np.where(valid, low, np.inf)
484
+ cs_cnt = np.zeros((t_len + 1, n_codes), dtype=np.int64)
485
+ cs_cnt[1:] = np.cumsum(valid, axis=0)
486
+
487
+ for t in range(t_len):
488
+ end = t if strict_prior else t + 1
489
+ start = max(0, end - window)
490
+ if end <= start:
491
+ continue
492
+ cnt = cs_cnt[end] - cs_cnt[start]
493
+ ok = cnt >= req
494
+ if not ok.any():
495
+ continue
496
+ hi_out[t, ok] = h_pos[start:end, ok].max(axis=0)
497
+ lo_out[t, ok] = l_pos[start:end, ok].min(axis=0)
498
+ return hi_out, lo_out
499
+
500
+
501
+ def build_pattern_context(
502
+ daily_pack: DailyPack,
503
+ *,
504
+ end_index: int | None = None,
505
+ ) -> PatternMatrixContext:
506
+ """Build point-in-time vectorized feature matrices from ``daily_pack``."""
507
+ total_dates = len(daily_pack.dates)
508
+ if end_index is not None:
509
+ end_idx = end_index + 1 if end_index >= 0 else total_dates + end_index + 1
510
+ if end_idx <= 0 or end_idx > total_dates:
511
+ raise IndexError(f"end_index {end_index} out of range for {total_dates} sessions")
512
+ # Slice strictly before forward_adjust so future splits never rescale past queries.
513
+ work_pack = DailyPack(
514
+ dates=daily_pack.dates[:end_idx],
515
+ codes=daily_pack.codes,
516
+ matrices={k: v[:end_idx] for k, v in daily_pack.matrices.items()},
517
+ meta=daily_pack.meta,
518
+ sources=daily_pack.sources,
519
+ manifest=daily_pack.manifest,
520
+ )
521
+ else:
522
+ work_pack = daily_pack
523
+
524
+ limit_masks = compute_limit_masks(work_pack)
525
+ adj = forward_adjust(work_pack)
526
+
527
+ dates = np.asarray(work_pack.dates, dtype=str)
528
+ codes = np.asarray(work_pack.codes, dtype=str)
529
+ t_len, n_codes = len(dates), len(codes)
530
+
531
+ name_map: dict[str, str] = {}
532
+ ind_map: dict[str, str] = {}
533
+ if work_pack.meta is not None and not work_pack.meta.empty and "code" in work_pack.meta.columns:
534
+ for row in work_pack.meta.itertuples(index=False):
535
+ c = normalize_code(getattr(row, "code", ""), allow_ticker=False)
536
+ if not c:
537
+ continue
538
+ nm = getattr(row, "name", "")
539
+ ind = getattr(row, "industry", "")
540
+ name_map[c] = "" if nm is None or pd.isna(nm) else str(nm)
541
+ ind_map[c] = "" if ind is None or pd.isna(ind) else str(ind)
542
+ names = np.asarray([name_map.get(normalize_code(c, allow_ticker=False) or c, "") for c in codes], dtype=object)
543
+ industries = np.asarray([ind_map.get(normalize_code(c, allow_ticker=False) or c, "") for c in codes], dtype=object)
544
+
545
+ open_ = np.asarray(adj["open"], dtype=np.float64)
546
+ high = np.asarray(adj["high"], dtype=np.float64)
547
+ low = np.asarray(adj["low"], dtype=np.float64)
548
+ close = np.asarray(adj["close"], dtype=np.float64)
549
+ raw_close = np.asarray(work_pack.matrices["close"], dtype=np.float64)
550
+ vol = np.asarray(work_pack.matrices["volume"], dtype=np.float64)
551
+
552
+ valid = (
553
+ np.isfinite(close) & (close > 0)
554
+ & np.isfinite(open_) & (open_ > 0)
555
+ & np.isfinite(high) & (high > 0)
556
+ & np.isfinite(low) & (low > 0)
557
+ & (~np.isfinite(vol) | (vol > 0))
558
+ )
559
+ valid_count = np.cumsum(valid, axis=0)
560
+
561
+ # Carry forward last valid close and volume (per stock, strictly backward-looking).
562
+ prev_valid_close = np.full((t_len, n_codes), np.nan, dtype=np.float64)
563
+ prev_valid_volume = np.full((t_len, n_codes), np.nan, dtype=np.float64)
564
+ last_c = np.full(n_codes, np.nan, dtype=np.float64)
565
+ last_v = np.full(n_codes, np.nan, dtype=np.float64)
566
+ vol_valid = valid & np.isfinite(vol) & (vol > 0)
567
+ for t in range(t_len):
568
+ prev_valid_close[t] = last_c
569
+ prev_valid_volume[t] = last_v
570
+ v_t = valid[t]
571
+ if v_t.any():
572
+ last_c = np.where(v_t, close[t], last_c)
573
+ vv_t = vol_valid[t]
574
+ if vv_t.any():
575
+ last_v = np.where(vv_t, vol[t], last_v)
576
+
577
+ ma5 = _rolling_mean_valid(close, valid, 5, min_valid=4)
578
+ ma10 = _rolling_mean_valid(close, valid, 10, min_valid=8)
579
+ ma20 = _rolling_mean_valid(close, valid, 20, min_valid=16)
580
+ ma60 = _rolling_mean_valid(close, valid, 60, min_valid=48)
581
+ ma20_lag1 = _shift_rows(ma20, 1)
582
+ ma20_lag5 = _shift_rows(ma20, 5)
583
+
584
+ vol_shift = _shift_rows(vol, 1)
585
+ vol_valid_shift = _shift_rows(vol_valid.astype(np.float64), 1, fill=0.0) > 0.5
586
+ vol_ma5_prev = _rolling_mean_valid(vol_shift, vol_valid_shift, 5, min_valid=3)
587
+ vol_ma20_prev = _rolling_mean_valid(vol_shift, vol_valid_shift, 20, min_valid=12)
588
+
589
+ tr = np.where(
590
+ valid,
591
+ np.fmax(
592
+ high - low,
593
+ np.fmax(np.abs(high - prev_valid_close), np.abs(low - prev_valid_close)),
594
+ ),
595
+ np.nan,
596
+ )
597
+ atr20 = _rolling_mean_valid(tr, valid & np.isfinite(tr), 20, min_valid=14)
598
+ atr_pos = np.where(np.isfinite(atr20) & (atr20 > 0), atr20, np.nan)
599
+
600
+ limit_pct = limit_masks["limit_pct"]
601
+ change_pct = (close / prev_valid_close - 1.0) * 100.0
602
+ ret_limit_ratio = (close / prev_valid_close - 1.0) / limit_pct[None, :]
603
+ body_pct = (close / open_ - 1.0) * 100.0
604
+ body_atr = (close - open_) / atr_pos
605
+ body_limit_ratio = (close / open_ - 1.0) / limit_pct[None, :]
606
+
607
+ bar_range = np.maximum(high - low, 0.0)
608
+ upper_shadow = np.maximum(high - np.maximum(open_, close), 0.0)
609
+ lower_shadow = np.maximum(np.minimum(open_, close) - low, 0.0)
610
+ bar_range_atr = bar_range / atr_pos
611
+ upper_shadow_atr = upper_shadow / atr_pos
612
+ lower_shadow_atr = lower_shadow / atr_pos
613
+ range_pos = valid & (bar_range > 0)
614
+ upper_shadow_to_range = np.divide(
615
+ upper_shadow, bar_range, out=np.zeros_like(bar_range), where=range_pos
616
+ )
617
+ close_pos_in_bar = np.divide(
618
+ close - low, bar_range, out=np.full_like(bar_range, 0.5), where=range_pos
619
+ )
620
+ atr20_pct = (atr_pos / close) * 100.0
621
+
622
+ vol_ratio_1d = np.divide(
623
+ vol, prev_valid_volume, out=np.full_like(vol, np.nan), where=vol_valid & (prev_valid_volume > 0)
624
+ )
625
+ vol_ratio_5d = np.divide(
626
+ vol, vol_ma5_prev, out=np.full_like(vol, np.nan), where=vol_valid & (vol_ma5_prev > 0)
627
+ )
628
+ vol_ratio_20d = np.divide(
629
+ vol, vol_ma20_prev, out=np.full_like(vol, np.nan), where=vol_valid & (vol_ma20_prev > 0)
630
+ )
631
+
632
+ high_60d, low_60d = _rolling_extrema(high, low, valid, 60, strict_prior=False, min_valid=45)
633
+ span_60d = high_60d - low_60d
634
+ pos_in_60d = np.divide(
635
+ close - low_60d, span_60d, out=np.full_like(close, np.nan), where=span_60d > 0
636
+ )
637
+ drawdown_from_60d_high_pct = (
638
+ np.divide(close, high_60d, out=np.full_like(close, np.nan), where=high_60d > 0) - 1.0
639
+ ) * 100.0
640
+
641
+ prev_high_20d, prev_low_20d = _rolling_extrema(high, low, valid, 20, strict_prior=True, min_valid=15)
642
+ prev_range_20d_pct = (
643
+ np.divide(prev_high_20d, prev_low_20d, out=np.full_like(prev_high_20d, np.nan), where=prev_low_20d > 0)
644
+ - 1.0
645
+ ) * 100.0
646
+ prev_range_20d_atr = (prev_high_20d - prev_low_20d) / atr_pos
647
+ breakout_20d_pct = (
648
+ np.divide(close, prev_high_20d, out=np.full_like(close, np.nan), where=prev_high_20d > 0) - 1.0
649
+ ) * 100.0
650
+ breakout_20d_atr = (close - prev_high_20d) / atr_pos
651
+ prev_below_prev_high_20d = (
652
+ np.isfinite(prev_valid_close) & np.isfinite(prev_high_20d) & (prev_valid_close <= prev_high_20d)
653
+ ).astype(np.float64)
654
+
655
+ # Prior 60d decline into recent 10d low
656
+ _, recent_low_10d = _rolling_extrema(high, low, valid, 10, strict_prior=False, min_valid=6)
657
+ prior_high_60d, _ = _rolling_extrema(high, low, valid, 60, strict_prior=True, min_valid=40)
658
+ prior_60d_decline_pct = (
659
+ np.divide(prior_high_60d, recent_low_10d, out=np.full_like(close, np.nan), where=recent_low_10d > 0) - 1.0
660
+ ) * 100.0
661
+
662
+ pullback_to_ma20_pct = (
663
+ np.divide(close, ma20, out=np.full_like(close, np.nan), where=ma20 > 0) - 1.0
664
+ ) * 100.0
665
+ pullback_to_ma20_atr = (close - ma20) / atr_pos
666
+ low_to_ma20_atr = (low - ma20) / atr_pos
667
+ ma20_slope_5d_pct = (
668
+ np.divide(ma20, ma20_lag5, out=np.full_like(ma20, np.nan), where=ma20_lag5 > 0) - 1.0
669
+ ) * 100.0
670
+
671
+ ma_bullish = (np.isfinite(ma5) & np.isfinite(ma20) & np.isfinite(ma60) & (ma5 >= ma20) & (ma20 >= ma60)).astype(np.float64)
672
+ ma20_above_ma60 = (np.isfinite(ma20) & np.isfinite(ma60) & (ma20 >= ma60)).astype(np.float64)
673
+ price_above_ma20 = (np.isfinite(ma20) & (close >= ma20)).astype(np.float64)
674
+ price_above_ma60 = (np.isfinite(ma60) & (close >= ma60)).astype(np.float64)
675
+ prev_close_above_ma20 = (
676
+ np.isfinite(prev_valid_close) & np.isfinite(ma20_lag1) & (prev_valid_close >= ma20_lag1)
677
+ ).astype(np.float64)
678
+
679
+ valid_lag1 = _shift_rows(valid.astype(np.float64), 1, fill=0.0) > 0.5
680
+ open_lag1 = _shift_rows(open_, 1)
681
+ close_lag1 = _shift_rows(close, 1)
682
+ valid_lag3 = _shift_rows(valid.astype(np.float64), 3, fill=0.0) > 0.5
683
+ close_lag3 = _shift_rows(close, 3)
684
+
685
+ valid_streak = np.zeros((t_len, n_codes), dtype=np.float64)
686
+ bull_streak = np.zeros((t_len, n_codes), dtype=np.float64)
687
+ close_higher_streak = np.zeros((t_len, n_codes), dtype=np.float64)
688
+ bull_bar = valid & (close > open_)
689
+ higher_bar = valid & valid_lag1 & (close > close_lag1)
690
+ for t in range(t_len):
691
+ if t == 0:
692
+ valid_streak[t] = np.where(valid[t], 1.0, 0.0)
693
+ bull_streak[t] = np.where(bull_bar[t], 1.0, 0.0)
694
+ close_higher_streak[t] = 0.0
695
+ else:
696
+ valid_streak[t] = np.where(valid[t], valid_streak[t - 1] + 1.0, 0.0)
697
+ bull_streak[t] = np.where(bull_bar[t], bull_streak[t - 1] + 1.0, 0.0)
698
+ close_higher_streak[t] = np.where(higher_bar[t], close_higher_streak[t - 1] + 1.0, 0.0)
699
+
700
+ body_lo_prev = np.minimum(open_lag1, close_lag1) - 0.10 * atr_pos
701
+ body_hi_prev = np.maximum(open_lag1, close_lag1) + 0.10 * atr_pos
702
+ open_in_prev_body = np.where(
703
+ valid & valid_lag1 & np.isfinite(atr_pos),
704
+ ((open_ >= body_lo_prev) & (open_ <= body_hi_prev)).astype(np.float64),
705
+ np.nan,
706
+ )
707
+ body_cur = close - open_
708
+ body_prev = close_lag1 - open_lag1
709
+ body_ratio_vs_prev = np.divide(
710
+ body_cur,
711
+ body_prev,
712
+ out=np.full_like(close, np.nan),
713
+ where=valid & valid_lag1 & (body_cur > 0) & (body_prev > 0),
714
+ )
715
+ is_limit_up_feat = np.where(valid, limit_masks["is_limit_up"].astype(np.float64), np.nan)
716
+ ret_3d_limit_ratio = np.where(
717
+ (valid_streak >= 3.0) & valid_lag3 & (close_lag3 > 0),
718
+ (close / close_lag3 - 1.0) / limit_pct[None, :],
719
+ np.nan,
720
+ )
721
+
722
+ features: dict[str, np.ndarray] = {
723
+ "valid_bars": valid_count.astype(np.float64),
724
+ "valid_streak": valid_streak,
725
+ "bull_streak": bull_streak,
726
+ "close_higher_streak": close_higher_streak,
727
+ "open_in_prev_body": open_in_prev_body,
728
+ "body_ratio_vs_prev": body_ratio_vs_prev,
729
+ "is_bull_bar": (valid & (close > open_)).astype(np.float64),
730
+ "is_bear_bar": (valid & (close < open_)).astype(np.float64),
731
+ "is_limit_up": is_limit_up_feat,
732
+ "not_one_price_limit_up": (~limit_masks["is_one_price_limit_up"]).astype(np.float64),
733
+ "ma_bullish": ma_bullish,
734
+ "ma20_above_ma60": ma20_above_ma60,
735
+ "price_above_ma20": price_above_ma20,
736
+ "price_above_ma60": price_above_ma60,
737
+ "prev_close_above_ma20": prev_close_above_ma20,
738
+ "ma20_slope_5d_pct": ma20_slope_5d_pct,
739
+ "pos_in_60d": pos_in_60d,
740
+ "drawdown_from_60d_high_pct": drawdown_from_60d_high_pct,
741
+ "prior_60d_decline_pct": prior_60d_decline_pct,
742
+ "change_pct": change_pct,
743
+ "ret_limit_ratio": ret_limit_ratio,
744
+ "ret_3d_limit_ratio": ret_3d_limit_ratio,
745
+ "body_pct": body_pct,
746
+ "body_atr": body_atr,
747
+ "body_limit_ratio": body_limit_ratio,
748
+ "bar_range_atr": bar_range_atr,
749
+ "upper_shadow_atr": upper_shadow_atr,
750
+ "lower_shadow_atr": lower_shadow_atr,
751
+ "upper_shadow_to_range": upper_shadow_to_range,
752
+ "close_pos_in_bar": close_pos_in_bar,
753
+ "atr20_pct": atr20_pct,
754
+ "vol_ratio_1d": vol_ratio_1d,
755
+ "vol_ratio_5d": vol_ratio_5d,
756
+ "vol_ratio_20d": vol_ratio_20d,
757
+ "prev_range_20d_pct": prev_range_20d_pct,
758
+ "prev_range_20d_atr": prev_range_20d_atr,
759
+ "breakout_20d_pct": breakout_20d_pct,
760
+ "breakout_20d_atr": breakout_20d_atr,
761
+ "prev_below_prev_high_20d": prev_below_prev_high_20d,
762
+ "pullback_to_ma20_pct": pullback_to_ma20_pct,
763
+ "pullback_to_ma20_atr": pullback_to_ma20_atr,
764
+ "low_to_ma20_atr": low_to_ma20_atr,
765
+ }
766
+ _ = ma10 # Reserved for future trend templates.
767
+
768
+ return PatternMatrixContext(
769
+ dates=dates,
770
+ codes=codes,
771
+ names=names,
772
+ industries=industries,
773
+ valid=valid,
774
+ valid_count=valid_count,
775
+ open=open_,
776
+ high=high,
777
+ low=low,
778
+ close=close,
779
+ raw_close=raw_close,
780
+ volume=vol,
781
+ proxy_amount=limit_masks["proxy_amount"],
782
+ is_st=limit_masks["is_st"],
783
+ is_one_price_limit_up=limit_masks["is_one_price_limit_up"],
784
+ limit_pct=limit_pct,
785
+ features=features,
786
+ )
787
+
788
+
789
+ def _compute_double_bottom_neckline_breakout(
790
+ ctx: PatternMatrixContext,
791
+ params: dict[str, Any] | None = None,
792
+ ) -> np.ndarray:
793
+ cfg = dict(params or {})
794
+ key = tuple(sorted(cfg.items()))
795
+ if key in ctx.double_bottom_cache:
796
+ return ctx.double_bottom_cache[key]
797
+
798
+ prior_decline_min_pct = float(cfg.get("prior_decline_min_pct", 12.0))
799
+ trough_diff_max_atr = float(cfg.get("trough_diff_max_atr", 1.2))
800
+ min_trough_gap = int(cfg.get("min_trough_gap", 7))
801
+ neckline_min_atr = float(cfg.get("neckline_min_atr", 1.5))
802
+ neckline_min_pct = float(cfg.get("neckline_min_pct", 5.0))
803
+ overshoot_max_atr = float(cfg.get("breakout_max_overshoot_atr", 2.2))
804
+
805
+ t_len, n_codes = ctx.close.shape
806
+ out = np.zeros((t_len, n_codes), dtype=bool)
807
+ if t_len < 56:
808
+ ctx.double_bottom_cache[key] = out
809
+ return out
810
+
811
+ atr = ctx.features["atr20_pct"] / 100.0 * ctx.close
812
+ prev_c = _shift_rows(ctx.close, 1)
813
+ offsets = np.arange(55, dtype=np.int64)[:, None]
814
+
815
+ for t in range(55, t_len):
816
+ eligible = ctx.valid[t] & (ctx.valid_count[t] >= 55) & np.isfinite(atr[t]) & (atr[t] > 0)
817
+ cols = np.flatnonzero(eligible)
818
+ if cols.size == 0:
819
+ continue
820
+
821
+ s0 = t - 55
822
+ win_v = ctx.valid[s0:t, cols]
823
+ win_l = np.where(win_v, ctx.low[s0:t, cols], np.inf)
824
+ win_h = np.where(win_v, ctx.high[s0:t, cols], -np.inf)
825
+
826
+ # Left trough in [t-55 .. t-21] (offsets 0..34), right trough in [t-18 .. t-2] (37..53).
827
+ left_slice = win_l[:35]
828
+ right_slice = win_l[37:54]
829
+ i1 = np.argmin(left_slice, axis=0)
830
+ i2 = 37 + np.argmin(right_slice, axis=0)
831
+ l1 = left_slice[i1, np.arange(cols.size)]
832
+ l2 = right_slice[i2 - 37, np.arange(cols.size)]
833
+
834
+ mid_mask = (offsets > i1[None, :]) & (offsets < i2[None, :]) & win_v
835
+ n_peak = np.where(mid_mask, win_h, -np.inf).max(axis=0)
836
+
837
+ p_start = max(0, t - 70)
838
+ prior_hi = np.where(
839
+ ctx.valid[p_start : t - 15, cols],
840
+ ctx.high[p_start : t - 15, cols],
841
+ -np.inf,
842
+ ).max(axis=0)
843
+
844
+ atr_t = atr[t, cols]
845
+ close_t = ctx.close[t, cols]
846
+ prev_t = prev_c[t, cols]
847
+ max_trough = np.maximum(l1, l2)
848
+ min_trough = np.minimum(l1, l2)
849
+
850
+ ok = (
851
+ np.isfinite(l1)
852
+ & np.isfinite(l2)
853
+ & np.isfinite(n_peak)
854
+ & np.isfinite(prior_hi)
855
+ & (min_trough > 0)
856
+ & ((i2 - i1) >= min_trough_gap)
857
+ & ((prior_hi / min_trough - 1.0) * 100.0 >= prior_decline_min_pct)
858
+ & (np.abs(l2 - l1) <= trough_diff_max_atr * atr_t)
859
+ & (l2 >= l1 - 0.8 * atr_t)
860
+ & ((n_peak - max_trough) >= neckline_min_atr * atr_t)
861
+ & ((n_peak / max_trough - 1.0) * 100.0 >= neckline_min_pct)
862
+ & (close_t > n_peak)
863
+ & (~np.isfinite(prev_t) | (prev_t <= n_peak * 1.01))
864
+ & ((close_t - n_peak) <= overshoot_max_atr * atr_t)
865
+ )
866
+ if ok.any():
867
+ out[t, cols[ok]] = True
868
+
869
+ ctx.double_bottom_cache[key] = out
870
+ return out
871
+
872
+
873
+ def _eval_static_condition(ctx: PatternMatrixContext, cond: dict[str, Any]) -> np.ndarray:
874
+ feat = cond["feature"]
875
+ if feat == "double_bottom_neckline_breakout":
876
+ arr = _compute_double_bottom_neckline_breakout(ctx, cond.get("params")).astype(np.float64)
877
+ else:
878
+ arr = ctx.features[feat]
879
+
880
+ lag = int(cond.get("lag") or 0)
881
+ if lag > 0:
882
+ arr = _shift_rows(arr, lag)
883
+
884
+ mask = np.isfinite(arr)
885
+ if "equals" in cond:
886
+ eq = cond["equals"]
887
+ target = 1.0 if eq is True else (0.0 if eq is False else float(eq))
888
+ mask &= arr == target
889
+ if "min" in cond and cond["min"] is not None:
890
+ mask &= arr >= float(cond["min"])
891
+ if "max" in cond and cond["max"] is not None:
892
+ mask &= arr <= float(cond["max"])
893
+ return mask
894
+
895
+
896
+ def _universe_mask(ctx: PatternMatrixContext, spec: PatternSpec) -> np.ndarray:
897
+ mask = ctx.valid & (ctx.valid_count >= spec.min_history_days)
898
+ uni = spec.universe
899
+ if uni.get("exclude_st", True):
900
+ mask &= (~ctx.is_st)[None, :]
901
+ if uni.get("exclude_one_price_limit_up", False):
902
+ mask &= ~ctx.is_one_price_limit_up
903
+ amt_min = uni.get("proxy_amount_min")
904
+ if amt_min is not None:
905
+ mask &= np.isfinite(ctx.proxy_amount) & (ctx.proxy_amount >= float(amt_min))
906
+ close_min = uni.get("close_min")
907
+ if close_min is not None:
908
+ mask &= ctx.close >= float(close_min)
909
+ return mask
910
+
911
+
912
+ def _eval_observe_relative(
913
+ ctx: PatternMatrixContext,
914
+ cond: dict[str, Any],
915
+ obs_slice: slice,
916
+ cur_slice: slice,
917
+ ) -> np.ndarray:
918
+ feat = cond["feature"]
919
+ if feat == "close_above_observe_high":
920
+ arr = (ctx.close[cur_slice] > ctx.high[obs_slice]).astype(np.float64)
921
+ elif feat == "close_above_observe_close":
922
+ arr = (ctx.close[cur_slice] > ctx.close[obs_slice]).astype(np.float64)
923
+ elif feat == "close_above_observe_mid":
924
+ mid = 0.5 * (ctx.open[obs_slice] + ctx.close[obs_slice])
925
+ arr = (ctx.close[cur_slice] >= mid).astype(np.float64)
926
+ elif feat == "hold_above_observe_low":
927
+ arr = (ctx.close[cur_slice] >= ctx.low[obs_slice]).astype(np.float64)
928
+ elif feat == "volume_below_observe_ratio":
929
+ obs_v = ctx.volume[obs_slice]
930
+ arr = np.where(obs_v > 0, ctx.volume[cur_slice] / obs_v, np.nan)
931
+ elif feat == "range_ratio_vs_observe":
932
+ obs_r = np.maximum(ctx.high[obs_slice] - ctx.low[obs_slice], 0.0)
933
+ cur_r = np.maximum(ctx.high[cur_slice] - ctx.low[cur_slice], 0.0)
934
+ arr = np.where(obs_r > 0, cur_r / obs_r, np.nan)
935
+ else:
936
+ raise ValueError(f"Unsupported observe-relative feature {feat!r}")
937
+
938
+ mask = np.isfinite(arr)
939
+ if "equals" in cond:
940
+ eq = cond["equals"]
941
+ target = 1.0 if eq is True else (0.0 if eq is False else float(eq))
942
+ mask &= arr == target
943
+ if "min" in cond and cond["min"] is not None:
944
+ mask &= arr >= float(cond["min"])
945
+ if "max" in cond and cond["max"] is not None:
946
+ mask &= arr <= float(cond["max"])
947
+ return mask
948
+
949
+
950
+ def _apply_cooldown(
951
+ signal_mask: np.ndarray,
952
+ observe_idx: np.ndarray,
953
+ cooldown_days: int,
954
+ ) -> tuple[np.ndarray, np.ndarray]:
955
+ if cooldown_days <= 0:
956
+ return signal_mask, observe_idx
957
+ t_len, n_codes = signal_mask.shape
958
+ out_mask = signal_mask.copy()
959
+ out_obs = observe_idx.copy()
960
+ last_fire = np.full(n_codes, -(cooldown_days + 1), dtype=np.int64)
961
+ for t in range(t_len):
962
+ keep = out_mask[t] & ((t - last_fire) > cooldown_days)
963
+ out_mask[t] = keep
964
+ out_obs[t] = np.where(keep, out_obs[t], -1)
965
+ if keep.any():
966
+ last_fire = np.where(keep, t, last_fire)
967
+ return out_mask, out_obs
968
+
969
+
970
+ def evaluate_pattern_matrix(
971
+ ctx: PatternMatrixContext,
972
+ spec: PatternSpec,
973
+ ) -> tuple[np.ndarray, np.ndarray]:
974
+ """Evaluate a single ``PatternSpec`` over ``ctx``, returning (signal_mask, observe_index)."""
975
+ t_len, n_codes = ctx.close.shape
976
+ uni_mask = _universe_mask(ctx, spec)
977
+ observe_idx = np.full((t_len, n_codes), -1, dtype=np.int32)
978
+
979
+ if spec.mode == "direct":
980
+ sig = uni_mask.copy()
981
+ for cond in spec.conditions:
982
+ sig &= _eval_static_condition(ctx, cond)
983
+ return _apply_cooldown(sig, observe_idx, spec.cooldown_days)
984
+
985
+ # Stateless observe/confirm lookback
986
+ obs_mask = ctx.valid & (ctx.valid_count >= spec.min_history_days)
987
+ if spec.universe.get("exclude_st", True):
988
+ obs_mask &= (~ctx.is_st)[None, :]
989
+ for cond in spec.observe:
990
+ obs_mask &= _eval_static_condition(ctx, cond)
991
+
992
+ static_confirm: list[dict[str, Any]] = []
993
+ rel_confirm: list[dict[str, Any]] = []
994
+ for cond in spec.confirm:
995
+ if cond["feature"] in _OBSERVE_RELATIVE_FEATURES:
996
+ rel_confirm.append(cond)
997
+ else:
998
+ static_confirm.append(cond)
999
+
1000
+ confirm_base = uni_mask.copy()
1001
+ for cond in static_confirm:
1002
+ confirm_base &= _eval_static_condition(ctx, cond)
1003
+
1004
+ inv_rule = spec.invalidation["rule"]
1005
+ tol_atr = float(spec.invalidation.get("tolerance_atr", 0.0))
1006
+ atr = np.where(np.isfinite(ctx.features["atr20_pct"]), ctx.features["atr20_pct"] / 100.0 * ctx.close, 0.0)
1007
+
1008
+ if inv_rule == "low_below_observe_low":
1009
+ inv_floor = ctx.low - tol_atr * atr
1010
+ check_series = ctx.low
1011
+ elif inv_rule == "close_below_observe_low":
1012
+ inv_floor = ctx.low - tol_atr * atr
1013
+ check_series = ctx.close
1014
+ elif inv_rule == "close_below_observe_open":
1015
+ inv_floor = ctx.open - tol_atr * atr
1016
+ check_series = ctx.close
1017
+ elif inv_rule == "close_below_observe_mid":
1018
+ inv_floor = 0.5 * (ctx.open + ctx.close) - tol_atr * atr
1019
+ check_series = ctx.close
1020
+ else:
1021
+ inv_floor = np.full((t_len, n_codes), -np.inf, dtype=np.float64)
1022
+ check_series = ctx.close
1023
+
1024
+ signal_mask = np.zeros((t_len, n_codes), dtype=bool)
1025
+ for lag in range(spec.min_wait_days, min(spec.lookback_days, t_len - 1) + 1):
1026
+ obs_slice = slice(0, t_len - lag)
1027
+ cur_slice = slice(lag, t_len)
1028
+ pair_ok = obs_mask[obs_slice] & confirm_base[cur_slice]
1029
+ if not pair_ok.any():
1030
+ continue
1031
+
1032
+ if inv_rule != "none":
1033
+ floor = inv_floor[obs_slice]
1034
+ for step in range(1, lag + 1):
1035
+ mid_slice = slice(step, t_len - lag + step)
1036
+ breached = ctx.valid[mid_slice] & (check_series[mid_slice] < floor)
1037
+ pair_ok &= ~breached
1038
+ if not pair_ok.any():
1039
+ break
1040
+ if not pair_ok.any():
1041
+ continue
1042
+
1043
+ for rel_cond in rel_confirm:
1044
+ pair_ok &= _eval_observe_relative(ctx, rel_cond, obs_slice, cur_slice)
1045
+ if not pair_ok.any():
1046
+ break
1047
+ if not pair_ok.any():
1048
+ continue
1049
+
1050
+ new_hits = pair_ok & ~signal_mask[cur_slice]
1051
+ if new_hits.any():
1052
+ signal_mask[cur_slice] |= new_hits
1053
+ obs_rows = np.arange(t_len - lag, dtype=np.int32)[:, None]
1054
+ observe_idx[cur_slice] = np.where(new_hits, obs_rows, observe_idx[cur_slice])
1055
+
1056
+ return _apply_cooldown(signal_mask, observe_idx, spec.cooldown_days)
1057
+
1058
+
1059
+ def compute_overhead_supply_10pct_row(
1060
+ ctx: PatternMatrixContext,
1061
+ row_idx: int,
1062
+ col_indices: np.ndarray,
1063
+ *,
1064
+ window: int = 60,
1065
+ ) -> np.ndarray:
1066
+ """Volume share in [close, close * 1.10] over the prior ``window`` valid sessions."""
1067
+ out = np.full(len(col_indices), np.nan, dtype=np.float64)
1068
+ if row_idx <= 0 or len(col_indices) == 0:
1069
+ return out
1070
+ start = max(0, row_idx - window)
1071
+ v_win = ctx.valid[start:row_idx, col_indices] & np.isfinite(ctx.volume[start:row_idx, col_indices]) & (ctx.volume[start:row_idx, col_indices] > 0)
1072
+ vol_win = np.where(v_win, ctx.volume[start:row_idx, col_indices], 0.0)
1073
+ total_vol = vol_win.sum(axis=0)
1074
+ tp = (
1075
+ ctx.high[start:row_idx, col_indices]
1076
+ + ctx.low[start:row_idx, col_indices]
1077
+ + ctx.close[start:row_idx, col_indices]
1078
+ ) / 3.0
1079
+ c_now = ctx.close[row_idx, col_indices][None, :]
1080
+ in_band = v_win & (tp > c_now) & (tp <= c_now * 1.10)
1081
+ band_vol = np.where(in_band, vol_win, 0.0).sum(axis=0)
1082
+ ok = total_vol > 0
1083
+ out[ok] = (band_vol[ok] / total_vol[ok]) * 100.0
1084
+ return out
1085
+
1086
+
1087
+ def scan_patterns(
1088
+ daily_pack: DailyPack,
1089
+ *,
1090
+ patterns: Sequence[str] | None = None,
1091
+ as_of_index: int = -1,
1092
+ trade_date: str | None = None,
1093
+ include_experimental: bool = False,
1094
+ patterns_dir: Path | None = None,
1095
+ ) -> PatternScanResult:
1096
+ """Scan CN ``daily_pack`` at ``as_of_index`` or ``trade_date`` without persisted state."""
1097
+ dates = [str(d) for d in daily_pack.dates]
1098
+ if not dates:
1099
+ raise ValueError("DailyPack contains no sessions")
1100
+ if trade_date is not None:
1101
+ if trade_date not in dates:
1102
+ raise ValueError(f"trade_date {trade_date!r} not found in DailyPack ({dates[0]}..{dates[-1]})")
1103
+ idx = dates.index(trade_date)
1104
+ else:
1105
+ idx = as_of_index if as_of_index >= 0 else len(dates) + as_of_index
1106
+ if idx < 0 or idx >= len(dates):
1107
+ raise IndexError(f"as_of_index {as_of_index} out of range for {len(dates)} sessions")
1108
+
1109
+ if patterns:
1110
+ specs = [load_pattern(name, patterns_dir=patterns_dir) for name in patterns]
1111
+ else:
1112
+ specs = list_patterns(include_experimental=include_experimental, patterns_dir=patterns_dir)
1113
+
1114
+ ctx = build_pattern_context(daily_pack, end_index=idx)
1115
+ regime = compute_market_regime(daily_pack, as_of_index=idx)
1116
+ last_row = len(ctx.dates) - 1
1117
+ universe_count = int(ctx.valid[last_row].sum())
1118
+
1119
+ signals_by_pattern: dict[str, list[PatternSignal]] = {}
1120
+ counts_by_pattern: dict[str, int] = {}
1121
+
1122
+ for spec in specs:
1123
+ sig_mask, obs_idx = evaluate_pattern_matrix(ctx, spec)
1124
+ cols = np.flatnonzero(sig_mask[last_row])
1125
+ overhead = compute_overhead_supply_10pct_row(ctx, last_row, cols)
1126
+ items: list[PatternSignal] = []
1127
+ for pos, j in enumerate(cols.tolist()):
1128
+ obs_row = int(obs_idx[last_row, j])
1129
+ chg = ctx.features["change_pct"][last_row, j]
1130
+ amt = ctx.proxy_amount[last_row, j]
1131
+ atr_pct = ctx.features["atr20_pct"][last_row, j]
1132
+ vr20 = ctx.features["vol_ratio_20d"][last_row, j]
1133
+ ov = overhead[pos]
1134
+ items.append(
1135
+ PatternSignal(
1136
+ pattern=spec.name,
1137
+ display_name=spec.display_name,
1138
+ family=spec.family,
1139
+ status=spec.status,
1140
+ code=str(ctx.codes[j]),
1141
+ name=str(ctx.names[j]),
1142
+ industry=str(ctx.industries[j]),
1143
+ trade_date=str(ctx.dates[last_row]),
1144
+ close=round(float(ctx.raw_close[last_row, j]), 4),
1145
+ change_pct=round(float(chg), 2) if np.isfinite(chg) else 0.0,
1146
+ proxy_amount=round(float(amt), 2) if np.isfinite(amt) else None,
1147
+ atr20_pct=round(float(atr_pct), 2) if np.isfinite(atr_pct) else None,
1148
+ vol_ratio_20d=round(float(vr20), 2) if np.isfinite(vr20) else None,
1149
+ overhead_supply_10pct=round(float(ov), 2) if np.isfinite(ov) else None,
1150
+ observe_date=str(ctx.dates[obs_row]) if obs_row >= 0 else None,
1151
+ observe_lag_days=(last_row - obs_row) if obs_row >= 0 else None,
1152
+ aligned_strategy=spec.aligned_strategy,
1153
+ )
1154
+ )
1155
+ items.sort(key=lambda s: (-(s.proxy_amount or 0.0), s.code))
1156
+ signals_by_pattern[spec.name] = items
1157
+ counts_by_pattern[spec.name] = len(items)
1158
+
1159
+ return PatternScanResult(
1160
+ trade_date=str(ctx.dates[last_row]),
1161
+ pack_trade_date=str(daily_pack.dates[-1]),
1162
+ universe_count=universe_count,
1163
+ patterns_evaluated=[spec.name for spec in specs],
1164
+ market_regime=regime,
1165
+ signals_by_pattern=signals_by_pattern,
1166
+ counts_by_pattern=counts_by_pattern,
1167
+ )
1168
+
1169
+
1170
+ def extract_mini_kline_bars(
1171
+ daily_pack: DailyPack,
1172
+ codes: Sequence[str],
1173
+ *,
1174
+ as_of_index: int = -1,
1175
+ trade_date: str | None = None,
1176
+ bars: int = 20,
1177
+ ) -> dict[str, list[list[float]]]:
1178
+ """Extract up to ``bars`` forward-adjusted [o, h, l, c] bars per code without look-ahead."""
1179
+ dates = [str(d) for d in daily_pack.dates]
1180
+ if not dates or len(daily_pack.codes) == 0 or int(bars) <= 0:
1181
+ return {}
1182
+ if trade_date is not None:
1183
+ if trade_date not in dates:
1184
+ raise ValueError(f"trade_date {trade_date!r} not found in DailyPack")
1185
+ idx = dates.index(trade_date)
1186
+ else:
1187
+ idx = as_of_index if as_of_index >= 0 else len(dates) + as_of_index
1188
+ if idx < 0 or idx >= len(dates):
1189
+ raise IndexError(f"as_of_index {as_of_index} out of range for {len(dates)} sessions")
1190
+
1191
+ sub_pack = DailyPack(
1192
+ dates=daily_pack.dates[: idx + 1],
1193
+ codes=daily_pack.codes,
1194
+ matrices={k: v[: idx + 1] for k, v in daily_pack.matrices.items()},
1195
+ meta=daily_pack.meta,
1196
+ sources=daily_pack.sources,
1197
+ manifest=daily_pack.manifest,
1198
+ )
1199
+ adj = forward_adjust(sub_pack)
1200
+ pack_codes = np.asarray(sub_pack.codes, dtype=str)
1201
+ o_mat = np.asarray(adj["open"], dtype=np.float64)
1202
+ h_mat = np.asarray(adj["high"], dtype=np.float64)
1203
+ lo_mat = np.asarray(adj["low"], dtype=np.float64)
1204
+ c_mat = np.asarray(adj["close"], dtype=np.float64)
1205
+ v_mat = np.asarray(sub_pack.matrices["volume"], dtype=np.float64)
1206
+
1207
+ out: dict[str, list[list[float]]] = {}
1208
+ n_bars = int(bars)
1209
+ for raw_code in codes:
1210
+ code = normalize_code(raw_code, allow_ticker=False) or str(raw_code).strip()
1211
+ if not code or code in out:
1212
+ continue
1213
+ pos = int(np.searchsorted(pack_codes, code))
1214
+ if pos >= len(pack_codes) or pack_codes[pos] != code:
1215
+ continue
1216
+ valid_col = (
1217
+ np.isfinite(o_mat[:, pos]) & (o_mat[:, pos] > 0)
1218
+ & np.isfinite(h_mat[:, pos]) & (h_mat[:, pos] > 0)
1219
+ & np.isfinite(lo_mat[:, pos]) & (lo_mat[:, pos] > 0)
1220
+ & np.isfinite(c_mat[:, pos]) & (c_mat[:, pos] > 0)
1221
+ & (~np.isfinite(v_mat[:, pos]) | (v_mat[:, pos] > 0))
1222
+ )
1223
+ rows = np.flatnonzero(valid_col)[-n_bars:]
1224
+ out[code] = [
1225
+ [
1226
+ round(float(o_mat[r, pos]), 2),
1227
+ round(float(h_mat[r, pos]), 2),
1228
+ round(float(lo_mat[r, pos]), 2),
1229
+ round(float(c_mat[r, pos]), 2),
1230
+ ]
1231
+ for r in rows
1232
+ ]
1233
+ return out