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.
- alphasift/__init__.py +52 -0
- alphasift/__main__.py +7 -0
- alphasift/audit.py +191 -0
- alphasift/candidate_context.py +738 -0
- alphasift/cli.py +2797 -0
- alphasift/config.py +705 -0
- alphasift/context.py +672 -0
- alphasift/daily.py +1256 -0
- alphasift/daily_brief.py +593 -0
- alphasift/daily_report.py +1115 -0
- alphasift/daily_report_html.py +1257 -0
- alphasift/doctor.py +1123 -0
- alphasift/dsa.py +302 -0
- alphasift/dsa_adapter.py +178 -0
- alphasift/dsa_provider.py +192 -0
- alphasift/evaluate.py +2418 -0
- alphasift/filter.py +517 -0
- alphasift/hotspot.py +1713 -0
- alphasift/industry.py +959 -0
- alphasift/llm_client.py +349 -0
- alphasift/market_digest.py +284 -0
- alphasift/market_news.py +446 -0
- alphasift/market_regime.py +578 -0
- alphasift/markets.py +160 -0
- alphasift/mcp.py +720 -0
- alphasift/models.py +315 -0
- alphasift/normalize.py +113 -0
- alphasift/notify.py +2608 -0
- alphasift/overview.py +225 -0
- alphasift/pack.py +1470 -0
- alphasift/pack_features.py +431 -0
- alphasift/pattern_replay.py +1449 -0
- alphasift/patterns/bottom_volume_yang.yaml +32 -0
- alphasift/patterns/box_breakout.yaml +36 -0
- alphasift/patterns/double_bottom_breakout.yaml +38 -0
- alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
- alphasift/patterns/shooting_star_confirm.yaml +49 -0
- alphasift/patterns/single_yang_hold.yaml +44 -0
- alphasift/patterns/steady_trend_breakout.yaml +39 -0
- alphasift/patterns/three_white_soldiers.yaml +72 -0
- alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
- alphasift/patterns.py +1233 -0
- alphasift/performance_history.py +297 -0
- alphasift/pipeline.py +1010 -0
- alphasift/post_analysis.py +337 -0
- alphasift/ranker.py +990 -0
- alphasift/report.py +379 -0
- alphasift/result_schema.py +179 -0
- alphasift/risk.py +452 -0
- alphasift/run_history.py +164 -0
- alphasift/scorer.py +597 -0
- alphasift/server.py +680 -0
- alphasift/snapshot.py +1025 -0
- alphasift/snapshot_us.py +280 -0
- alphasift/snapshot_yahoo.py +358 -0
- alphasift/source_guard.py +70 -0
- alphasift/source_history.py +306 -0
- alphasift/store.py +294 -0
- alphasift/strategies/balanced_alpha.yaml +76 -0
- alphasift/strategies/blue_chip_income.yaml +87 -0
- alphasift/strategies/capital_heat.yaml +74 -0
- alphasift/strategies/dual_low.yaml +80 -0
- alphasift/strategies/global_value.yaml +65 -0
- alphasift/strategies/low_volatility_quality.yaml +95 -0
- alphasift/strategies/momentum_quality.yaml +81 -0
- alphasift/strategies/oversold_reversal.yaml +75 -0
- alphasift/strategies/quality_value.yaml +80 -0
- alphasift/strategies/shrink_pullback.yaml +77 -0
- alphasift/strategies/us_momentum_quality.yaml +74 -0
- alphasift/strategies/volume_breakout.yaml +78 -0
- alphasift/strategy.py +1090 -0
- alphasift/strategy_cards.py +424 -0
- alphasift/strategy_templates.py +291 -0
- alphasift/timeutil.py +38 -0
- alphasift/valuation_kr.py +149 -0
- alphasift/workbench_ui.py +1051 -0
- alphasift-0.3.1.data/data/.env.example +151 -0
- alphasift-0.3.1.data/data/LICENSE +184 -0
- alphasift-0.3.1.data/data/SKILL.md +190 -0
- alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
- alphasift-0.3.1.dist-info/METADATA +312 -0
- alphasift-0.3.1.dist-info/RECORD +86 -0
- alphasift-0.3.1.dist-info/WHEEL +5 -0
- alphasift-0.3.1.dist-info/entry_points.txt +2 -0
- alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
- alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/strategy.py
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Strategy YAML loader."""
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import logging
|
|
6
|
+
import math
|
|
7
|
+
from dataclasses import asdict, fields
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from alphasift.models import (
|
|
13
|
+
HardFilterConfig,
|
|
14
|
+
ScreeningConfig,
|
|
15
|
+
Strategy,
|
|
16
|
+
StrategyInfo,
|
|
17
|
+
StrategyStyle,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
22
|
+
_BUNDLED_STRATEGIES_DIR = Path(__file__).resolve().parent / "strategies"
|
|
23
|
+
_TOP_LEVEL_KEYS = {
|
|
24
|
+
"name",
|
|
25
|
+
"display_name",
|
|
26
|
+
"description",
|
|
27
|
+
"version",
|
|
28
|
+
"category",
|
|
29
|
+
"tags",
|
|
30
|
+
"style",
|
|
31
|
+
"screening",
|
|
32
|
+
}
|
|
33
|
+
_SCREENING_KEYS = {
|
|
34
|
+
"enabled",
|
|
35
|
+
"market_scope",
|
|
36
|
+
"hard_filters",
|
|
37
|
+
"tech_weight",
|
|
38
|
+
"factor_weights",
|
|
39
|
+
"scoring_profile",
|
|
40
|
+
"risk_profile",
|
|
41
|
+
"portfolio_profile",
|
|
42
|
+
"scorecard_profile",
|
|
43
|
+
"event_profile",
|
|
44
|
+
"ranking_hints",
|
|
45
|
+
"max_output",
|
|
46
|
+
}
|
|
47
|
+
_HARD_FILTER_KEYS = set(HardFilterConfig.__dataclass_fields__.keys())
|
|
48
|
+
_SCORING_PROFILE_KEYS = {
|
|
49
|
+
"momentum_base",
|
|
50
|
+
"momentum_intraday_slope",
|
|
51
|
+
"momentum_chase_start_pct",
|
|
52
|
+
"momentum_chase_penalty_slope",
|
|
53
|
+
"momentum_downside_start_pct",
|
|
54
|
+
"momentum_downside_penalty_slope",
|
|
55
|
+
"momentum_60d_base",
|
|
56
|
+
"momentum_60d_slope",
|
|
57
|
+
"momentum_60d_overheat_pct",
|
|
58
|
+
"momentum_60d_overheat_penalty_slope",
|
|
59
|
+
"momentum_60d_breakdown_pct",
|
|
60
|
+
"momentum_60d_breakdown_penalty_slope",
|
|
61
|
+
"macd_bullish_bonus",
|
|
62
|
+
"macd_bearish_penalty",
|
|
63
|
+
"reversal_ideal_change_pct",
|
|
64
|
+
"reversal_distance_penalty_slope",
|
|
65
|
+
"reversal_collapse_start_pct",
|
|
66
|
+
"reversal_collapse_penalty_slope",
|
|
67
|
+
"reversal_chase_start_pct",
|
|
68
|
+
"reversal_chase_penalty_slope",
|
|
69
|
+
"rsi_oversold_bonus",
|
|
70
|
+
"rsi_overbought_penalty",
|
|
71
|
+
"activity_ideal_volume_ratio",
|
|
72
|
+
"activity_volume_ratio_distance_slope",
|
|
73
|
+
"activity_high_volume_ratio",
|
|
74
|
+
"activity_high_volume_ratio_penalty_slope",
|
|
75
|
+
"activity_ideal_turnover_rate",
|
|
76
|
+
"activity_turnover_distance_slope",
|
|
77
|
+
"activity_high_turnover_rate",
|
|
78
|
+
"activity_high_turnover_penalty_slope",
|
|
79
|
+
"stability_base",
|
|
80
|
+
"stability_change_abs_penalty_slope",
|
|
81
|
+
"stability_hot_change_pct",
|
|
82
|
+
"stability_hot_change_penalty_slope",
|
|
83
|
+
"stability_high_turnover_rate",
|
|
84
|
+
"stability_high_turnover_penalty_slope",
|
|
85
|
+
"stability_high_volume_ratio",
|
|
86
|
+
"stability_high_volume_ratio_penalty_slope",
|
|
87
|
+
"stability_invalid_pe_penalty",
|
|
88
|
+
"stability_high_volatility_pct",
|
|
89
|
+
"stability_high_volatility_penalty_slope",
|
|
90
|
+
"stability_max_drawdown_floor_pct",
|
|
91
|
+
"stability_drawdown_penalty_slope",
|
|
92
|
+
"stability_high_atr_pct",
|
|
93
|
+
"stability_high_atr_penalty_slope",
|
|
94
|
+
"stability_low_daily_quality_score",
|
|
95
|
+
"stability_low_daily_quality_penalty_slope",
|
|
96
|
+
"stability_bad_daily_quality_flag_penalty",
|
|
97
|
+
"theme_heat_unknown_score",
|
|
98
|
+
"theme_heat_change_slope",
|
|
99
|
+
"theme_heat_rank_bonus",
|
|
100
|
+
"theme_heat_trend_min_observations",
|
|
101
|
+
"theme_heat_trend_slope",
|
|
102
|
+
"theme_heat_trend_bonus_cap",
|
|
103
|
+
"theme_heat_cooling_penalty_slope",
|
|
104
|
+
"theme_heat_cooling_penalty_cap",
|
|
105
|
+
"theme_heat_persistence_min_score",
|
|
106
|
+
"theme_heat_persistence_slope",
|
|
107
|
+
"theme_heat_persistence_bonus_cap",
|
|
108
|
+
"theme_heat_cooling_score_penalty_slope",
|
|
109
|
+
"theme_heat_cooling_score_penalty_cap",
|
|
110
|
+
"theme_heat_overheat_score",
|
|
111
|
+
"theme_heat_overheat_penalty_slope",
|
|
112
|
+
"factor_rank_blend",
|
|
113
|
+
}
|
|
114
|
+
_RISK_PROFILE_KEYS = {
|
|
115
|
+
"chase_change_pct",
|
|
116
|
+
"chase_points",
|
|
117
|
+
"breakdown_change_pct",
|
|
118
|
+
"breakdown_points",
|
|
119
|
+
"abnormal_volume_ratio",
|
|
120
|
+
"abnormal_volume_ratio_points",
|
|
121
|
+
"high_turnover_rate",
|
|
122
|
+
"high_turnover_points",
|
|
123
|
+
"invalid_pe_points",
|
|
124
|
+
"high_pb",
|
|
125
|
+
"high_pb_points",
|
|
126
|
+
"weak_signal_score",
|
|
127
|
+
"weak_signal_points",
|
|
128
|
+
"macd_bearish_points",
|
|
129
|
+
"rsi_overbought_points",
|
|
130
|
+
"low_llm_confidence",
|
|
131
|
+
"low_llm_confidence_points",
|
|
132
|
+
"llm_risk_points",
|
|
133
|
+
"llm_risk_points_cap",
|
|
134
|
+
"deep_risk_points",
|
|
135
|
+
"deep_risk_points_cap",
|
|
136
|
+
"low_daily_quality_score",
|
|
137
|
+
"low_daily_quality_points",
|
|
138
|
+
"bad_daily_quality_flag_points",
|
|
139
|
+
"stale_daily_cache_points",
|
|
140
|
+
"fallback_daily_errors_points",
|
|
141
|
+
"fetch_failed_daily_points",
|
|
142
|
+
}
|
|
143
|
+
_PORTFOLIO_PROFILE_KEYS = {"mode", "max_same_bucket", "concentration_penalty", "buckets"}
|
|
144
|
+
_PORTFOLIO_MODES = {"soft", "hard_cap"}
|
|
145
|
+
_SCORECARD_PROFILE_KEYS = {
|
|
146
|
+
"value_quality_value_min",
|
|
147
|
+
"value_quality_stability_min",
|
|
148
|
+
"value_quality_bonus",
|
|
149
|
+
"capital_confirmed_momentum_min",
|
|
150
|
+
"capital_confirmed_activity_min",
|
|
151
|
+
"capital_confirmed_bonus",
|
|
152
|
+
"controlled_reversal_min",
|
|
153
|
+
"controlled_reversal_bonus",
|
|
154
|
+
"hot_money_activity_min",
|
|
155
|
+
"hot_money_stability_max",
|
|
156
|
+
"hot_money_penalty",
|
|
157
|
+
"volume_spike_ratio",
|
|
158
|
+
"volume_spike_penalty",
|
|
159
|
+
"high_llm_confidence",
|
|
160
|
+
"high_llm_confidence_bonus",
|
|
161
|
+
"low_llm_confidence",
|
|
162
|
+
"low_llm_confidence_penalty",
|
|
163
|
+
"catalyst_bonus",
|
|
164
|
+
"catalyst_bonus_cap",
|
|
165
|
+
"llm_risk_penalty",
|
|
166
|
+
"llm_risk_penalty_cap",
|
|
167
|
+
"score_delta_cap",
|
|
168
|
+
}
|
|
169
|
+
_EVENT_PROFILE_KEYS = {
|
|
170
|
+
"preferred_event_tags",
|
|
171
|
+
"avoided_event_tags",
|
|
172
|
+
"preferred_announcement_categories",
|
|
173
|
+
"avoided_announcement_categories",
|
|
174
|
+
"source_weights",
|
|
175
|
+
"notes",
|
|
176
|
+
}
|
|
177
|
+
_STYLE_KEYS = {
|
|
178
|
+
"risk_profile",
|
|
179
|
+
"holding_period",
|
|
180
|
+
"execution_style",
|
|
181
|
+
"market_regime",
|
|
182
|
+
"capital_profile",
|
|
183
|
+
"ui_badge",
|
|
184
|
+
}
|
|
185
|
+
_STRATEGY_DIR_CACHE: dict[
|
|
186
|
+
Path,
|
|
187
|
+
tuple[tuple[tuple[str, int, int, str], ...], dict[str, Strategy]],
|
|
188
|
+
] = {}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def load_strategy(filepath: Path) -> Strategy:
|
|
192
|
+
"""Load a screening strategy from a YAML file."""
|
|
193
|
+
with open(filepath, "r", encoding="utf-8") as f:
|
|
194
|
+
data = yaml.safe_load(f)
|
|
195
|
+
|
|
196
|
+
if not isinstance(data, dict):
|
|
197
|
+
raise ValueError(f"Invalid strategy file: {filepath}")
|
|
198
|
+
|
|
199
|
+
_raise_unknown_keys(data, _TOP_LEVEL_KEYS, f"strategy file {filepath.name}")
|
|
200
|
+
|
|
201
|
+
screening_data = data.get("screening", {})
|
|
202
|
+
if not isinstance(screening_data, dict):
|
|
203
|
+
raise ValueError(f"Invalid screening section in strategy file: {filepath}")
|
|
204
|
+
_raise_unknown_keys(screening_data, _SCREENING_KEYS, f"screening section of {filepath.name}")
|
|
205
|
+
|
|
206
|
+
hf_data = screening_data.get("hard_filters", {})
|
|
207
|
+
if not isinstance(hf_data, dict):
|
|
208
|
+
raise ValueError(f"Invalid hard_filters section in strategy file: {filepath}")
|
|
209
|
+
_raise_unknown_keys(hf_data, _HARD_FILTER_KEYS, f"hard_filters section of {filepath.name}")
|
|
210
|
+
|
|
211
|
+
hard_filters = HardFilterConfig(**hf_data)
|
|
212
|
+
|
|
213
|
+
screening = ScreeningConfig(
|
|
214
|
+
enabled=screening_data.get("enabled", False),
|
|
215
|
+
market_scope=screening_data.get("market_scope", ["cn"]),
|
|
216
|
+
hard_filters=hard_filters,
|
|
217
|
+
tech_weight=screening_data.get("tech_weight", 0.35),
|
|
218
|
+
factor_weights=screening_data.get("factor_weights", {}),
|
|
219
|
+
scoring_profile=_scoring_profile(screening_data, filepath),
|
|
220
|
+
risk_profile=_optional_mapping(
|
|
221
|
+
screening_data, "risk_profile", filepath, allowed_keys=_RISK_PROFILE_KEYS
|
|
222
|
+
),
|
|
223
|
+
portfolio_profile=_portfolio_profile(screening_data, filepath),
|
|
224
|
+
scorecard_profile=_optional_mapping(
|
|
225
|
+
screening_data, "scorecard_profile", filepath, allowed_keys=_SCORECARD_PROFILE_KEYS
|
|
226
|
+
),
|
|
227
|
+
event_profile=_optional_mapping(
|
|
228
|
+
screening_data, "event_profile", filepath, allowed_keys=_EVENT_PROFILE_KEYS
|
|
229
|
+
),
|
|
230
|
+
ranking_hints=screening_data.get("ranking_hints", ""),
|
|
231
|
+
max_output=screening_data.get("max_output", 5),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
return Strategy(
|
|
235
|
+
name=data.get("name", filepath.stem),
|
|
236
|
+
display_name=data.get("display_name", data.get("name", filepath.stem)),
|
|
237
|
+
description=data.get("description", ""),
|
|
238
|
+
version=str(data.get("version", "1")),
|
|
239
|
+
category=data.get("category", "trend"),
|
|
240
|
+
tags=list(data.get("tags", []) or []),
|
|
241
|
+
style=_strategy_style(data, filepath),
|
|
242
|
+
screening=screening,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def load_all_strategies(strategies_dir: Path) -> dict[str, Strategy]:
|
|
247
|
+
"""Load all strategies from a directory."""
|
|
248
|
+
resolved_dir = strategies_dir.resolve()
|
|
249
|
+
signature = _strategy_dir_signature(resolved_dir)
|
|
250
|
+
cached = _STRATEGY_DIR_CACHE.get(resolved_dir)
|
|
251
|
+
if cached is not None and cached[0] == signature:
|
|
252
|
+
return dict(cached[1])
|
|
253
|
+
|
|
254
|
+
_validate_strategy_dir_sync(strategies_dir)
|
|
255
|
+
strategies = {}
|
|
256
|
+
if not strategies_dir.is_dir():
|
|
257
|
+
_STRATEGY_DIR_CACHE[resolved_dir] = (signature, strategies)
|
|
258
|
+
return strategies
|
|
259
|
+
for f in sorted(strategies_dir.glob("*.yaml")):
|
|
260
|
+
try:
|
|
261
|
+
s = load_strategy(f)
|
|
262
|
+
if s.screening.enabled:
|
|
263
|
+
strategies[s.name] = s
|
|
264
|
+
except Exception as e:
|
|
265
|
+
logger.warning("Failed to load strategy %s: %s", f.name, e)
|
|
266
|
+
continue
|
|
267
|
+
_STRATEGY_DIR_CACHE[resolved_dir] = (signature, dict(strategies))
|
|
268
|
+
return dict(strategies)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _strategy_dir_signature(strategies_dir: Path) -> tuple[tuple[str, int, int, str], ...]:
|
|
272
|
+
if not strategies_dir.is_dir():
|
|
273
|
+
return ()
|
|
274
|
+
signature = []
|
|
275
|
+
for filepath in sorted(strategies_dir.glob("*.yaml")):
|
|
276
|
+
try:
|
|
277
|
+
stat = filepath.stat()
|
|
278
|
+
digest = hashlib.sha256(filepath.read_bytes()).hexdigest()
|
|
279
|
+
except OSError:
|
|
280
|
+
continue
|
|
281
|
+
signature.append((filepath.name, stat.st_mtime_ns, stat.st_size, digest))
|
|
282
|
+
return tuple(signature)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def list_strategies(strategies_dir: Path | None = None) -> list[StrategyInfo]:
|
|
286
|
+
"""List available screening strategies."""
|
|
287
|
+
from alphasift.config import Config
|
|
288
|
+
from alphasift.filter import requires_daily_features
|
|
289
|
+
|
|
290
|
+
if strategies_dir is None:
|
|
291
|
+
strategies_dir = Config.from_env().strategies_dir
|
|
292
|
+
|
|
293
|
+
strategies = load_all_strategies(strategies_dir)
|
|
294
|
+
infos: list[StrategyInfo] = []
|
|
295
|
+
for s in strategies.values():
|
|
296
|
+
daily_required = requires_daily_features(s.screening.hard_filters)
|
|
297
|
+
infos.append(StrategyInfo(
|
|
298
|
+
name=s.name,
|
|
299
|
+
display_name=s.display_name,
|
|
300
|
+
description=s.description,
|
|
301
|
+
version=s.version,
|
|
302
|
+
category=s.category,
|
|
303
|
+
tags=s.tags,
|
|
304
|
+
market_scope=s.screening.market_scope,
|
|
305
|
+
requires_daily_features=daily_required,
|
|
306
|
+
data_requirements=_strategy_data_requirements(s, daily_required=daily_required),
|
|
307
|
+
required_snapshot_fields=_required_snapshot_fields(s.screening.hard_filters),
|
|
308
|
+
required_daily_fields=_required_daily_fields(s.screening.hard_filters),
|
|
309
|
+
active_filters=_active_hard_filters(s.screening.hard_filters),
|
|
310
|
+
factor_weights={key: float(value) for key, value in s.screening.factor_weights.items()},
|
|
311
|
+
profile_keys=_strategy_profile_keys(s.screening),
|
|
312
|
+
style=_style_to_dict(s.style),
|
|
313
|
+
))
|
|
314
|
+
return infos
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def strategy_facets(strategies_dir: Path | None = None) -> dict[str, object]:
|
|
318
|
+
"""Return UI-ready filter facets for the strategy catalog."""
|
|
319
|
+
return strategy_facets_from_infos(list_strategies(strategies_dir))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def strategy_facets_from_infos(strategies: list[StrategyInfo]) -> dict[str, object]:
|
|
323
|
+
"""Build strategy catalog facets from already loaded strategy metadata."""
|
|
324
|
+
return {
|
|
325
|
+
"schema_version": 1,
|
|
326
|
+
"strategy_count": len(strategies),
|
|
327
|
+
"daily_strategy_count": sum(1 for item in strategies if item.requires_daily_features),
|
|
328
|
+
"facets": [
|
|
329
|
+
_strategy_facet(
|
|
330
|
+
strategies,
|
|
331
|
+
name="category",
|
|
332
|
+
query_param="category",
|
|
333
|
+
multi=False,
|
|
334
|
+
values_fn=lambda item: [item.category],
|
|
335
|
+
),
|
|
336
|
+
_strategy_facet(
|
|
337
|
+
strategies,
|
|
338
|
+
name="risk_profile",
|
|
339
|
+
query_param="risk_profile",
|
|
340
|
+
multi=False,
|
|
341
|
+
values_fn=lambda item: [str(item.style.get("risk_profile") or "")],
|
|
342
|
+
),
|
|
343
|
+
_strategy_facet(
|
|
344
|
+
strategies,
|
|
345
|
+
name="holding_period",
|
|
346
|
+
query_param="holding_period",
|
|
347
|
+
multi=False,
|
|
348
|
+
values_fn=lambda item: [str(item.style.get("holding_period") or "")],
|
|
349
|
+
),
|
|
350
|
+
_strategy_facet(
|
|
351
|
+
strategies,
|
|
352
|
+
name="execution_style",
|
|
353
|
+
query_param="execution_style",
|
|
354
|
+
multi=False,
|
|
355
|
+
values_fn=lambda item: [str(item.style.get("execution_style") or "")],
|
|
356
|
+
),
|
|
357
|
+
_strategy_facet(
|
|
358
|
+
strategies,
|
|
359
|
+
name="capital_profile",
|
|
360
|
+
query_param="capital_profile",
|
|
361
|
+
multi=False,
|
|
362
|
+
values_fn=lambda item: [str(item.style.get("capital_profile") or "")],
|
|
363
|
+
),
|
|
364
|
+
_strategy_facet(
|
|
365
|
+
strategies,
|
|
366
|
+
name="market_regime",
|
|
367
|
+
query_param="market_regime",
|
|
368
|
+
multi=True,
|
|
369
|
+
values_fn=lambda item: item.style.get("market_regime", []),
|
|
370
|
+
),
|
|
371
|
+
_strategy_facet(
|
|
372
|
+
strategies,
|
|
373
|
+
name="data_requirement",
|
|
374
|
+
query_param="data_requirement",
|
|
375
|
+
multi=True,
|
|
376
|
+
values_fn=lambda item: item.data_requirements,
|
|
377
|
+
),
|
|
378
|
+
_strategy_facet(
|
|
379
|
+
strategies,
|
|
380
|
+
name="tag",
|
|
381
|
+
query_param="tag",
|
|
382
|
+
multi=True,
|
|
383
|
+
values_fn=lambda item: item.tags,
|
|
384
|
+
),
|
|
385
|
+
_strategy_facet(
|
|
386
|
+
strategies,
|
|
387
|
+
name="daily_required",
|
|
388
|
+
query_param="daily_required",
|
|
389
|
+
multi=False,
|
|
390
|
+
values_fn=lambda item: [str(bool(item.requires_daily_features)).lower()],
|
|
391
|
+
),
|
|
392
|
+
_strategy_facet(
|
|
393
|
+
strategies,
|
|
394
|
+
name="required_snapshot_field",
|
|
395
|
+
query_param="",
|
|
396
|
+
multi=True,
|
|
397
|
+
filterable=False,
|
|
398
|
+
values_fn=lambda item: item.required_snapshot_fields,
|
|
399
|
+
),
|
|
400
|
+
_strategy_facet(
|
|
401
|
+
strategies,
|
|
402
|
+
name="required_daily_field",
|
|
403
|
+
query_param="",
|
|
404
|
+
multi=True,
|
|
405
|
+
filterable=False,
|
|
406
|
+
values_fn=lambda item: item.required_daily_fields,
|
|
407
|
+
),
|
|
408
|
+
],
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _strategy_facet(
|
|
413
|
+
strategies: list[StrategyInfo],
|
|
414
|
+
*,
|
|
415
|
+
name: str,
|
|
416
|
+
query_param: str,
|
|
417
|
+
multi: bool,
|
|
418
|
+
values_fn,
|
|
419
|
+
filterable: bool = True,
|
|
420
|
+
) -> dict[str, object]:
|
|
421
|
+
groups: dict[str, list[str]] = {}
|
|
422
|
+
for item in strategies:
|
|
423
|
+
raw_values = values_fn(item) or []
|
|
424
|
+
if isinstance(raw_values, str):
|
|
425
|
+
raw_values = [raw_values]
|
|
426
|
+
for raw_value in raw_values:
|
|
427
|
+
value = str(raw_value).strip()
|
|
428
|
+
if value:
|
|
429
|
+
groups.setdefault(value, []).append(item.name)
|
|
430
|
+
values = [
|
|
431
|
+
{
|
|
432
|
+
"value": value,
|
|
433
|
+
"count": len(strategy_names),
|
|
434
|
+
"strategies": sorted(strategy_names),
|
|
435
|
+
}
|
|
436
|
+
for value, strategy_names in groups.items()
|
|
437
|
+
]
|
|
438
|
+
values.sort(key=lambda item: (-int(item["count"]), str(item["value"])))
|
|
439
|
+
return {
|
|
440
|
+
"name": name,
|
|
441
|
+
"query_param": query_param,
|
|
442
|
+
"filterable": bool(filterable),
|
|
443
|
+
"multi": bool(multi),
|
|
444
|
+
"values": values,
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def match_strategies(
|
|
449
|
+
strategies_dir: Path | None = None,
|
|
450
|
+
*,
|
|
451
|
+
risk_profile: str = "",
|
|
452
|
+
holding_period: str = "",
|
|
453
|
+
execution_style: str = "",
|
|
454
|
+
market_regime: list[str] | None = None,
|
|
455
|
+
capital_profile: str = "",
|
|
456
|
+
data_requirements: list[str] | None = None,
|
|
457
|
+
tags: list[str] | None = None,
|
|
458
|
+
category: str = "",
|
|
459
|
+
daily_required: bool | None = None,
|
|
460
|
+
strict: bool = False,
|
|
461
|
+
limit: int | None = None,
|
|
462
|
+
) -> list[dict[str, object]]:
|
|
463
|
+
"""Rank strategies by UI/agent-facing selection preferences."""
|
|
464
|
+
criteria = {
|
|
465
|
+
"risk_profile": risk_profile,
|
|
466
|
+
"holding_period": holding_period,
|
|
467
|
+
"execution_style": execution_style,
|
|
468
|
+
"capital_profile": capital_profile,
|
|
469
|
+
"category": category,
|
|
470
|
+
}
|
|
471
|
+
regimes = _normalized_values(market_regime)
|
|
472
|
+
required_data = _normalized_values(data_requirements)
|
|
473
|
+
required_tags = _normalized_values(tags)
|
|
474
|
+
results: list[dict[str, object]] = []
|
|
475
|
+
|
|
476
|
+
for info in list_strategies(strategies_dir):
|
|
477
|
+
score = 0.0
|
|
478
|
+
matched: list[str] = []
|
|
479
|
+
missing: list[str] = []
|
|
480
|
+
style = info.style or {}
|
|
481
|
+
|
|
482
|
+
score += _match_single(
|
|
483
|
+
criteria["risk_profile"],
|
|
484
|
+
str(style.get("risk_profile") or ""),
|
|
485
|
+
"risk_profile",
|
|
486
|
+
3.0,
|
|
487
|
+
matched,
|
|
488
|
+
missing,
|
|
489
|
+
)
|
|
490
|
+
score += _match_single(
|
|
491
|
+
criteria["holding_period"],
|
|
492
|
+
str(style.get("holding_period") or ""),
|
|
493
|
+
"holding_period",
|
|
494
|
+
2.0,
|
|
495
|
+
matched,
|
|
496
|
+
missing,
|
|
497
|
+
)
|
|
498
|
+
score += _match_single(
|
|
499
|
+
criteria["execution_style"],
|
|
500
|
+
str(style.get("execution_style") or ""),
|
|
501
|
+
"execution_style",
|
|
502
|
+
2.0,
|
|
503
|
+
matched,
|
|
504
|
+
missing,
|
|
505
|
+
)
|
|
506
|
+
score += _match_single(
|
|
507
|
+
criteria["capital_profile"],
|
|
508
|
+
str(style.get("capital_profile") or ""),
|
|
509
|
+
"capital_profile",
|
|
510
|
+
1.0,
|
|
511
|
+
matched,
|
|
512
|
+
missing,
|
|
513
|
+
)
|
|
514
|
+
score += _match_single(
|
|
515
|
+
criteria["category"],
|
|
516
|
+
info.category,
|
|
517
|
+
"category",
|
|
518
|
+
1.5,
|
|
519
|
+
matched,
|
|
520
|
+
missing,
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
available_regimes = _normalized_values(style.get("market_regime", []))
|
|
524
|
+
score += _match_many(regimes, available_regimes, "market_regime", 1.0, matched, missing)
|
|
525
|
+
score += _match_many(
|
|
526
|
+
required_data,
|
|
527
|
+
_normalized_values(info.data_requirements),
|
|
528
|
+
"data_requirement",
|
|
529
|
+
1.0,
|
|
530
|
+
matched,
|
|
531
|
+
missing,
|
|
532
|
+
)
|
|
533
|
+
score += _match_many(required_tags, _normalized_values(info.tags), "tag", 1.0, matched, missing)
|
|
534
|
+
if daily_required is not None:
|
|
535
|
+
if bool(info.requires_daily_features) == daily_required:
|
|
536
|
+
score += 1.0
|
|
537
|
+
matched.append(f"daily_required:{str(daily_required).lower()}")
|
|
538
|
+
else:
|
|
539
|
+
missing.append(f"daily_required:{str(daily_required).lower()}")
|
|
540
|
+
|
|
541
|
+
if strict and missing:
|
|
542
|
+
continue
|
|
543
|
+
results.append({
|
|
544
|
+
"name": info.name,
|
|
545
|
+
"display_name": info.display_name,
|
|
546
|
+
"description": info.description,
|
|
547
|
+
"version": info.version,
|
|
548
|
+
"category": info.category,
|
|
549
|
+
"tags": list(info.tags),
|
|
550
|
+
"market_scope": list(info.market_scope),
|
|
551
|
+
"style": dict(info.style),
|
|
552
|
+
"data_requirements": list(info.data_requirements),
|
|
553
|
+
"requires_daily_features": info.requires_daily_features,
|
|
554
|
+
"required_snapshot_fields": list(info.required_snapshot_fields),
|
|
555
|
+
"required_daily_fields": list(info.required_daily_fields),
|
|
556
|
+
"factor_weights": dict(info.factor_weights),
|
|
557
|
+
"active_filters": list(info.active_filters),
|
|
558
|
+
"profile_keys": dict(info.profile_keys),
|
|
559
|
+
"score": round(score, 2),
|
|
560
|
+
"matched": matched,
|
|
561
|
+
"missing": missing,
|
|
562
|
+
})
|
|
563
|
+
|
|
564
|
+
results.sort(key=lambda item: (-float(item["score"]), str(item["name"])))
|
|
565
|
+
if limit is not None:
|
|
566
|
+
results = results[:max(limit, 0)]
|
|
567
|
+
return results
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def compare_strategies(
|
|
571
|
+
base_name: str,
|
|
572
|
+
target_name: str,
|
|
573
|
+
strategies_dir: Path | None = None,
|
|
574
|
+
) -> dict[str, object]:
|
|
575
|
+
"""Compare two enabled strategies for strategy review and UI diff views."""
|
|
576
|
+
from alphasift.config import Config
|
|
577
|
+
from alphasift.filter import requires_daily_features
|
|
578
|
+
|
|
579
|
+
if strategies_dir is None:
|
|
580
|
+
strategies_dir = Config.from_env().strategies_dir
|
|
581
|
+
strategies = load_all_strategies(strategies_dir)
|
|
582
|
+
try:
|
|
583
|
+
base = strategies[base_name]
|
|
584
|
+
target = strategies[target_name]
|
|
585
|
+
except KeyError as exc:
|
|
586
|
+
missing = exc.args[0]
|
|
587
|
+
raise ValueError(f"Strategy '{missing}' not found") from exc
|
|
588
|
+
|
|
589
|
+
base_daily = requires_daily_features(base.screening.hard_filters)
|
|
590
|
+
target_daily = requires_daily_features(target.screening.hard_filters)
|
|
591
|
+
differences = {
|
|
592
|
+
"identity": _mapping_diff(
|
|
593
|
+
{
|
|
594
|
+
"version": base.version,
|
|
595
|
+
"category": base.category,
|
|
596
|
+
"market_scope": list(base.screening.market_scope),
|
|
597
|
+
"requires_daily_features": base_daily,
|
|
598
|
+
},
|
|
599
|
+
{
|
|
600
|
+
"version": target.version,
|
|
601
|
+
"category": target.category,
|
|
602
|
+
"market_scope": list(target.screening.market_scope),
|
|
603
|
+
"requires_daily_features": target_daily,
|
|
604
|
+
},
|
|
605
|
+
),
|
|
606
|
+
"tags": _list_diff(base.tags, target.tags),
|
|
607
|
+
"style": _mapping_diff(_style_to_dict(base.style), _style_to_dict(target.style)),
|
|
608
|
+
"data_requirements": _list_diff(
|
|
609
|
+
_strategy_data_requirements(base, daily_required=base_daily),
|
|
610
|
+
_strategy_data_requirements(target, daily_required=target_daily),
|
|
611
|
+
),
|
|
612
|
+
"required_snapshot_fields": _list_diff(
|
|
613
|
+
_required_snapshot_fields(base.screening.hard_filters),
|
|
614
|
+
_required_snapshot_fields(target.screening.hard_filters),
|
|
615
|
+
),
|
|
616
|
+
"required_daily_fields": _list_diff(
|
|
617
|
+
_required_daily_fields(base.screening.hard_filters),
|
|
618
|
+
_required_daily_fields(target.screening.hard_filters),
|
|
619
|
+
),
|
|
620
|
+
"active_filters": _list_diff(
|
|
621
|
+
_active_hard_filters(base.screening.hard_filters),
|
|
622
|
+
_active_hard_filters(target.screening.hard_filters),
|
|
623
|
+
),
|
|
624
|
+
"hard_filter_values": _mapping_diff(
|
|
625
|
+
_active_filter_values(base.screening.hard_filters),
|
|
626
|
+
_active_filter_values(target.screening.hard_filters),
|
|
627
|
+
),
|
|
628
|
+
"factor_weights": _numeric_mapping_diff(
|
|
629
|
+
base.screening.factor_weights,
|
|
630
|
+
target.screening.factor_weights,
|
|
631
|
+
),
|
|
632
|
+
"profile_keys": _nested_list_diff(
|
|
633
|
+
_strategy_profile_keys(base.screening),
|
|
634
|
+
_strategy_profile_keys(target.screening),
|
|
635
|
+
),
|
|
636
|
+
}
|
|
637
|
+
return {
|
|
638
|
+
"base": _strategy_compare_summary(base, daily_required=base_daily),
|
|
639
|
+
"target": _strategy_compare_summary(target, daily_required=target_daily),
|
|
640
|
+
"differences": differences,
|
|
641
|
+
"summary": _strategy_compare_summary_notes(differences),
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _strategy_data_requirements(strategy: Strategy, *, daily_required: bool) -> list[str]:
|
|
646
|
+
requirements = ["snapshot"]
|
|
647
|
+
if daily_required:
|
|
648
|
+
requirements.append("daily_k")
|
|
649
|
+
factors = set(strategy.screening.factor_weights)
|
|
650
|
+
if factors & {"theme_heat", "topic_alignment"}:
|
|
651
|
+
requirements.append("industry_context")
|
|
652
|
+
if strategy.screening.event_profile:
|
|
653
|
+
requirements.append("event_context")
|
|
654
|
+
return requirements
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def _strategy_compare_summary(strategy: Strategy, *, daily_required: bool) -> dict[str, object]:
|
|
658
|
+
return {
|
|
659
|
+
"name": strategy.name,
|
|
660
|
+
"display_name": strategy.display_name,
|
|
661
|
+
"version": strategy.version,
|
|
662
|
+
"category": strategy.category,
|
|
663
|
+
"tags": list(strategy.tags),
|
|
664
|
+
"style": _style_to_dict(strategy.style),
|
|
665
|
+
"data_requirements": _strategy_data_requirements(strategy, daily_required=daily_required),
|
|
666
|
+
"requires_daily_features": daily_required,
|
|
667
|
+
"active_filters": _active_hard_filters(strategy.screening.hard_filters),
|
|
668
|
+
"factor_weights": {key: float(value) for key, value in strategy.screening.factor_weights.items()},
|
|
669
|
+
"profile_keys": _strategy_profile_keys(strategy.screening),
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _strategy_compare_summary_notes(differences: dict[str, object]) -> dict[str, object]:
|
|
674
|
+
changed_sections = [
|
|
675
|
+
name
|
|
676
|
+
for name, value in differences.items()
|
|
677
|
+
if _diff_has_changes(value)
|
|
678
|
+
]
|
|
679
|
+
notes: list[str] = []
|
|
680
|
+
data_diff = differences.get("data_requirements", {})
|
|
681
|
+
if isinstance(data_diff, dict):
|
|
682
|
+
added = data_diff.get("added", [])
|
|
683
|
+
removed = data_diff.get("removed", [])
|
|
684
|
+
if added:
|
|
685
|
+
notes.append("target_requires_additional_data:" + ",".join(str(item) for item in added))
|
|
686
|
+
if removed:
|
|
687
|
+
notes.append("target_removes_data:" + ",".join(str(item) for item in removed))
|
|
688
|
+
identity_diff = differences.get("identity", {})
|
|
689
|
+
if isinstance(identity_diff, dict) and "requires_daily_features" in identity_diff.get("changed", {}):
|
|
690
|
+
notes.append("daily_feature_requirement_changed")
|
|
691
|
+
return {
|
|
692
|
+
"changed_sections": changed_sections,
|
|
693
|
+
"change_count": len(changed_sections),
|
|
694
|
+
"compatibility_notes": notes,
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _diff_has_changes(value: object) -> bool:
|
|
699
|
+
if not isinstance(value, dict):
|
|
700
|
+
return bool(value)
|
|
701
|
+
for key in ("added", "removed", "changed"):
|
|
702
|
+
item = value.get(key)
|
|
703
|
+
if item:
|
|
704
|
+
return True
|
|
705
|
+
for item in value.values():
|
|
706
|
+
if isinstance(item, dict) and _diff_has_changes(item):
|
|
707
|
+
return True
|
|
708
|
+
return False
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _active_filter_values(filters_config: HardFilterConfig) -> dict[str, object]:
|
|
712
|
+
active = set(_active_hard_filters(filters_config))
|
|
713
|
+
values = asdict(filters_config)
|
|
714
|
+
return {
|
|
715
|
+
key: value
|
|
716
|
+
for key, value in values.items()
|
|
717
|
+
if key in active
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _list_diff(base: list[object], target: list[object]) -> dict[str, list[object]]:
|
|
722
|
+
base_values = list(dict.fromkeys(base))
|
|
723
|
+
target_values = list(dict.fromkeys(target))
|
|
724
|
+
return {
|
|
725
|
+
"shared": [item for item in base_values if item in target_values],
|
|
726
|
+
"added": [item for item in target_values if item not in base_values],
|
|
727
|
+
"removed": [item for item in base_values if item not in target_values],
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def _mapping_diff(base: dict[str, object], target: dict[str, object]) -> dict[str, object]:
|
|
732
|
+
base_keys = set(base)
|
|
733
|
+
target_keys = set(target)
|
|
734
|
+
changed = {}
|
|
735
|
+
for key in sorted(base_keys & target_keys):
|
|
736
|
+
if base[key] != target[key]:
|
|
737
|
+
changed[key] = {
|
|
738
|
+
"base": base[key],
|
|
739
|
+
"target": target[key],
|
|
740
|
+
}
|
|
741
|
+
return {
|
|
742
|
+
"added": {key: target[key] for key in sorted(target_keys - base_keys)},
|
|
743
|
+
"removed": {key: base[key] for key in sorted(base_keys - target_keys)},
|
|
744
|
+
"changed": changed,
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _numeric_mapping_diff(base: dict[str, object], target: dict[str, object]) -> dict[str, object]:
|
|
749
|
+
diff = _mapping_diff(
|
|
750
|
+
{key: float(value) for key, value in base.items()},
|
|
751
|
+
{key: float(value) for key, value in target.items()},
|
|
752
|
+
)
|
|
753
|
+
changed = diff.get("changed", {})
|
|
754
|
+
if isinstance(changed, dict):
|
|
755
|
+
for item in changed.values():
|
|
756
|
+
if isinstance(item, dict):
|
|
757
|
+
item["delta"] = round(float(item["target"]) - float(item["base"]), 6)
|
|
758
|
+
return diff
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _nested_list_diff(
|
|
762
|
+
base: dict[str, list[str]],
|
|
763
|
+
target: dict[str, list[str]],
|
|
764
|
+
) -> dict[str, object]:
|
|
765
|
+
keys = sorted(set(base) | set(target))
|
|
766
|
+
return {
|
|
767
|
+
key: _list_diff(base.get(key, []), target.get(key, []))
|
|
768
|
+
for key in keys
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def _active_hard_filters(filters_config: HardFilterConfig) -> list[str]:
|
|
773
|
+
active: list[str] = []
|
|
774
|
+
defaults = HardFilterConfig()
|
|
775
|
+
for item in fields(HardFilterConfig):
|
|
776
|
+
name = item.name
|
|
777
|
+
value = getattr(filters_config, name)
|
|
778
|
+
default = getattr(defaults, name)
|
|
779
|
+
if name == "exclude_st":
|
|
780
|
+
if bool(value):
|
|
781
|
+
active.append(name)
|
|
782
|
+
continue
|
|
783
|
+
if value != default and value is not None and value is not False:
|
|
784
|
+
active.append(name)
|
|
785
|
+
return active
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _required_snapshot_fields(filters_config: HardFilterConfig) -> list[str]:
|
|
789
|
+
fields: list[str] = []
|
|
790
|
+
if filters_config.exclude_st:
|
|
791
|
+
fields.append("name")
|
|
792
|
+
if filters_config.amount_min is not None:
|
|
793
|
+
fields.append("amount")
|
|
794
|
+
if filters_config.avg_amount_usd_min is not None:
|
|
795
|
+
fields.append("avg_amount_usd")
|
|
796
|
+
if filters_config.price_min is not None or filters_config.price_max is not None:
|
|
797
|
+
fields.append("price")
|
|
798
|
+
if filters_config.market_cap_min is not None or filters_config.market_cap_max is not None:
|
|
799
|
+
fields.append("total_mv")
|
|
800
|
+
if filters_config.pe_ttm_min is not None or filters_config.pe_ttm_max is not None:
|
|
801
|
+
fields.append("pe_ratio")
|
|
802
|
+
if filters_config.pb_min is not None or filters_config.pb_max is not None:
|
|
803
|
+
fields.append("pb_ratio")
|
|
804
|
+
if filters_config.volume_ratio_min is not None:
|
|
805
|
+
fields.append("volume_ratio")
|
|
806
|
+
if filters_config.turnover_rate_min is not None:
|
|
807
|
+
fields.append("turnover_rate")
|
|
808
|
+
if filters_config.change_pct_min is not None or filters_config.change_pct_max is not None:
|
|
809
|
+
fields.append("change_pct")
|
|
810
|
+
return list(dict.fromkeys(fields))
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def _required_daily_fields(filters_config: HardFilterConfig) -> list[str]:
|
|
814
|
+
checks = [
|
|
815
|
+
("change_60d", filters_config.change_60d_min is not None or filters_config.change_60d_max is not None),
|
|
816
|
+
("ma_bullish", filters_config.require_ma_bullish),
|
|
817
|
+
("price_above_ma20", filters_config.require_price_above_ma20),
|
|
818
|
+
("signal_score", filters_config.signal_score_min is not None),
|
|
819
|
+
("macd_status", bool(filters_config.macd_status_whitelist)),
|
|
820
|
+
("rsi_status", bool(filters_config.rsi_status_whitelist)),
|
|
821
|
+
(
|
|
822
|
+
"breakout_20d_pct",
|
|
823
|
+
filters_config.breakout_20d_pct_min is not None
|
|
824
|
+
or filters_config.breakout_20d_pct_max is not None,
|
|
825
|
+
),
|
|
826
|
+
("range_20d_pct", filters_config.range_20d_pct_max is not None),
|
|
827
|
+
(
|
|
828
|
+
"volume_ratio_20d",
|
|
829
|
+
filters_config.volume_ratio_20d_min is not None
|
|
830
|
+
or filters_config.volume_ratio_20d_max is not None,
|
|
831
|
+
),
|
|
832
|
+
("body_pct", filters_config.body_pct_min is not None or filters_config.body_pct_max is not None),
|
|
833
|
+
(
|
|
834
|
+
"pullback_to_ma20_pct",
|
|
835
|
+
filters_config.pullback_to_ma20_pct_min is not None
|
|
836
|
+
or filters_config.pullback_to_ma20_pct_max is not None,
|
|
837
|
+
),
|
|
838
|
+
(
|
|
839
|
+
"consolidation_days_20d",
|
|
840
|
+
filters_config.consolidation_days_20d_min is not None
|
|
841
|
+
or filters_config.consolidation_days_20d_max is not None,
|
|
842
|
+
),
|
|
843
|
+
(
|
|
844
|
+
"volatility_20d_pct",
|
|
845
|
+
filters_config.volatility_20d_pct_min is not None
|
|
846
|
+
or filters_config.volatility_20d_pct_max is not None,
|
|
847
|
+
),
|
|
848
|
+
(
|
|
849
|
+
"max_drawdown_20d_pct",
|
|
850
|
+
filters_config.max_drawdown_20d_pct_min is not None
|
|
851
|
+
or filters_config.max_drawdown_20d_pct_max is not None,
|
|
852
|
+
),
|
|
853
|
+
("atr_20_pct", filters_config.atr_20_pct_min is not None or filters_config.atr_20_pct_max is not None),
|
|
854
|
+
]
|
|
855
|
+
return [field for field, enabled in checks if enabled]
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _strategy_profile_keys(screening: ScreeningConfig) -> dict[str, list[str]]:
|
|
859
|
+
profile_values = {
|
|
860
|
+
"scoring": screening.scoring_profile,
|
|
861
|
+
"risk": screening.risk_profile,
|
|
862
|
+
"portfolio": screening.portfolio_profile,
|
|
863
|
+
"scorecard": screening.scorecard_profile,
|
|
864
|
+
"event": screening.event_profile,
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
name: sorted(value)
|
|
868
|
+
for name, value in profile_values.items()
|
|
869
|
+
if value
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def _strategy_style(data: dict, filepath: Path) -> StrategyStyle:
|
|
874
|
+
raw = data.get("style", {})
|
|
875
|
+
if raw is None:
|
|
876
|
+
raw = {}
|
|
877
|
+
if not isinstance(raw, dict):
|
|
878
|
+
raise ValueError(f"Invalid style section in strategy file: {filepath}")
|
|
879
|
+
_raise_unknown_keys(raw, _STYLE_KEYS, f"style section of {filepath.name}")
|
|
880
|
+
inferred = _infer_strategy_style(
|
|
881
|
+
category=str(data.get("category", "trend")),
|
|
882
|
+
tags=[str(item) for item in data.get("tags", []) or []],
|
|
883
|
+
)
|
|
884
|
+
return StrategyStyle(
|
|
885
|
+
risk_profile=str(raw.get("risk_profile") or inferred.risk_profile),
|
|
886
|
+
holding_period=str(raw.get("holding_period") or inferred.holding_period),
|
|
887
|
+
execution_style=str(raw.get("execution_style") or inferred.execution_style),
|
|
888
|
+
market_regime=_string_list(raw.get("market_regime") or inferred.market_regime),
|
|
889
|
+
capital_profile=str(raw.get("capital_profile") or inferred.capital_profile),
|
|
890
|
+
ui_badge=str(raw.get("ui_badge") or inferred.ui_badge),
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _infer_strategy_style(*, category: str, tags: list[str]) -> StrategyStyle:
|
|
895
|
+
tag_set = {tag.lower() for tag in tags}
|
|
896
|
+
if category == "value" or "defensive" in tag_set:
|
|
897
|
+
risk_profile = "defensive"
|
|
898
|
+
elif category in {"momentum", "trend"}:
|
|
899
|
+
risk_profile = "aggressive"
|
|
900
|
+
else:
|
|
901
|
+
risk_profile = "balanced"
|
|
902
|
+
|
|
903
|
+
if "short_term" in tag_set or category == "momentum":
|
|
904
|
+
holding_period = "short_term"
|
|
905
|
+
elif "daily_k" in tag_set or "trend" in tag_set:
|
|
906
|
+
holding_period = "swing"
|
|
907
|
+
else:
|
|
908
|
+
holding_period = "watchlist"
|
|
909
|
+
|
|
910
|
+
if category == "value":
|
|
911
|
+
execution_style = "mean_reversion"
|
|
912
|
+
elif category == "reversal":
|
|
913
|
+
execution_style = "reversal"
|
|
914
|
+
elif category in {"momentum", "trend"}:
|
|
915
|
+
execution_style = "trend_following"
|
|
916
|
+
else:
|
|
917
|
+
execution_style = "multi_factor"
|
|
918
|
+
|
|
919
|
+
if risk_profile == "defensive":
|
|
920
|
+
market_regime = ["risk_off", "range_bound"]
|
|
921
|
+
elif execution_style == "trend_following":
|
|
922
|
+
market_regime = ["risk_on", "trend"]
|
|
923
|
+
elif execution_style == "reversal":
|
|
924
|
+
market_regime = ["oversold_repair", "range_bound"]
|
|
925
|
+
else:
|
|
926
|
+
market_regime = ["neutral"]
|
|
927
|
+
|
|
928
|
+
return StrategyStyle(
|
|
929
|
+
risk_profile=risk_profile,
|
|
930
|
+
holding_period=holding_period,
|
|
931
|
+
execution_style=execution_style,
|
|
932
|
+
market_regime=market_regime,
|
|
933
|
+
capital_profile="medium_liquidity",
|
|
934
|
+
ui_badge=category,
|
|
935
|
+
)
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def _style_to_dict(style: StrategyStyle) -> dict[str, object]:
|
|
939
|
+
return {
|
|
940
|
+
"risk_profile": style.risk_profile,
|
|
941
|
+
"holding_period": style.holding_period,
|
|
942
|
+
"execution_style": style.execution_style,
|
|
943
|
+
"market_regime": list(style.market_regime),
|
|
944
|
+
"capital_profile": style.capital_profile,
|
|
945
|
+
"ui_badge": style.ui_badge,
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def _string_list(value: object) -> list[str]:
|
|
950
|
+
if isinstance(value, list):
|
|
951
|
+
return [str(item) for item in value if str(item).strip()]
|
|
952
|
+
if isinstance(value, str):
|
|
953
|
+
return [item.strip() for item in value.split(",") if item.strip()]
|
|
954
|
+
return []
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
def _normalized_values(values: object) -> list[str]:
|
|
958
|
+
raw = _string_list(values)
|
|
959
|
+
normalized = []
|
|
960
|
+
seen = set()
|
|
961
|
+
for item in raw:
|
|
962
|
+
token = item.strip().lower()
|
|
963
|
+
if not token or token in seen:
|
|
964
|
+
continue
|
|
965
|
+
normalized.append(token)
|
|
966
|
+
seen.add(token)
|
|
967
|
+
return normalized
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def _match_single(
|
|
971
|
+
expected: str,
|
|
972
|
+
actual: str,
|
|
973
|
+
label: str,
|
|
974
|
+
weight: float,
|
|
975
|
+
matched: list[str],
|
|
976
|
+
missing: list[str],
|
|
977
|
+
) -> float:
|
|
978
|
+
expected_normalized = expected.strip().lower()
|
|
979
|
+
if not expected_normalized:
|
|
980
|
+
return 0.0
|
|
981
|
+
if actual.strip().lower() == expected_normalized:
|
|
982
|
+
matched.append(f"{label}:{expected_normalized}")
|
|
983
|
+
return weight
|
|
984
|
+
missing.append(f"{label}:{expected_normalized}")
|
|
985
|
+
return 0.0
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def _match_many(
|
|
989
|
+
expected: list[str],
|
|
990
|
+
actual: list[str],
|
|
991
|
+
label: str,
|
|
992
|
+
weight: float,
|
|
993
|
+
matched: list[str],
|
|
994
|
+
missing: list[str],
|
|
995
|
+
) -> float:
|
|
996
|
+
if not expected:
|
|
997
|
+
return 0.0
|
|
998
|
+
actual_set = set(actual)
|
|
999
|
+
score = 0.0
|
|
1000
|
+
for item in expected:
|
|
1001
|
+
if item in actual_set:
|
|
1002
|
+
matched.append(f"{label}:{item}")
|
|
1003
|
+
score += weight
|
|
1004
|
+
else:
|
|
1005
|
+
missing.append(f"{label}:{item}")
|
|
1006
|
+
return score
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def _validate_strategy_dir_sync(strategies_dir: Path) -> None:
|
|
1010
|
+
"""Fail fast if bundled strategy mirrors drift apart from built-in repo files."""
|
|
1011
|
+
resolved = strategies_dir.resolve()
|
|
1012
|
+
repo_dir = (_PROJECT_ROOT / "strategies").resolve()
|
|
1013
|
+
bundled_dir = _BUNDLED_STRATEGIES_DIR.resolve()
|
|
1014
|
+
if resolved != repo_dir or not bundled_dir.is_dir():
|
|
1015
|
+
return
|
|
1016
|
+
|
|
1017
|
+
repo_files = {f.name: f for f in repo_dir.glob("*.yaml")}
|
|
1018
|
+
bundled_files = {f.name: f for f in bundled_dir.glob("*.yaml")}
|
|
1019
|
+
missing_from_repo = bundled_files.keys() - repo_files.keys()
|
|
1020
|
+
if missing_from_repo:
|
|
1021
|
+
raise RuntimeError(
|
|
1022
|
+
"Strategy directories are out of sync: bundled strategies are missing from "
|
|
1023
|
+
f"strategies/: {', '.join(sorted(missing_from_repo))}."
|
|
1024
|
+
)
|
|
1025
|
+
|
|
1026
|
+
for name, bundled_file in bundled_files.items():
|
|
1027
|
+
repo_file = repo_files[name]
|
|
1028
|
+
if repo_file.read_bytes() != bundled_files[name].read_bytes():
|
|
1029
|
+
raise RuntimeError(
|
|
1030
|
+
"Strategy directories are out of sync: "
|
|
1031
|
+
f"strategies/{name} does not match alphasift/strategies/{name}."
|
|
1032
|
+
)
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def _raise_unknown_keys(data: dict, allowed_keys: set[str], context: str) -> None:
|
|
1036
|
+
unknown_keys = sorted(set(data.keys()) - allowed_keys)
|
|
1037
|
+
if unknown_keys:
|
|
1038
|
+
raise ValueError(
|
|
1039
|
+
f"Unknown keys in {context}: {', '.join(unknown_keys)}"
|
|
1040
|
+
)
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _scoring_profile(screening_data: dict, filepath: Path) -> dict:
|
|
1044
|
+
profile = _optional_mapping(
|
|
1045
|
+
screening_data, "scoring_profile", filepath, allowed_keys=_SCORING_PROFILE_KEYS
|
|
1046
|
+
)
|
|
1047
|
+
if "factor_rank_blend" in profile:
|
|
1048
|
+
raw = profile["factor_rank_blend"]
|
|
1049
|
+
err = (
|
|
1050
|
+
f"Invalid scoring_profile.factor_rank_blend in {filepath.name}: {raw!r} "
|
|
1051
|
+
"(expected finite float between 0.0 and 1.0)"
|
|
1052
|
+
)
|
|
1053
|
+
if isinstance(raw, bool):
|
|
1054
|
+
raise ValueError(err)
|
|
1055
|
+
try:
|
|
1056
|
+
val = float(raw)
|
|
1057
|
+
except (TypeError, ValueError) as exc:
|
|
1058
|
+
raise ValueError(err) from exc
|
|
1059
|
+
if not math.isfinite(val) or not (0.0 <= val <= 1.0):
|
|
1060
|
+
raise ValueError(err)
|
|
1061
|
+
return profile
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def _portfolio_profile(screening_data: dict, filepath: Path) -> dict:
|
|
1065
|
+
profile = _optional_mapping(
|
|
1066
|
+
screening_data, "portfolio_profile", filepath, allowed_keys=_PORTFOLIO_PROFILE_KEYS
|
|
1067
|
+
)
|
|
1068
|
+
mode = str(profile.get("mode", "soft")).strip().lower()
|
|
1069
|
+
if mode not in _PORTFOLIO_MODES:
|
|
1070
|
+
raise ValueError(
|
|
1071
|
+
f"Invalid portfolio_profile.mode in {filepath.name}: {profile.get('mode')!r} "
|
|
1072
|
+
f"(expected one of: {', '.join(sorted(_PORTFOLIO_MODES))})"
|
|
1073
|
+
)
|
|
1074
|
+
return profile
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _optional_mapping(
|
|
1078
|
+
data: dict,
|
|
1079
|
+
key: str,
|
|
1080
|
+
filepath: Path,
|
|
1081
|
+
*,
|
|
1082
|
+
allowed_keys: set[str],
|
|
1083
|
+
) -> dict:
|
|
1084
|
+
value = data.get(key, {})
|
|
1085
|
+
if value is None:
|
|
1086
|
+
return {}
|
|
1087
|
+
if not isinstance(value, dict):
|
|
1088
|
+
raise ValueError(f"Invalid {key} section in strategy file: {filepath}")
|
|
1089
|
+
_raise_unknown_keys(value, allowed_keys, f"{key} section of {filepath.name}")
|
|
1090
|
+
return value
|