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/cli.py
ADDED
|
@@ -0,0 +1,2797 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""CLI entry point."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import asdict
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from alphasift import __version__
|
|
14
|
+
from alphasift.audit import audit_project
|
|
15
|
+
from alphasift.config import Config
|
|
16
|
+
from alphasift.doctor import doctor_data_sources, doctor_radar_readiness, write_doctor_report
|
|
17
|
+
from alphasift.dsa import check_dsa_readiness
|
|
18
|
+
from alphasift.evaluate import evaluate_saved_run, evaluate_saved_runs, evaluate_saved_runs_by_windows
|
|
19
|
+
from alphasift.hotspot import (
|
|
20
|
+
append_hotspot_history,
|
|
21
|
+
discover_hotspots,
|
|
22
|
+
get_hotspot_detail,
|
|
23
|
+
hotspot_detail_to_dict,
|
|
24
|
+
save_hotspots_json,
|
|
25
|
+
)
|
|
26
|
+
from alphasift.industry import fetch_akshare_board_map, save_industry_map
|
|
27
|
+
from alphasift.overview import build_overview
|
|
28
|
+
from alphasift.performance_history import build_strategy_performance_summary
|
|
29
|
+
from alphasift.pipeline import screen
|
|
30
|
+
from alphasift.report import (
|
|
31
|
+
build_run_report_payload,
|
|
32
|
+
render_run_report_markdown,
|
|
33
|
+
report_payload_to_json,
|
|
34
|
+
write_run_report,
|
|
35
|
+
)
|
|
36
|
+
from alphasift.server import serve_api
|
|
37
|
+
from alphasift.store import (
|
|
38
|
+
evaluation_result_to_jsonl,
|
|
39
|
+
list_saved_runs,
|
|
40
|
+
load_screen_result,
|
|
41
|
+
save_evaluation_result,
|
|
42
|
+
save_screen_result,
|
|
43
|
+
screen_result_to_jsonl,
|
|
44
|
+
)
|
|
45
|
+
from alphasift.strategy import compare_strategies, list_strategies, match_strategies
|
|
46
|
+
from alphasift.strategy_templates import (
|
|
47
|
+
get_strategy_template,
|
|
48
|
+
list_strategy_templates,
|
|
49
|
+
render_strategy_template,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main():
|
|
54
|
+
logging.basicConfig(
|
|
55
|
+
level=logging.INFO,
|
|
56
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
57
|
+
)
|
|
58
|
+
parser = argparse.ArgumentParser(prog="alphasift", description="自动选股 Skill")
|
|
59
|
+
parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
|
|
60
|
+
parser.add_argument(
|
|
61
|
+
"--env-file",
|
|
62
|
+
action="append",
|
|
63
|
+
default=None,
|
|
64
|
+
help="加载额外 .env 文件,可重复;用于复用 daily_stock_analysis/daily_ai_assistant 配置",
|
|
65
|
+
)
|
|
66
|
+
sub = parser.add_subparsers(dest="command")
|
|
67
|
+
|
|
68
|
+
# screen
|
|
69
|
+
sp = sub.add_parser("screen", help="执行选股")
|
|
70
|
+
sp.add_argument("strategy", help="策略名称")
|
|
71
|
+
sp.add_argument(
|
|
72
|
+
"--market", default="cn",
|
|
73
|
+
help="市场:cn(A 股)、us、hk、jp、kr、tw、in;非 A 股通过 Yahoo 筛选器获取快照",
|
|
74
|
+
)
|
|
75
|
+
sp.add_argument("--max-output", type=int, default=None)
|
|
76
|
+
sp.add_argument("--no-llm", action="store_true", help="不使用 LLM 排序")
|
|
77
|
+
sp.add_argument(
|
|
78
|
+
"--context",
|
|
79
|
+
default=None,
|
|
80
|
+
help="传给 LLM 的市场/新闻/主题上下文,不参与硬筛,只用于候选相对排序",
|
|
81
|
+
)
|
|
82
|
+
sp.add_argument(
|
|
83
|
+
"--context-file",
|
|
84
|
+
action="append",
|
|
85
|
+
default=None,
|
|
86
|
+
help="追加传给 LLM 的上下文文本文件,可重复",
|
|
87
|
+
)
|
|
88
|
+
sp.add_argument(
|
|
89
|
+
"--candidate-context-file",
|
|
90
|
+
action="append",
|
|
91
|
+
default=None,
|
|
92
|
+
help="追加候选级上下文 CSV/JSON/JSONL,需包含 code,可含 news/announcement/fund_flow/text 等列",
|
|
93
|
+
)
|
|
94
|
+
sp.add_argument(
|
|
95
|
+
"--collect-candidate-context",
|
|
96
|
+
action="store_true",
|
|
97
|
+
help="对送入 LLM 的 Top K 候选抓取新闻/公告/资金流线索,默认关闭",
|
|
98
|
+
)
|
|
99
|
+
sp.add_argument(
|
|
100
|
+
"--candidate-context-max-candidates",
|
|
101
|
+
type=int,
|
|
102
|
+
default=None,
|
|
103
|
+
help="最多对前 N 个 LLM 候选抓取外部线索",
|
|
104
|
+
)
|
|
105
|
+
sp.add_argument(
|
|
106
|
+
"--candidate-context-provider",
|
|
107
|
+
action="append",
|
|
108
|
+
default=None,
|
|
109
|
+
help="候选级抓取来源:news、announcement、fund_flow;可重复或逗号分隔",
|
|
110
|
+
)
|
|
111
|
+
sp.add_argument(
|
|
112
|
+
"--industry-map-file",
|
|
113
|
+
action="append",
|
|
114
|
+
default=None,
|
|
115
|
+
help="追加 code->industry/concepts 映射 CSV/JSON/JSONL,可重复",
|
|
116
|
+
)
|
|
117
|
+
sp.add_argument(
|
|
118
|
+
"--industry-provider",
|
|
119
|
+
default=None,
|
|
120
|
+
help="可选行业/概念映射 provider,例如 akshare;默认读取 INDUSTRY_PROVIDER",
|
|
121
|
+
)
|
|
122
|
+
sp.add_argument(
|
|
123
|
+
"--post-analyzer",
|
|
124
|
+
action="append",
|
|
125
|
+
default=None,
|
|
126
|
+
help="追加 L3 后置分析器:scorecard、dsa、external_http;可重复或逗号分隔",
|
|
127
|
+
)
|
|
128
|
+
sp.add_argument(
|
|
129
|
+
"--no-post-analysis",
|
|
130
|
+
action="store_true",
|
|
131
|
+
help="关闭默认 L3 后置评分器和其他后置分析器",
|
|
132
|
+
)
|
|
133
|
+
sp.add_argument(
|
|
134
|
+
"--post-analysis-max-picks",
|
|
135
|
+
type=int,
|
|
136
|
+
default=None,
|
|
137
|
+
help="最多对前 N 只候选运行 L3 后置分析器",
|
|
138
|
+
)
|
|
139
|
+
sp.add_argument("--deep-analysis", action="store_true", help="兼容参数:等同启用 --post-analyzer dsa")
|
|
140
|
+
sp.add_argument(
|
|
141
|
+
"--deep-analysis-max-picks",
|
|
142
|
+
type=int,
|
|
143
|
+
default=None,
|
|
144
|
+
help="最多对前 N 只候选调用 DSA(默认使用环境变量或 3)",
|
|
145
|
+
)
|
|
146
|
+
sp.add_argument(
|
|
147
|
+
"--daily-enrich",
|
|
148
|
+
dest="daily_enrich",
|
|
149
|
+
action="store_true",
|
|
150
|
+
default=None,
|
|
151
|
+
help="对 L1 后的 Top N 候选补充日 K 特征",
|
|
152
|
+
)
|
|
153
|
+
sp.add_argument(
|
|
154
|
+
"--no-daily-enrich",
|
|
155
|
+
dest="daily_enrich",
|
|
156
|
+
action="store_false",
|
|
157
|
+
help="即使环境变量开启也不做可选日 K 增强;策略必需的日 K 过滤仍会执行",
|
|
158
|
+
)
|
|
159
|
+
sp.add_argument(
|
|
160
|
+
"--daily-enrich-max-candidates",
|
|
161
|
+
type=int,
|
|
162
|
+
default=None,
|
|
163
|
+
help="日 K 增强最多处理的候选数",
|
|
164
|
+
)
|
|
165
|
+
sp.add_argument("--explain-filters", action="store_true", help="输出 hard filter waterfall 诊断")
|
|
166
|
+
sp.add_argument("--save-run", action="store_true", help="保存本次运行到 ALPHASIFT_DATA_DIR/runs")
|
|
167
|
+
sp.add_argument("--output", default=None, help="额外写出结果到指定路径")
|
|
168
|
+
sp.add_argument("--jsonl", action="store_true", help="以 JSONL 输出")
|
|
169
|
+
sp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
170
|
+
|
|
171
|
+
# strategies
|
|
172
|
+
stp = sub.add_parser("strategies", help="列出可用策略")
|
|
173
|
+
stp.add_argument("--json", action="store_true", help="以 JSON 输出完整策略目录元数据")
|
|
174
|
+
stp.add_argument("--explain", action="store_true", help="输出包含数据依赖和主要因子的可读策略目录")
|
|
175
|
+
stp.add_argument("--compare", nargs=2, metavar=("BASE", "TARGET"), help="对比两套策略的风格、依赖、硬筛和权重")
|
|
176
|
+
stp.add_argument("--templates", action="store_true", help="列出可复用的策略编写模板")
|
|
177
|
+
stp.add_argument("--template", default=None, help="输出指定策略模板 YAML")
|
|
178
|
+
stp.add_argument("--risk-profile", default=None, help="按风险风格匹配:defensive / balanced / aggressive")
|
|
179
|
+
stp.add_argument("--holding-period", default=None, help="按持有周期匹配:short_term / swing / watchlist")
|
|
180
|
+
stp.add_argument("--execution-style", default=None, help="按执行风格匹配,例如 mean_reversion / breakout")
|
|
181
|
+
stp.add_argument("--market-regime", action="append", default=None, help="按行情环境匹配,可重复或逗号分隔")
|
|
182
|
+
stp.add_argument("--capital-profile", default=None, help="按流动性/容量风格匹配")
|
|
183
|
+
stp.add_argument("--data-requirement", action="append", default=None, help="按数据依赖匹配,可重复或逗号分隔")
|
|
184
|
+
stp.add_argument("--tag", action="append", default=None, help="按策略标签匹配,可重复或逗号分隔")
|
|
185
|
+
stp.add_argument("--category", default=None, help="按策略分类匹配")
|
|
186
|
+
stp.add_argument(
|
|
187
|
+
"--daily-required",
|
|
188
|
+
choices=["any", "true", "false"],
|
|
189
|
+
default="any",
|
|
190
|
+
help="按是否依赖日 K 特征匹配",
|
|
191
|
+
)
|
|
192
|
+
stp.add_argument("--strict", action="store_true", help="只返回满足全部匹配条件的策略")
|
|
193
|
+
stp.add_argument("--limit", type=int, default=None, help="最多返回 N 个策略匹配结果")
|
|
194
|
+
|
|
195
|
+
# evaluate
|
|
196
|
+
ep = sub.add_parser("evaluate", help="用最新快照评估已保存的选股结果")
|
|
197
|
+
ep.add_argument("run", help="run_id 或保存的 run JSON 文件路径")
|
|
198
|
+
ep.add_argument("--save", action="store_true", help="保存评估结果到 ALPHASIFT_DATA_DIR/evaluations")
|
|
199
|
+
ep.add_argument("--output", default=None, help="额外写出评估结果到指定路径")
|
|
200
|
+
ep.add_argument("--jsonl", action="store_true", help="以 JSONL 输出")
|
|
201
|
+
ep.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
202
|
+
ep.add_argument("--cost-bps", type=float, default=None, help="评估收益扣除的往返成本,单位 bps")
|
|
203
|
+
ep.add_argument("--follow-through-pct", type=float, default=None, help="突破延续判定的最低收益百分比")
|
|
204
|
+
ep.add_argument("--failed-breakout-pct", type=float, default=None, help="突破失败判定的最高收益百分比")
|
|
205
|
+
ep.add_argument("--with-price-path", action="store_true", help="额外抓取日 K 路径,计算最大回撤和最大浮盈")
|
|
206
|
+
ep.add_argument("--price-path-lookback-days", type=int, default=None, help="价格路径日 K 回看天数")
|
|
207
|
+
ep.add_argument("--window", type=int, help="单个 T+N 交易日窗口,例如 5")
|
|
208
|
+
|
|
209
|
+
# evaluate-batch
|
|
210
|
+
ebp = sub.add_parser("evaluate-batch", help="批量评估最近保存的选股结果并按策略聚合")
|
|
211
|
+
ebp.add_argument("--limit", type=int, default=20, help="最多评估最近 N 个 run")
|
|
212
|
+
ebp.add_argument("--strategy", default=None, help="只评估指定策略")
|
|
213
|
+
ebp.add_argument("--market", default="cn", help="只评估指定市场的 run(cn / us / hk / jp / kr / tw / in),批量共用一个快照,市场必须一致")
|
|
214
|
+
ebp.add_argument("--output", default=None, help="额外写出批量评估 JSON 到指定路径")
|
|
215
|
+
ebp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
216
|
+
ebp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
217
|
+
ebp.add_argument("--cost-bps", type=float, default=None, help="评估收益扣除的往返成本,单位 bps")
|
|
218
|
+
ebp.add_argument("--follow-through-pct", type=float, default=None, help="突破延续判定的最低收益百分比")
|
|
219
|
+
ebp.add_argument("--failed-breakout-pct", type=float, default=None, help="突破失败判定的最高收益百分比")
|
|
220
|
+
ebp.add_argument("--with-price-path", action="store_true", help="额外抓取日 K 路径,计算最大回撤和最大浮盈")
|
|
221
|
+
ebp.add_argument("--price-path-lookback-days", type=int, default=None, help="价格路径日 K 回看天数")
|
|
222
|
+
ebp.add_argument("--failure-samples", type=int, default=5, help="失败样本复盘最多展示 N 条,0 表示只输出聚合")
|
|
223
|
+
|
|
224
|
+
# performance
|
|
225
|
+
pp = sub.add_parser("performance", help="汇总已保存 evaluation 的策略后验表现")
|
|
226
|
+
pp.add_argument("--limit", type=int, default=100, help="最多读取最近 N 个已保存 evaluation")
|
|
227
|
+
pp.add_argument("--strategy", default=None, help="只汇总指定策略")
|
|
228
|
+
pp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
229
|
+
pp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
230
|
+
|
|
231
|
+
# evaluate-strategies
|
|
232
|
+
esp = sub.add_parser("evaluate-strategies", help="生成策略级评估 summary")
|
|
233
|
+
esp.add_argument("--limit", type=int, default=20, help="最多评估最近 N 个 run")
|
|
234
|
+
esp.add_argument("--strategy", default=None, help="只评估指定策略")
|
|
235
|
+
esp.add_argument("--market", default="cn", help="只评估指定市场的 run(cn / us / hk / jp / kr / tw / in),批量共用一个快照,市场必须一致")
|
|
236
|
+
esp.add_argument("--output", default=None, help="额外写出策略评估 JSON 到指定路径")
|
|
237
|
+
esp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
238
|
+
esp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
239
|
+
esp.add_argument("--cost-bps", type=float, default=None, help="评估收益扣除的往返成本,单位 bps")
|
|
240
|
+
esp.add_argument("--follow-through-pct", type=float, default=None, help="突破延续判定的最低收益百分比")
|
|
241
|
+
esp.add_argument("--failed-breakout-pct", type=float, default=None, help="突破失败判定的最高收益百分比")
|
|
242
|
+
esp.add_argument("--with-price-path", action="store_true", help="额外抓取日 K 路径,计算最大回撤和最大浮盈")
|
|
243
|
+
esp.add_argument("--price-path-lookback-days", type=int, default=None, help="价格路径日 K 回看天数")
|
|
244
|
+
esp.add_argument("--failure-samples", type=int, default=5, help="失败样本复盘最多展示 N 条,0 表示只输出聚合")
|
|
245
|
+
esp.add_argument(
|
|
246
|
+
"--window",
|
|
247
|
+
default=None,
|
|
248
|
+
help=(
|
|
249
|
+
"逗号分隔的 T+N 交易日窗口,例如 5,10,20:按截止日后第 N 根日 K 收盘计算收益,"
|
|
250
|
+
"并与所在市场基准指数同期收益对比;未满 N 日的记为 pending。和 --price-path-lookback-days 互斥"
|
|
251
|
+
),
|
|
252
|
+
)
|
|
253
|
+
for command in (ep, esp):
|
|
254
|
+
command.add_argument(
|
|
255
|
+
"--entry-mode", choices=("close", "next_open"), default="close",
|
|
256
|
+
help="T+N 入场价:close 为截止日收盘(默认),next_open 为之后首根日 K 的开盘价",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# runs
|
|
260
|
+
rp = sub.add_parser("runs", help="列出已保存的运行")
|
|
261
|
+
rp.add_argument("--limit", type=int, default=20)
|
|
262
|
+
rp.add_argument("--strategy", default=None, help="只列出指定策略的运行")
|
|
263
|
+
rp.add_argument("--json", action="store_true", help="以 JSON 输出完整运行元数据")
|
|
264
|
+
|
|
265
|
+
# overview
|
|
266
|
+
op = sub.add_parser("overview", help="输出 UI/agent 总览:策略、数据源健康和最近运行")
|
|
267
|
+
op.add_argument("--strategy", default=None, help="聚焦指定策略,同时过滤最近运行")
|
|
268
|
+
op.add_argument("--runs-limit", type=int, default=5, help="最近运行最多返回 N 条")
|
|
269
|
+
op.add_argument("--live-data-check", action="store_true", help="执行真实数据源 smoke check;默认只读健康状态")
|
|
270
|
+
op.add_argument("--risk-profile", default=None, help="推荐策略风险风格:defensive / balanced / aggressive")
|
|
271
|
+
op.add_argument("--holding-period", default=None, help="推荐策略持有周期:short_term / swing / watchlist")
|
|
272
|
+
op.add_argument("--execution-style", default=None, help="推荐策略执行风格,例如 mean_reversion / breakout")
|
|
273
|
+
op.add_argument("--market-regime", action="append", default=None, help="推荐策略行情环境,可重复或逗号分隔")
|
|
274
|
+
op.add_argument("--capital-profile", default=None, help="推荐策略流动性/容量风格")
|
|
275
|
+
op.add_argument("--data-requirement", action="append", default=None, help="推荐策略数据依赖,可重复或逗号分隔")
|
|
276
|
+
op.add_argument("--tag", action="append", default=None, help="推荐策略标签,可重复或逗号分隔")
|
|
277
|
+
op.add_argument("--category", default=None, help="推荐策略分类")
|
|
278
|
+
op.add_argument(
|
|
279
|
+
"--daily-required",
|
|
280
|
+
choices=["any", "true", "false"],
|
|
281
|
+
default="any",
|
|
282
|
+
help="按是否依赖日 K 特征推荐策略",
|
|
283
|
+
)
|
|
284
|
+
op.add_argument("--strict", action="store_true", help="只推荐满足全部策略偏好的候选")
|
|
285
|
+
op.add_argument("--match-limit", type=int, default=5, help="最多返回 N 个策略推荐")
|
|
286
|
+
op.add_argument("--output", default=None, help="额外写出 overview JSON")
|
|
287
|
+
op.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
288
|
+
op.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
289
|
+
|
|
290
|
+
# serve
|
|
291
|
+
svp = sub.add_parser("serve", help="启动只读本地 JSON API,供 UI/agent 消费")
|
|
292
|
+
svp.add_argument("--host", default="127.0.0.1", help="监听地址,默认 127.0.0.1")
|
|
293
|
+
svp.add_argument("--port", type=int, default=8765, help="监听端口,默认 8765")
|
|
294
|
+
|
|
295
|
+
# mcp
|
|
296
|
+
sub.add_parser("mcp", help="启动零依赖 STDIO MCP 服务器(供 Claude Code / Cursor / Codex / OpenClaw 调用)")
|
|
297
|
+
|
|
298
|
+
# report
|
|
299
|
+
rep = sub.add_parser("report", help="把已保存运行生成为 Markdown/JSON 报告")
|
|
300
|
+
rep.add_argument("run", help="run_id 或保存的 run JSON 文件路径")
|
|
301
|
+
rep.add_argument("--output", default=None, help="写出报告路径;默认打印到 stdout")
|
|
302
|
+
rep.add_argument("--json", action="store_true", help="输出 UI/agent 可消费的 JSON payload")
|
|
303
|
+
rep.add_argument("--max-picks", type=int, default=10, help="报告中最多展示前 N 只候选")
|
|
304
|
+
rep.add_argument("--evaluate", action="store_true", help="生成报告前附带最新 T+N 评估")
|
|
305
|
+
rep.add_argument("--cost-bps", type=float, default=None, help="评估收益扣除的往返成本,单位 bps")
|
|
306
|
+
rep.add_argument("--follow-through-pct", type=float, default=None, help="突破延续判定的最低收益百分比")
|
|
307
|
+
rep.add_argument("--failed-breakout-pct", type=float, default=None, help="突破失败判定的最高收益百分比")
|
|
308
|
+
rep.add_argument("--with-price-path", action="store_true", help="附带评估时抓取日 K 路径")
|
|
309
|
+
rep.add_argument("--price-path-lookback-days", type=int, default=None, help="价格路径日 K 回看天数")
|
|
310
|
+
|
|
311
|
+
# industry-cache
|
|
312
|
+
icp = sub.add_parser("industry-cache", help="刷新行业/概念映射缓存文件")
|
|
313
|
+
icp.add_argument("--provider", default="akshare", choices=["akshare"], help="行业/概念 provider")
|
|
314
|
+
icp.add_argument("--max-boards", type=int, default=80, help="最多抓取行业和概念板块数")
|
|
315
|
+
icp.add_argument("--output", default="data/industry_map.csv", help="输出 CSV/JSON 路径")
|
|
316
|
+
icp.add_argument("--explain", action="store_true", help="输出紧凑摘要")
|
|
317
|
+
|
|
318
|
+
# hotspots
|
|
319
|
+
hp = sub.add_parser("hotspots", help="发现并排序热点概念/行业")
|
|
320
|
+
hp.add_argument("--top", type=int, default=20, help="输出前 N 个热点")
|
|
321
|
+
hp.add_argument("--provider", default="akshare", help="热点 provider:akshare 或 none")
|
|
322
|
+
hp.add_argument("--max-boards", type=int, default=80, help="每类最多读取 N 个板块")
|
|
323
|
+
hp.add_argument("--history-path", default=None, help="读取热点 history JSONL 并回填趋势")
|
|
324
|
+
hp.add_argument("--fallback-cache", default=None, help="live provider 失败/无数据时读取 last-good 热点缓存")
|
|
325
|
+
hp.add_argument("--output", default=None, help="额外写出热点 JSON")
|
|
326
|
+
hp.add_argument("--explain", action="store_true", help="输出紧凑摘要")
|
|
327
|
+
|
|
328
|
+
hdp = sub.add_parser("hotspot", help="查看单个热点详情")
|
|
329
|
+
hdp.add_argument("topic", help="热点/概念/行业名称")
|
|
330
|
+
hdp.add_argument("--provider", default="akshare", help="热点 provider:akshare 或 none")
|
|
331
|
+
hdp.add_argument("--top-stocks", type=int, default=10, help="输出前 N 只热点成分股")
|
|
332
|
+
hdp.add_argument("--history-path", default=None, help="读取热点 history JSONL 并回填趋势")
|
|
333
|
+
hdp.add_argument("--fallback-cache", default=None, help="live provider 失败/无数据时读取 last-good 热点缓存")
|
|
334
|
+
hdp.add_argument("--timeline", action="store_true", help="加载并展示热点时间线")
|
|
335
|
+
hdp.add_argument("--timeline-path", default=None, help="热点时间线 JSONL")
|
|
336
|
+
hdp.add_argument("--output", default=None, help="额外写出详情 JSON")
|
|
337
|
+
hdp.add_argument("--explain", action="store_true", help="输出紧凑摘要")
|
|
338
|
+
|
|
339
|
+
hcp = sub.add_parser("hotspot-cache", help="刷新热点排行缓存并追加 history")
|
|
340
|
+
hcp.add_argument("--top", type=int, default=20, help="缓存前 N 个热点")
|
|
341
|
+
hcp.add_argument("--provider", default="akshare", help="热点 provider:akshare 或 none")
|
|
342
|
+
hcp.add_argument("--max-boards", type=int, default=80, help="每类最多读取 N 个板块")
|
|
343
|
+
hcp.add_argument("--history-path", default="data/hotspot.history.jsonl", help="追加写入 history JSONL")
|
|
344
|
+
hcp.add_argument("--output", default="data/hotspots.json", help="输出热点 JSON")
|
|
345
|
+
hcp.add_argument("--explain", action="store_true", help="输出紧凑摘要")
|
|
346
|
+
|
|
347
|
+
# audit
|
|
348
|
+
ap = sub.add_parser("audit", help="评估项目能力、策略配置覆盖和已知短板")
|
|
349
|
+
ap.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
350
|
+
|
|
351
|
+
# doctor
|
|
352
|
+
dp = sub.add_parser("doctor", help="诊断运行环境和数据源")
|
|
353
|
+
doctor_sub = dp.add_subparsers(dest="doctor_command")
|
|
354
|
+
dsp = doctor_sub.add_parser("data-sources", help="诊断 snapshot / daily 数据源状态")
|
|
355
|
+
dsp.add_argument("--snapshot-source", action="append", default=None, help="snapshot 来源,可重复或逗号分隔")
|
|
356
|
+
dsp.add_argument("--daily-source", default=None, help="daily K 来源,默认使用 DAILY_SOURCE/config")
|
|
357
|
+
dsp.add_argument("--daily-code", default="000001", help="daily K smoke test 股票代码,默认 000001;非 A 股默认用该市场的代表性股票")
|
|
358
|
+
dsp.add_argument(
|
|
359
|
+
"--market", default=None,
|
|
360
|
+
help="诊断的市场:cn / us / hk / jp / kr / tw / in;默认 cn,若 --strategy 不支持 cn 则取其第一个市场",
|
|
361
|
+
)
|
|
362
|
+
dsp.add_argument("--strategy", default=None, help="按指定策略的必需 snapshot/daily 字段做数据源预检")
|
|
363
|
+
dsp.add_argument("--all-strategies", action="store_true", help="按所有策略的字段并集做数据源覆盖矩阵")
|
|
364
|
+
dsp.add_argument("--compare-snapshot-sources", action="store_true", help="逐个检查 snapshot 源字段覆盖和代码交集")
|
|
365
|
+
dsp.add_argument("--no-live", action="store_true", help="只输出配置和内存 health,不发起网络取数")
|
|
366
|
+
dsp.add_argument("--no-daily", action="store_true", help="跳过 daily K smoke test")
|
|
367
|
+
dsp.add_argument("--output", default=None, help="额外写出 JSON 诊断报告")
|
|
368
|
+
dsp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
369
|
+
dsp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
370
|
+
drp = doctor_sub.add_parser("dsa-readiness", help="诊断可选 DSA 分析服务可用性")
|
|
371
|
+
drp.add_argument("--api-url", default=None, help="DSA base URL 或 analyze endpoint;默认读取 DSA_API_URL")
|
|
372
|
+
drp.add_argument("--timeout-sec", type=float, default=5.0, help="readiness probe 超时秒数")
|
|
373
|
+
drp.add_argument("--output", default=None, help="额外写出 JSON 诊断报告")
|
|
374
|
+
drp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
375
|
+
drp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
376
|
+
rdp = doctor_sub.add_parser("radar", help="检查 A 股日线包、形态模板、AI 赛道与 IM 推送就绪状态")
|
|
377
|
+
rdp.add_argument("--pack-dir", default=None, help="A 股日线包目录,默认读取 ALPHASIFT_PACK_DIR")
|
|
378
|
+
rdp.add_argument("--trade-date", default=None, help="预期交易日 YYYY-MM-DD")
|
|
379
|
+
rdp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
380
|
+
rdp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
381
|
+
rdp.add_argument("--strict-pack", action="store_true", help="若日线包无效或为空则以非零退出码失败")
|
|
382
|
+
rdp.add_argument("--require-fresh", action="store_true", help="若日线包未达到预期交易日则以非零退出码失败")
|
|
383
|
+
|
|
384
|
+
pp = sub.add_parser("pack", help="管理 A 股离线日线包")
|
|
385
|
+
pack_sub = pp.add_subparsers(dest="pack_command", required=True)
|
|
386
|
+
pull_parser = pack_sub.add_parser("pull", help="从 GitHub Release 拉取并校验数据包")
|
|
387
|
+
pull_parser.add_argument("--tag", default=None, help="Release 标签,默认 data-cn")
|
|
388
|
+
pull_parser.add_argument("--trade-date", default=None, help="预期交易日 YYYY-MM-DD(轮询新鲜度用)")
|
|
389
|
+
pull_parser.add_argument("--wait-sec", type=float, default=0.0, help="若远端包未更新至目标日,最多等待秒数,默认 0")
|
|
390
|
+
pull_parser.add_argument("--poll-sec", type=float, default=30.0, help="轮询间隔秒数,默认 30")
|
|
391
|
+
info_parser = pack_sub.add_parser("info", help="查看已校验的数据包及新鲜度")
|
|
392
|
+
info_parser.add_argument("--trade-date", help="预期交易日 YYYY-MM-DD,默认按 A 股收盘时间估算")
|
|
393
|
+
build_parser = pack_sub.add_parser("build", help="用日线历史回填 A 股日线包")
|
|
394
|
+
build_parser.add_argument(
|
|
395
|
+
"--source", choices=["auto", "baostock", "yfinance", "daily"], default="auto",
|
|
396
|
+
help="历史数据源:baostock、yfinance、daily(现有新浪和腾讯日线源)或 auto(Baostock 可连时优先,否则走批量 yfinance)",
|
|
397
|
+
)
|
|
398
|
+
build_parser.add_argument("--days", type=int, help="回填交易日数量,默认 250")
|
|
399
|
+
build_parser.add_argument("--codes-limit", type=int, help="仅处理排序后的前 N 个代码,用于小样本验证")
|
|
400
|
+
build_parser.add_argument("--trade-date", help="回填截止日期 YYYY-MM-DD")
|
|
401
|
+
|
|
402
|
+
# quickstart
|
|
403
|
+
qp = sub.add_parser(
|
|
404
|
+
"quickstart",
|
|
405
|
+
help="一键演示:列出策略 → 跑一个无 LLM 的 dual_low → 输出排名摘要",
|
|
406
|
+
)
|
|
407
|
+
qp.add_argument("--strategy", default="dual_low", help="演示用策略,默认 dual_low")
|
|
408
|
+
qp.add_argument("--max-output", type=int, default=5, help="演示输出候选数")
|
|
409
|
+
|
|
410
|
+
# market-stats (CN pack only)
|
|
411
|
+
msp = sub.add_parser("market-stats", help="计算 A 股离线日线包的客观盘面宽度、连板梯队与阶段标签")
|
|
412
|
+
msp.add_argument("--pack-dir", default=None, help="A 股日线包目录,默认读取 ALPHASIFT_PACK_DIR")
|
|
413
|
+
msp.add_argument("--trade-date", default=None, help="指定交易日 YYYY-MM-DD(仅计算至该日,无前瞻)")
|
|
414
|
+
msp.add_argument("--days", type=int, default=1, help="输出最近 N 个交易日统计,默认 1")
|
|
415
|
+
msp.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
416
|
+
msp.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
417
|
+
|
|
418
|
+
# patterns (CN pack only)
|
|
419
|
+
patp = sub.add_parser("patterns", help="A 股日线矩阵形态管理、扫描与 250 日 next_open 回放")
|
|
420
|
+
pat_sub = patp.add_subparsers(dest="patterns_command", required=True)
|
|
421
|
+
pat_list = pat_sub.add_parser("list", help="列出内置 A 股形态模板")
|
|
422
|
+
pat_list.add_argument("--include-experimental", action="store_true", help="包含尚未达毕业门槛的 experimental 形态")
|
|
423
|
+
pat_list.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
424
|
+
|
|
425
|
+
pat_scan = pat_sub.add_parser("scan", help="使用 A 股日线包进行无状态形态扫描")
|
|
426
|
+
pat_scan.add_argument("--pack-dir", default=None, help="A 股日线包目录,默认读取 ALPHASIFT_PACK_DIR")
|
|
427
|
+
pat_scan.add_argument("--pattern", action="append", default=None, help="只扫描指定形态,可重复")
|
|
428
|
+
pat_scan.add_argument("--trade-date", default=None, help="按截止交易日扫描(无前瞻)")
|
|
429
|
+
pat_scan.add_argument("--include-experimental", action="store_true", help="同时扫描 experimental 形态")
|
|
430
|
+
pat_scan.add_argument("--limit", type=int, default=20, help="--explain 模式下每个形态最多展示前 N 只,默认 20")
|
|
431
|
+
pat_scan.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
432
|
+
pat_scan.add_argument("--explain", action="store_true", help="输出紧凑可读摘要")
|
|
433
|
+
|
|
434
|
+
pat_replay = pat_sub.add_parser("replay", help="对形态做 250 日 next_open 回放、阶段切片与毕业门槛判定")
|
|
435
|
+
pat_replay.add_argument("--pack-dir", default=None, help="A 股日线包目录,默认读取 ALPHASIFT_PACK_DIR")
|
|
436
|
+
pat_replay.add_argument("--pattern", action="append", default=None, help="只回放指定形态,可重复")
|
|
437
|
+
pat_replay.add_argument("--benchmark-csv", default=None, help="可选基准 OHLC CSV(date,open,close)")
|
|
438
|
+
pat_replay.add_argument("--warmup-days", type=int, default=60, help="形态预热交易日数,默认 60")
|
|
439
|
+
pat_replay.add_argument("--cost-bps", type=float, default=0.0, help="扣减双边交易成本(bps)")
|
|
440
|
+
pat_replay.add_argument("--output-json", default=None, help="写出 JSON 回放报告")
|
|
441
|
+
pat_replay.add_argument("--output-md", default=None, help="写出 Markdown 回放报告")
|
|
442
|
+
pat_replay.add_argument(
|
|
443
|
+
"--allowed-regimes",
|
|
444
|
+
default=None,
|
|
445
|
+
help="仅保留指定市场情绪阶段(逗号分隔,支持 freezing/startup/main_up/divergence/ebb/neutral 或中文标签)",
|
|
446
|
+
)
|
|
447
|
+
pat_replay.add_argument(
|
|
448
|
+
"--exclude-regimes",
|
|
449
|
+
default=None,
|
|
450
|
+
help="剔除指定市场情绪阶段(逗号分隔,例如 freezing,ebb)",
|
|
451
|
+
)
|
|
452
|
+
pat_replay.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
453
|
+
|
|
454
|
+
# daily-report (CN daily report + multi-market digest + IM card + idempotent push)
|
|
455
|
+
drpt = sub.add_parser("daily-report", help="生成盘后结构化日报 report.json、<1200 字卡片并支持多通道幂等推送")
|
|
456
|
+
drpt.add_argument("--markets", default="cn", help="目标市场列表(逗号分隔;默认 cn,支持 us,hk,jp,kr,tw,in 海外简报)")
|
|
457
|
+
drpt.add_argument("--pack-dir", default=None, help="A 股日线包目录,默认读取 ALPHASIFT_PACK_DIR")
|
|
458
|
+
drpt.add_argument("--trade-date", default=None, help="指定交易日 YYYY-MM-DD")
|
|
459
|
+
drpt.add_argument("--run-id", action="append", default=None, help="附加已保存策略运行 ID/路径,可重复")
|
|
460
|
+
drpt.add_argument("--runs-dir", default=None, help="从目录自动附带该日保存的策略运行")
|
|
461
|
+
drpt.add_argument("--patterns-json", default=None, help="可选 patterns.json / replay.json 路径,补充形态历史期望标注")
|
|
462
|
+
drpt.add_argument("--no-announcements", action="store_true", help="跳过候选股近期公告负面关键词排雷")
|
|
463
|
+
drpt.add_argument("--no-news", action="store_true", help="跳过市场热点快讯与焦点个股新闻催化抓取")
|
|
464
|
+
drpt.add_argument("--expected-trade-date", default=None, help="目标 A 股交易日 YYYY-MM-DD;旧包将标记降级且默认不推送")
|
|
465
|
+
drpt.add_argument(
|
|
466
|
+
"--allow-stale-pack",
|
|
467
|
+
action="store_true",
|
|
468
|
+
help="允许使用落后于 expected-trade-date 的日线包生成带旧包标记的降级日报",
|
|
469
|
+
)
|
|
470
|
+
drpt.add_argument("--detail-url", default=None, help="覆盖 IM 卡片里的看板详情链接(传空字符串隐藏)")
|
|
471
|
+
drpt.add_argument(
|
|
472
|
+
"--ai-brief",
|
|
473
|
+
choices=["auto", "on", "off"],
|
|
474
|
+
default="auto",
|
|
475
|
+
help="生成 AI 盘后综述简报模式:auto(有 LLM Key 时启用)、on、off",
|
|
476
|
+
)
|
|
477
|
+
drpt.add_argument("--announcement-max-codes", type=int, default=20, help="公告排雷最多抽检前 N 只候选,默认 20")
|
|
478
|
+
drpt.add_argument("--output-json", default=None, help="写出 DailyReport report.json 路径")
|
|
479
|
+
drpt.add_argument("--output-card", default=None, help="额外写出 <1200 字 IM Markdown 卡片路径")
|
|
480
|
+
drpt.add_argument("--output-html", default=None, help="额外写出可打印独立 HTML 研报路径")
|
|
481
|
+
drpt.add_argument("--push", action="store_true", help="按 NOTIFY_URLS / 已配置渠道幂等推送(支持企微/飞书/钉钉/PushPlus/Server酱/Bark/邮件/Telegram/Discord/Slack/ntfy/Webhook;无配置静默跳过)")
|
|
482
|
+
drpt.add_argument("--channel", action="append", default=None, help="仅推送指定渠道(wecom/feishu/dingtalk/pushplus/serverchan/bark/email/telegram/discord/slack/ntfy/custom/apprise),可重复")
|
|
483
|
+
drpt.add_argument("--force-push", action="store_true", help="忽略同交易日幂等锁强制重发")
|
|
484
|
+
drpt.add_argument("--dry-run-push", action="store_true", help="演练推送流程,不实际发送请求也不写状态")
|
|
485
|
+
drpt.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
486
|
+
drpt.add_argument("--explain", action="store_true", help="输出紧凑摘要与 IM 卡片预览")
|
|
487
|
+
|
|
488
|
+
# notify (channel readiness & connectivity test)
|
|
489
|
+
ntfy = sub.add_parser("notify", help="检查推送渠道配置(支持 1 行 NOTIFY_URLS)或发送连通性测试消息")
|
|
490
|
+
ntfy_sub = ntfy.add_subparsers(dest="notify_action", required=True)
|
|
491
|
+
ntfy_status = ntfy_sub.add_parser("status", help="查看已配置推送渠道与幂等账本路径(不输出任何密钥)")
|
|
492
|
+
ntfy_status.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
493
|
+
ntfy_test = ntfy_sub.add_parser("test", help="向已配置渠道发送一次非持久化测试消息(不污染日报幂等锁)")
|
|
494
|
+
ntfy_test.add_argument("--channel", action="append", default=None, help="仅测试指定渠道(wecom/feishu/dingtalk/pushplus/serverchan/bark/email/telegram/discord/slack/ntfy/custom/apprise),可重复")
|
|
495
|
+
ntfy_test.add_argument("--dry-run", action="store_true", help="演练流程,不发送实际 HTTP 请求")
|
|
496
|
+
ntfy_test.add_argument("--json", action="store_true", help="以 JSON 输出")
|
|
497
|
+
|
|
498
|
+
args = parser.parse_args()
|
|
499
|
+
_apply_env_file_args(args.env_file)
|
|
500
|
+
|
|
501
|
+
if args.command == "screen":
|
|
502
|
+
config = Config.from_env()
|
|
503
|
+
if args.no_post_analysis and (args.post_analyzer or args.deep_analysis):
|
|
504
|
+
parser.error("--no-post-analysis cannot be combined with --post-analyzer or --deep-analysis")
|
|
505
|
+
post_analyzers = []
|
|
506
|
+
if not args.no_post_analysis:
|
|
507
|
+
post_analyzers = list(config.post_analyzers)
|
|
508
|
+
if args.post_analyzer:
|
|
509
|
+
post_analyzers.extend(args.post_analyzer)
|
|
510
|
+
result = screen(
|
|
511
|
+
args.strategy,
|
|
512
|
+
market=args.market,
|
|
513
|
+
max_output=args.max_output,
|
|
514
|
+
use_llm=not args.no_llm,
|
|
515
|
+
llm_context=args.context,
|
|
516
|
+
llm_context_files=args.context_file,
|
|
517
|
+
candidate_context_files=args.candidate_context_file,
|
|
518
|
+
collect_llm_candidate_context=args.collect_candidate_context or None,
|
|
519
|
+
candidate_context_max_candidates=args.candidate_context_max_candidates,
|
|
520
|
+
candidate_context_providers=_split_csv_args(args.candidate_context_provider),
|
|
521
|
+
industry_map_files=args.industry_map_file,
|
|
522
|
+
industry_provider=args.industry_provider,
|
|
523
|
+
post_analyzers=post_analyzers,
|
|
524
|
+
post_analysis_max_picks=args.post_analysis_max_picks,
|
|
525
|
+
daily_enrich=args.daily_enrich,
|
|
526
|
+
daily_enrich_max_candidates=args.daily_enrich_max_candidates,
|
|
527
|
+
explain_filters=args.explain_filters,
|
|
528
|
+
deep_analysis=args.deep_analysis,
|
|
529
|
+
deep_analysis_max_picks=args.deep_analysis_max_picks,
|
|
530
|
+
config=config,
|
|
531
|
+
)
|
|
532
|
+
if args.save_run:
|
|
533
|
+
save_screen_result(result, data_dir=config.data_dir)
|
|
534
|
+
if args.output:
|
|
535
|
+
save_screen_result(result, data_dir=config.data_dir, path=args.output, jsonl=args.jsonl)
|
|
536
|
+
if args.explain:
|
|
537
|
+
print(_format_screen_explain(result))
|
|
538
|
+
elif args.jsonl:
|
|
539
|
+
print("\n".join(screen_result_to_jsonl(result)))
|
|
540
|
+
else:
|
|
541
|
+
print(json.dumps(asdict(result), ensure_ascii=False, indent=2))
|
|
542
|
+
|
|
543
|
+
elif args.command == "strategies":
|
|
544
|
+
if args.templates and args.template:
|
|
545
|
+
parser.error("--templates cannot be combined with --template")
|
|
546
|
+
if args.templates:
|
|
547
|
+
templates = list_strategy_templates()
|
|
548
|
+
if args.json:
|
|
549
|
+
print(json.dumps(templates, ensure_ascii=False, indent=2))
|
|
550
|
+
elif args.explain:
|
|
551
|
+
print(_format_strategy_templates_explain(templates))
|
|
552
|
+
else:
|
|
553
|
+
for item in templates:
|
|
554
|
+
tags = ",".join(str(value) for value in item.get("tags", []) or [])
|
|
555
|
+
suffix = f" tags={tags}" if tags else ""
|
|
556
|
+
print(
|
|
557
|
+
f" {str(item.get('name', '')):<28} {str(item.get('display_name', '')):<10} "
|
|
558
|
+
f"[{str(item.get('category', '-'))}] {str(item.get('description', ''))}{suffix}"
|
|
559
|
+
)
|
|
560
|
+
elif args.template:
|
|
561
|
+
try:
|
|
562
|
+
template = get_strategy_template(args.template, include_yaml=True)
|
|
563
|
+
except ValueError as exc:
|
|
564
|
+
parser.error(str(exc))
|
|
565
|
+
if args.json:
|
|
566
|
+
print(json.dumps(template, ensure_ascii=False, indent=2))
|
|
567
|
+
elif args.explain:
|
|
568
|
+
print(_format_strategy_template_explain(template))
|
|
569
|
+
else:
|
|
570
|
+
print(render_strategy_template(args.template), end="")
|
|
571
|
+
elif args.compare:
|
|
572
|
+
try:
|
|
573
|
+
payload = compare_strategies(args.compare[0], args.compare[1])
|
|
574
|
+
except ValueError as exc:
|
|
575
|
+
parser.error(str(exc))
|
|
576
|
+
if args.json:
|
|
577
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
578
|
+
else:
|
|
579
|
+
print(_format_strategy_compare_explain(payload))
|
|
580
|
+
elif _has_strategy_match_args(args):
|
|
581
|
+
criteria = _strategy_match_criteria_from_args(args)
|
|
582
|
+
matches = match_strategies(
|
|
583
|
+
risk_profile=args.risk_profile or "",
|
|
584
|
+
holding_period=args.holding_period or "",
|
|
585
|
+
execution_style=args.execution_style or "",
|
|
586
|
+
market_regime=_split_csv_args(args.market_regime) or [],
|
|
587
|
+
capital_profile=args.capital_profile or "",
|
|
588
|
+
data_requirements=_split_csv_args(args.data_requirement) or [],
|
|
589
|
+
tags=_split_csv_args(args.tag) or [],
|
|
590
|
+
category=args.category or "",
|
|
591
|
+
daily_required=_parse_daily_required(args.daily_required),
|
|
592
|
+
strict=args.strict,
|
|
593
|
+
limit=args.limit,
|
|
594
|
+
)
|
|
595
|
+
if args.json:
|
|
596
|
+
print(json.dumps(matches, ensure_ascii=False, indent=2))
|
|
597
|
+
elif args.explain:
|
|
598
|
+
print(_format_strategy_matches_explain(matches, criteria=criteria))
|
|
599
|
+
else:
|
|
600
|
+
for item in matches:
|
|
601
|
+
print(_format_strategy_match_line(item))
|
|
602
|
+
else:
|
|
603
|
+
strategies = list_strategies()
|
|
604
|
+
if args.json:
|
|
605
|
+
print(json.dumps([asdict(item) for item in strategies], ensure_ascii=False, indent=2))
|
|
606
|
+
elif args.explain:
|
|
607
|
+
print(_format_strategies_explain(strategies))
|
|
608
|
+
else:
|
|
609
|
+
for s in strategies:
|
|
610
|
+
tags = ",".join(s.tags)
|
|
611
|
+
suffix = f" tags={tags}" if tags else ""
|
|
612
|
+
print(
|
|
613
|
+
f" {s.name:<25} {s.display_name:<10} "
|
|
614
|
+
f"v{s.version:<5} [{s.category}] {s.description}{suffix}"
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
elif args.command == "evaluate":
|
|
618
|
+
if args.window is not None and args.window <= 0:
|
|
619
|
+
parser.error("--window must be a positive integer")
|
|
620
|
+
if args.entry_mode == "next_open" and args.window is None:
|
|
621
|
+
parser.error("--entry-mode next_open requires --window")
|
|
622
|
+
config = Config.from_env()
|
|
623
|
+
result = evaluate_saved_run(
|
|
624
|
+
args.run,
|
|
625
|
+
config=config,
|
|
626
|
+
cost_bps=args.cost_bps,
|
|
627
|
+
follow_through_pct=args.follow_through_pct,
|
|
628
|
+
failed_breakout_pct=args.failed_breakout_pct,
|
|
629
|
+
with_price_path=args.with_price_path or None,
|
|
630
|
+
price_path_lookback_days=args.price_path_lookback_days,
|
|
631
|
+
horizon_days=args.window,
|
|
632
|
+
entry_mode=args.entry_mode,
|
|
633
|
+
)
|
|
634
|
+
if args.save:
|
|
635
|
+
save_evaluation_result(result, data_dir=config.data_dir)
|
|
636
|
+
if args.output:
|
|
637
|
+
save_evaluation_result(result, data_dir=config.data_dir, path=args.output, jsonl=args.jsonl)
|
|
638
|
+
if args.explain:
|
|
639
|
+
print(_format_evaluation_explain(result))
|
|
640
|
+
elif args.jsonl:
|
|
641
|
+
print("\n".join(evaluation_result_to_jsonl(result)))
|
|
642
|
+
else:
|
|
643
|
+
print(json.dumps(asdict(result), ensure_ascii=False, indent=2))
|
|
644
|
+
|
|
645
|
+
elif args.command == "evaluate-batch":
|
|
646
|
+
config = Config.from_env()
|
|
647
|
+
result = evaluate_saved_runs(
|
|
648
|
+
config=config,
|
|
649
|
+
limit=args.limit,
|
|
650
|
+
strategy=args.strategy,
|
|
651
|
+
market=args.market,
|
|
652
|
+
cost_bps=args.cost_bps,
|
|
653
|
+
follow_through_pct=args.follow_through_pct,
|
|
654
|
+
failed_breakout_pct=args.failed_breakout_pct,
|
|
655
|
+
with_price_path=args.with_price_path or None,
|
|
656
|
+
price_path_lookback_days=args.price_path_lookback_days,
|
|
657
|
+
)
|
|
658
|
+
if args.output:
|
|
659
|
+
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
660
|
+
Path(args.output).write_text(
|
|
661
|
+
json.dumps(result, ensure_ascii=False, indent=2),
|
|
662
|
+
encoding="utf-8",
|
|
663
|
+
)
|
|
664
|
+
if args.explain:
|
|
665
|
+
print(_format_evaluation_batch_explain(result))
|
|
666
|
+
else:
|
|
667
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
668
|
+
|
|
669
|
+
elif args.command == "performance":
|
|
670
|
+
config = Config.from_env()
|
|
671
|
+
payload = build_strategy_performance_summary(
|
|
672
|
+
data_dir=config.data_dir,
|
|
673
|
+
limit=args.limit,
|
|
674
|
+
strategy=args.strategy,
|
|
675
|
+
)
|
|
676
|
+
if args.explain and not args.json:
|
|
677
|
+
print(_format_performance_summary_explain(payload))
|
|
678
|
+
else:
|
|
679
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
680
|
+
|
|
681
|
+
elif args.command == "evaluate-strategies":
|
|
682
|
+
config = Config.from_env()
|
|
683
|
+
try:
|
|
684
|
+
windows = _parse_window_list(args.window)
|
|
685
|
+
except ValueError as exc:
|
|
686
|
+
parser.error(str(exc))
|
|
687
|
+
if windows and args.price_path_lookback_days is not None:
|
|
688
|
+
parser.error("--window is incompatible with --price-path-lookback-days for this command")
|
|
689
|
+
if args.entry_mode == "next_open" and not windows:
|
|
690
|
+
parser.error("--entry-mode next_open requires --window")
|
|
691
|
+
|
|
692
|
+
if windows:
|
|
693
|
+
result = evaluate_saved_runs_by_windows(
|
|
694
|
+
windows=windows,
|
|
695
|
+
config=config,
|
|
696
|
+
limit=args.limit,
|
|
697
|
+
strategy=args.strategy,
|
|
698
|
+
market=args.market,
|
|
699
|
+
cost_bps=args.cost_bps,
|
|
700
|
+
follow_through_pct=args.follow_through_pct,
|
|
701
|
+
failed_breakout_pct=args.failed_breakout_pct,
|
|
702
|
+
failure_sample_limit=args.failure_samples,
|
|
703
|
+
entry_mode=args.entry_mode,
|
|
704
|
+
)
|
|
705
|
+
else:
|
|
706
|
+
result = evaluate_saved_runs(
|
|
707
|
+
config=config,
|
|
708
|
+
limit=args.limit,
|
|
709
|
+
strategy=args.strategy,
|
|
710
|
+
market=args.market,
|
|
711
|
+
cost_bps=args.cost_bps,
|
|
712
|
+
follow_through_pct=args.follow_through_pct,
|
|
713
|
+
failed_breakout_pct=args.failed_breakout_pct,
|
|
714
|
+
with_price_path=args.with_price_path or None,
|
|
715
|
+
price_path_lookback_days=args.price_path_lookback_days,
|
|
716
|
+
failure_sample_limit=args.failure_samples,
|
|
717
|
+
)
|
|
718
|
+
payload = {
|
|
719
|
+
"evaluated_at": result.get("evaluated_at"),
|
|
720
|
+
"snapshot_source": result.get("snapshot_source"),
|
|
721
|
+
"source_errors": result.get("source_errors", []),
|
|
722
|
+
"limit": result.get("limit"),
|
|
723
|
+
"strategy_filter": result.get("strategy_filter", ""),
|
|
724
|
+
"cost_bps": result.get("cost_bps"),
|
|
725
|
+
"with_price_path": result.get("with_price_path"),
|
|
726
|
+
"price_path_window_days": result.get("price_path_window_days", []),
|
|
727
|
+
"entry_mode": result.get("entry_mode", args.entry_mode),
|
|
728
|
+
"strategy_summaries": result.get("strategy_summaries", []),
|
|
729
|
+
"event_signal_review": result.get("event_signal_review", {}),
|
|
730
|
+
"failure_review": result.get("failure_review", {}),
|
|
731
|
+
"data_quality_review": result.get("data_quality_review", {}),
|
|
732
|
+
}
|
|
733
|
+
if result.get("window_reviews"):
|
|
734
|
+
payload["review_window_days"] = result.get("review_window_days")
|
|
735
|
+
payload["window_reviews"] = result.get("window_reviews", [])
|
|
736
|
+
if args.output:
|
|
737
|
+
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
738
|
+
Path(args.output).write_text(
|
|
739
|
+
json.dumps(payload, ensure_ascii=False, indent=2),
|
|
740
|
+
encoding="utf-8",
|
|
741
|
+
)
|
|
742
|
+
if args.explain or not args.json:
|
|
743
|
+
print(_format_evaluate_strategies_explain(payload))
|
|
744
|
+
else:
|
|
745
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
746
|
+
|
|
747
|
+
elif args.command == "runs":
|
|
748
|
+
config = Config.from_env()
|
|
749
|
+
runs = list_saved_runs(data_dir=config.data_dir, limit=args.limit, strategy=args.strategy)
|
|
750
|
+
if args.json:
|
|
751
|
+
print(json.dumps(runs, ensure_ascii=False, indent=2))
|
|
752
|
+
return
|
|
753
|
+
for item in runs:
|
|
754
|
+
print(
|
|
755
|
+
f"{item['run_id']:<14} {item['strategy']:<20} "
|
|
756
|
+
f"v{item.get('strategy_version') or '-':<5} "
|
|
757
|
+
f"{item['created_at']:<26} picks={item['picks']} "
|
|
758
|
+
f"source={item.get('snapshot_source') or '-'} "
|
|
759
|
+
f"daily={item.get('daily_enriched')} "
|
|
760
|
+
f"degraded={item.get('degradation_count', 0)} "
|
|
761
|
+
f"{item['path']}"
|
|
762
|
+
)
|
|
763
|
+
|
|
764
|
+
elif args.command == "overview":
|
|
765
|
+
config = Config.from_env()
|
|
766
|
+
payload = build_overview(
|
|
767
|
+
config,
|
|
768
|
+
strategy_name=args.strategy,
|
|
769
|
+
runs_limit=args.runs_limit,
|
|
770
|
+
live_data_check=args.live_data_check,
|
|
771
|
+
strategy_match=_overview_strategy_match_from_args(args),
|
|
772
|
+
match_limit=args.match_limit,
|
|
773
|
+
)
|
|
774
|
+
if args.output:
|
|
775
|
+
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
776
|
+
Path(args.output).write_text(
|
|
777
|
+
json.dumps(payload, ensure_ascii=False, indent=2),
|
|
778
|
+
encoding="utf-8",
|
|
779
|
+
)
|
|
780
|
+
if args.explain:
|
|
781
|
+
print(_format_overview_explain(payload))
|
|
782
|
+
else:
|
|
783
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
784
|
+
|
|
785
|
+
elif args.command == "serve":
|
|
786
|
+
config = Config.from_env()
|
|
787
|
+
serve_api(config, host=args.host, port=args.port)
|
|
788
|
+
|
|
789
|
+
elif args.command == "mcp":
|
|
790
|
+
from alphasift.mcp import serve_mcp
|
|
791
|
+
|
|
792
|
+
serve_mcp(Config.from_env())
|
|
793
|
+
|
|
794
|
+
elif args.command == "report":
|
|
795
|
+
config = Config.from_env()
|
|
796
|
+
try:
|
|
797
|
+
run = load_screen_result(args.run, data_dir=config.data_dir)
|
|
798
|
+
except FileNotFoundError as exc:
|
|
799
|
+
parser.error(str(exc))
|
|
800
|
+
evaluation = None
|
|
801
|
+
if args.evaluate:
|
|
802
|
+
evaluation = evaluate_saved_run(
|
|
803
|
+
args.run,
|
|
804
|
+
config=config,
|
|
805
|
+
cost_bps=args.cost_bps,
|
|
806
|
+
follow_through_pct=args.follow_through_pct,
|
|
807
|
+
failed_breakout_pct=args.failed_breakout_pct,
|
|
808
|
+
with_price_path=args.with_price_path or None,
|
|
809
|
+
price_path_lookback_days=args.price_path_lookback_days,
|
|
810
|
+
)
|
|
811
|
+
payload = build_run_report_payload(
|
|
812
|
+
run,
|
|
813
|
+
evaluation=evaluation,
|
|
814
|
+
max_picks=args.max_picks,
|
|
815
|
+
)
|
|
816
|
+
if args.output:
|
|
817
|
+
write_run_report(args.output, payload, json_output=args.json)
|
|
818
|
+
elif args.json:
|
|
819
|
+
print(report_payload_to_json(payload))
|
|
820
|
+
else:
|
|
821
|
+
print(render_run_report_markdown(payload), end="")
|
|
822
|
+
|
|
823
|
+
elif args.command == "industry-cache":
|
|
824
|
+
mapping, notes = fetch_akshare_board_map(max_boards=args.max_boards)
|
|
825
|
+
output_path = save_industry_map(mapping, args.output)
|
|
826
|
+
generated_at = datetime.now().isoformat()
|
|
827
|
+
history_path = _append_industry_cache_history(
|
|
828
|
+
output_path,
|
|
829
|
+
mapping=mapping,
|
|
830
|
+
generated_at=generated_at,
|
|
831
|
+
)
|
|
832
|
+
metadata_path = _write_industry_cache_metadata(
|
|
833
|
+
output_path,
|
|
834
|
+
provider=args.provider,
|
|
835
|
+
max_boards=args.max_boards,
|
|
836
|
+
rows=len(mapping),
|
|
837
|
+
notes=notes,
|
|
838
|
+
generated_at=generated_at,
|
|
839
|
+
history_path=history_path,
|
|
840
|
+
)
|
|
841
|
+
if args.explain:
|
|
842
|
+
print(
|
|
843
|
+
f"industry_cache={output_path} metadata={metadata_path} "
|
|
844
|
+
f"history={history_path} rows={len(mapping)} "
|
|
845
|
+
f"notes={' | '.join(notes)}"
|
|
846
|
+
)
|
|
847
|
+
else:
|
|
848
|
+
print(json.dumps({
|
|
849
|
+
"path": str(output_path),
|
|
850
|
+
"metadata_path": str(metadata_path),
|
|
851
|
+
"history_path": str(history_path),
|
|
852
|
+
"rows": len(mapping),
|
|
853
|
+
"notes": notes,
|
|
854
|
+
}, ensure_ascii=False, indent=2))
|
|
855
|
+
|
|
856
|
+
elif args.command == "hotspots":
|
|
857
|
+
hotspots = discover_hotspots(
|
|
858
|
+
provider=args.provider,
|
|
859
|
+
max_boards=args.max_boards,
|
|
860
|
+
history_path=args.history_path,
|
|
861
|
+
fallback_cache_path=args.fallback_cache,
|
|
862
|
+
top=args.top,
|
|
863
|
+
)
|
|
864
|
+
if args.output:
|
|
865
|
+
save_hotspots_json(args.output, hotspots)
|
|
866
|
+
if args.explain:
|
|
867
|
+
print(_format_hotspots_explain(hotspots, provider=args.provider))
|
|
868
|
+
else:
|
|
869
|
+
print(json.dumps([asdict(item) for item in hotspots], ensure_ascii=False, indent=2))
|
|
870
|
+
|
|
871
|
+
elif args.command == "hotspot":
|
|
872
|
+
timeline_path = args.timeline_path if args.timeline else None
|
|
873
|
+
detail = get_hotspot_detail(
|
|
874
|
+
args.topic,
|
|
875
|
+
provider=args.provider,
|
|
876
|
+
top_stocks=args.top_stocks,
|
|
877
|
+
timeline_path=timeline_path,
|
|
878
|
+
history_path=args.history_path,
|
|
879
|
+
fallback_cache_path=args.fallback_cache,
|
|
880
|
+
)
|
|
881
|
+
if args.output:
|
|
882
|
+
output_path = Path(args.output)
|
|
883
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
884
|
+
output_path.write_text(
|
|
885
|
+
json.dumps(hotspot_detail_to_dict(detail), ensure_ascii=False, indent=2),
|
|
886
|
+
encoding="utf-8",
|
|
887
|
+
)
|
|
888
|
+
if args.explain:
|
|
889
|
+
print(_format_hotspot_detail_explain(detail))
|
|
890
|
+
else:
|
|
891
|
+
print(json.dumps(hotspot_detail_to_dict(detail), ensure_ascii=False, indent=2))
|
|
892
|
+
|
|
893
|
+
elif args.command == "hotspot-cache":
|
|
894
|
+
hotspots = discover_hotspots(
|
|
895
|
+
provider=args.provider,
|
|
896
|
+
max_boards=args.max_boards,
|
|
897
|
+
history_path=args.history_path,
|
|
898
|
+
fallback_cache_path=args.output,
|
|
899
|
+
top=args.top,
|
|
900
|
+
)
|
|
901
|
+
fallback_used = bool(getattr(hotspots, "fallback_used", False))
|
|
902
|
+
generated_at = datetime.now().isoformat()
|
|
903
|
+
history_path = None
|
|
904
|
+
history_appended = False
|
|
905
|
+
output_path = Path(args.output)
|
|
906
|
+
if fallback_used:
|
|
907
|
+
if not output_path.exists():
|
|
908
|
+
output_path = save_hotspots_json(args.output, hotspots)
|
|
909
|
+
else:
|
|
910
|
+
output_path = save_hotspots_json(args.output, hotspots)
|
|
911
|
+
history_path = append_hotspot_history(args.history_path, hotspots, generated_at=generated_at)
|
|
912
|
+
history_appended = True
|
|
913
|
+
metadata_path = _write_hotspot_cache_metadata(
|
|
914
|
+
output_path,
|
|
915
|
+
provider=args.provider,
|
|
916
|
+
max_boards=args.max_boards,
|
|
917
|
+
rows=len(hotspots),
|
|
918
|
+
generated_at=generated_at,
|
|
919
|
+
history_path=history_path,
|
|
920
|
+
fallback_used=fallback_used,
|
|
921
|
+
source_errors=getattr(hotspots, "source_errors", []),
|
|
922
|
+
history_appended=history_appended,
|
|
923
|
+
)
|
|
924
|
+
if args.explain:
|
|
925
|
+
print(
|
|
926
|
+
f"hotspot_cache={output_path} metadata={metadata_path} "
|
|
927
|
+
f"history={history_path or '-'} rows={len(hotspots)} "
|
|
928
|
+
f"fallback={fallback_used}"
|
|
929
|
+
)
|
|
930
|
+
else:
|
|
931
|
+
print(json.dumps({
|
|
932
|
+
"path": str(output_path),
|
|
933
|
+
"metadata_path": str(metadata_path),
|
|
934
|
+
"history_path": str(history_path) if history_path is not None else "",
|
|
935
|
+
"schema_version": 2,
|
|
936
|
+
"rows": len(hotspots),
|
|
937
|
+
"fallback_used": fallback_used,
|
|
938
|
+
"source_errors": getattr(hotspots, "source_errors", []),
|
|
939
|
+
}, ensure_ascii=False, indent=2))
|
|
940
|
+
|
|
941
|
+
elif args.command == "audit":
|
|
942
|
+
config = Config.from_env()
|
|
943
|
+
result = audit_project(config.strategies_dir)
|
|
944
|
+
if args.json:
|
|
945
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
946
|
+
else:
|
|
947
|
+
print(_format_audit_explain(result))
|
|
948
|
+
|
|
949
|
+
elif args.command == "doctor":
|
|
950
|
+
config = Config.from_env()
|
|
951
|
+
if args.doctor_command == "data-sources":
|
|
952
|
+
try:
|
|
953
|
+
result = doctor_data_sources(
|
|
954
|
+
config,
|
|
955
|
+
snapshot_sources=_split_csv_args(args.snapshot_source) or None,
|
|
956
|
+
daily_source=args.daily_source,
|
|
957
|
+
daily_code=args.daily_code,
|
|
958
|
+
run_live=not args.no_live,
|
|
959
|
+
check_daily=not args.no_daily,
|
|
960
|
+
strategy_name=args.strategy,
|
|
961
|
+
all_strategies=args.all_strategies,
|
|
962
|
+
compare_snapshot_sources=args.compare_snapshot_sources,
|
|
963
|
+
market=args.market,
|
|
964
|
+
)
|
|
965
|
+
except ValueError as exc:
|
|
966
|
+
parser.error(str(exc))
|
|
967
|
+
if args.output:
|
|
968
|
+
write_doctor_report(args.output, result)
|
|
969
|
+
if args.json or not args.explain:
|
|
970
|
+
print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
|
|
971
|
+
else:
|
|
972
|
+
print(_format_data_sources_doctor_explain(result.to_dict()))
|
|
973
|
+
elif args.doctor_command == "dsa-readiness":
|
|
974
|
+
result = check_dsa_readiness(
|
|
975
|
+
args.api_url if args.api_url is not None else config.dsa_api_url,
|
|
976
|
+
timeout_sec=args.timeout_sec,
|
|
977
|
+
)
|
|
978
|
+
if args.output:
|
|
979
|
+
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
980
|
+
Path(args.output).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
981
|
+
if args.json or not args.explain:
|
|
982
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
983
|
+
else:
|
|
984
|
+
print(_format_dsa_readiness_explain(result))
|
|
985
|
+
elif args.doctor_command == "radar":
|
|
986
|
+
result = doctor_radar_readiness(
|
|
987
|
+
config,
|
|
988
|
+
pack_dir=Path(args.pack_dir).expanduser() if args.pack_dir else None,
|
|
989
|
+
trade_date=args.trade_date,
|
|
990
|
+
)
|
|
991
|
+
if args.explain and not args.json:
|
|
992
|
+
print(_format_radar_doctor_explain(result))
|
|
993
|
+
else:
|
|
994
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
995
|
+
pack_info = result.get("pack") or {}
|
|
996
|
+
if args.strict_pack and (
|
|
997
|
+
not pack_info.get("valid")
|
|
998
|
+
or int(pack_info.get("dates") or 0) <= 0
|
|
999
|
+
or int(pack_info.get("codes") or 0) <= 0
|
|
1000
|
+
):
|
|
1001
|
+
raise SystemExit(1)
|
|
1002
|
+
if args.require_fresh and not pack_info.get("fresh"):
|
|
1003
|
+
raise SystemExit(1)
|
|
1004
|
+
else:
|
|
1005
|
+
parser.error("doctor requires a subcommand, e.g. doctor data-sources")
|
|
1006
|
+
|
|
1007
|
+
elif args.command == "quickstart":
|
|
1008
|
+
_run_quickstart(strategy=args.strategy, max_output=args.max_output)
|
|
1009
|
+
|
|
1010
|
+
elif args.command == "pack":
|
|
1011
|
+
from alphasift import pack
|
|
1012
|
+
|
|
1013
|
+
config = Config.from_env()
|
|
1014
|
+
directory = pack.pack_dir(config)
|
|
1015
|
+
try:
|
|
1016
|
+
if args.pack_command == "pull":
|
|
1017
|
+
tag = args.tag if args.tag is not None else pack.DEFAULT_TAG
|
|
1018
|
+
if (args.wait_sec and args.wait_sec > 0) or args.trade_date:
|
|
1019
|
+
result = pack.pull_with_wait(
|
|
1020
|
+
directory,
|
|
1021
|
+
tag=tag,
|
|
1022
|
+
expected_trade_date=args.trade_date,
|
|
1023
|
+
max_wait_sec=args.wait_sec,
|
|
1024
|
+
poll_interval_sec=args.poll_sec,
|
|
1025
|
+
)
|
|
1026
|
+
else:
|
|
1027
|
+
result = pack.pull(directory, tag=tag)
|
|
1028
|
+
elif args.pack_command == "info":
|
|
1029
|
+
data = pack.load_pack(directory)
|
|
1030
|
+
expected = args.trade_date or pack.expected_trade_date()
|
|
1031
|
+
result = {**data.manifest, "expected_trade_date": expected, "fresh": pack.is_fresh(data, expected)}
|
|
1032
|
+
else:
|
|
1033
|
+
result = pack.backfill(
|
|
1034
|
+
directory, days=args.days if args.days is not None else pack.DEFAULT_DAYS,
|
|
1035
|
+
codes_limit=args.codes_limit, trade_date=args.trade_date, config=config, source=args.source,
|
|
1036
|
+
)
|
|
1037
|
+
except (OSError, RuntimeError, ValueError) as exc:
|
|
1038
|
+
parser.error(str(exc))
|
|
1039
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
1040
|
+
|
|
1041
|
+
elif args.command == "market-stats":
|
|
1042
|
+
from alphasift import pack
|
|
1043
|
+
from alphasift.market_regime import compute_market_regime, compute_market_regime_series
|
|
1044
|
+
|
|
1045
|
+
config = Config.from_env()
|
|
1046
|
+
directory = Path(args.pack_dir).expanduser() if args.pack_dir else pack.pack_dir(config)
|
|
1047
|
+
try:
|
|
1048
|
+
daily_pack = pack.load_pack(directory)
|
|
1049
|
+
if args.days <= 1:
|
|
1050
|
+
items = [compute_market_regime(daily_pack, trade_date=args.trade_date)]
|
|
1051
|
+
else:
|
|
1052
|
+
if args.trade_date is not None:
|
|
1053
|
+
dates = [str(d) for d in daily_pack.dates]
|
|
1054
|
+
if args.trade_date not in dates:
|
|
1055
|
+
raise ValueError(f"trade_date {args.trade_date!r} not found in DailyPack")
|
|
1056
|
+
end_idx = dates.index(args.trade_date)
|
|
1057
|
+
else:
|
|
1058
|
+
end_idx = len(daily_pack.dates) - 1
|
|
1059
|
+
series = compute_market_regime_series(daily_pack, end_index=end_idx)
|
|
1060
|
+
items = series[-max(1, int(args.days)):]
|
|
1061
|
+
except (OSError, RuntimeError, ValueError, IndexError) as exc:
|
|
1062
|
+
parser.error(str(exc))
|
|
1063
|
+
|
|
1064
|
+
if args.explain and not args.json:
|
|
1065
|
+
print(_format_market_stats_explain(items))
|
|
1066
|
+
else:
|
|
1067
|
+
payload: object = items[0].to_dict() if args.days <= 1 else [item.to_dict() for item in items]
|
|
1068
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1069
|
+
|
|
1070
|
+
elif args.command == "patterns":
|
|
1071
|
+
from alphasift import pack
|
|
1072
|
+
from alphasift.pattern_replay import load_cn_benchmark, render_replay_markdown, replay_patterns
|
|
1073
|
+
from alphasift.patterns import list_patterns, scan_patterns
|
|
1074
|
+
|
|
1075
|
+
config = Config.from_env()
|
|
1076
|
+
if args.patterns_command == "list":
|
|
1077
|
+
specs = list_patterns(include_experimental=args.include_experimental)
|
|
1078
|
+
if args.json:
|
|
1079
|
+
print(json.dumps([asdict(s) for s in specs], ensure_ascii=False, indent=2))
|
|
1080
|
+
else:
|
|
1081
|
+
print(f"patterns={len(specs)}")
|
|
1082
|
+
for spec in specs:
|
|
1083
|
+
aligned = f" aligned={spec.aligned_strategy}" if spec.aligned_strategy else ""
|
|
1084
|
+
print(
|
|
1085
|
+
f" {spec.name:<24} {spec.display_name:<10} "
|
|
1086
|
+
f"[{spec.family}/{spec.mode}] status={spec.status}{aligned}"
|
|
1087
|
+
)
|
|
1088
|
+
elif args.patterns_command == "scan":
|
|
1089
|
+
directory = Path(args.pack_dir).expanduser() if args.pack_dir else pack.pack_dir(config)
|
|
1090
|
+
try:
|
|
1091
|
+
daily_pack = pack.load_pack(directory)
|
|
1092
|
+
result = scan_patterns(
|
|
1093
|
+
daily_pack,
|
|
1094
|
+
patterns=args.pattern,
|
|
1095
|
+
trade_date=args.trade_date,
|
|
1096
|
+
include_experimental=args.include_experimental,
|
|
1097
|
+
)
|
|
1098
|
+
except (OSError, RuntimeError, ValueError, IndexError) as exc:
|
|
1099
|
+
parser.error(str(exc))
|
|
1100
|
+
if args.explain and not args.json:
|
|
1101
|
+
print(_format_pattern_scan_explain(result, limit=args.limit))
|
|
1102
|
+
else:
|
|
1103
|
+
print(json.dumps(result.to_dict(), ensure_ascii=False, indent=2))
|
|
1104
|
+
else:
|
|
1105
|
+
directory = Path(args.pack_dir).expanduser() if args.pack_dir else pack.pack_dir(config)
|
|
1106
|
+
try:
|
|
1107
|
+
daily_pack = pack.load_pack(directory)
|
|
1108
|
+
bench = load_cn_benchmark(
|
|
1109
|
+
Path(args.benchmark_csv).expanduser() if args.benchmark_csv else None,
|
|
1110
|
+
lookback_days=max(len(daily_pack.dates) + 40, 320),
|
|
1111
|
+
)
|
|
1112
|
+
report = replay_patterns(
|
|
1113
|
+
daily_pack,
|
|
1114
|
+
patterns=args.pattern,
|
|
1115
|
+
benchmark_df=bench,
|
|
1116
|
+
warmup_days=args.warmup_days,
|
|
1117
|
+
cost_bps=args.cost_bps,
|
|
1118
|
+
allowed_regimes=[
|
|
1119
|
+
s.strip() for s in (args.allowed_regimes or "").split(",") if s.strip()
|
|
1120
|
+
]
|
|
1121
|
+
or None,
|
|
1122
|
+
excluded_regimes=[
|
|
1123
|
+
s.strip() for s in (args.exclude_regimes or "").split(",") if s.strip()
|
|
1124
|
+
]
|
|
1125
|
+
or None,
|
|
1126
|
+
)
|
|
1127
|
+
except (OSError, RuntimeError, ValueError, IndexError) as exc:
|
|
1128
|
+
parser.error(str(exc))
|
|
1129
|
+
if args.output_json:
|
|
1130
|
+
out_json = Path(args.output_json)
|
|
1131
|
+
out_json.parent.mkdir(parents=True, exist_ok=True)
|
|
1132
|
+
out_json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
1133
|
+
if args.output_md:
|
|
1134
|
+
out_md = Path(args.output_md)
|
|
1135
|
+
out_md.parent.mkdir(parents=True, exist_ok=True)
|
|
1136
|
+
out_md.write_text(render_replay_markdown(report), encoding="utf-8")
|
|
1137
|
+
if args.json:
|
|
1138
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
1139
|
+
else:
|
|
1140
|
+
print(render_replay_markdown(report))
|
|
1141
|
+
|
|
1142
|
+
elif args.command == "daily-report":
|
|
1143
|
+
from alphasift import pack
|
|
1144
|
+
from alphasift.daily_report import (
|
|
1145
|
+
build_daily_report,
|
|
1146
|
+
load_daily_report_runs,
|
|
1147
|
+
write_daily_card,
|
|
1148
|
+
write_daily_report,
|
|
1149
|
+
)
|
|
1150
|
+
from alphasift.daily_report_html import write_daily_report_html
|
|
1151
|
+
from alphasift.market_digest import build_markets_digest, load_multi_market_runs
|
|
1152
|
+
from alphasift.markets import latest_settled_close
|
|
1153
|
+
from alphasift.notify import push_daily_report
|
|
1154
|
+
|
|
1155
|
+
config = Config.from_env()
|
|
1156
|
+
req_markets = [m.strip().lower() for m in str(getattr(args, "markets", "cn") or "cn").split(",") if m.strip()] or ["cn"]
|
|
1157
|
+
resolved_detail_url = args.detail_url if args.detail_url is not None else config.dashboard_url
|
|
1158
|
+
runs_dir_path = Path(args.runs_dir).expanduser() if args.runs_dir else None
|
|
1159
|
+
|
|
1160
|
+
track_summary = None
|
|
1161
|
+
summary_candidates = []
|
|
1162
|
+
if args.output_html:
|
|
1163
|
+
summary_candidates.append(Path(args.output_html).expanduser().parent / "summary.json")
|
|
1164
|
+
if args.output_json:
|
|
1165
|
+
summary_candidates.append(Path(args.output_json).expanduser().parent / "summary.json")
|
|
1166
|
+
if runs_dir_path is not None:
|
|
1167
|
+
summary_candidates.append(runs_dir_path.parent.parent / "site" / "summary.json")
|
|
1168
|
+
for cand in summary_candidates:
|
|
1169
|
+
if cand.is_file():
|
|
1170
|
+
try:
|
|
1171
|
+
track_summary = json.loads(cand.read_text(encoding="utf-8"))
|
|
1172
|
+
break
|
|
1173
|
+
except (OSError, ValueError):
|
|
1174
|
+
pass
|
|
1175
|
+
|
|
1176
|
+
pattern_replay = None
|
|
1177
|
+
replay_candidates = []
|
|
1178
|
+
if getattr(args, "patterns_json", None):
|
|
1179
|
+
replay_candidates.append(Path(args.patterns_json).expanduser())
|
|
1180
|
+
if runs_dir_path is not None:
|
|
1181
|
+
replay_candidates.append(runs_dir_path.parent / "patterns" / "replay.json")
|
|
1182
|
+
replay_candidates.append(runs_dir_path.parent.parent / "site" / "patterns.json")
|
|
1183
|
+
if args.output_json:
|
|
1184
|
+
replay_candidates.append(Path(args.output_json).expanduser().parent / "patterns.json")
|
|
1185
|
+
for cand in replay_candidates:
|
|
1186
|
+
if cand.is_file():
|
|
1187
|
+
try:
|
|
1188
|
+
pattern_replay = json.loads(cand.read_text(encoding="utf-8"))
|
|
1189
|
+
break
|
|
1190
|
+
except (OSError, ValueError):
|
|
1191
|
+
pass
|
|
1192
|
+
|
|
1193
|
+
try:
|
|
1194
|
+
if req_markets != ["cn"]:
|
|
1195
|
+
runs_by_mkt = load_multi_market_runs(
|
|
1196
|
+
config,
|
|
1197
|
+
markets=req_markets,
|
|
1198
|
+
runs_dir=runs_dir_path,
|
|
1199
|
+
trade_date=args.trade_date,
|
|
1200
|
+
)
|
|
1201
|
+
report = build_markets_digest(
|
|
1202
|
+
runs_by_mkt,
|
|
1203
|
+
markets=req_markets,
|
|
1204
|
+
trade_date=args.trade_date,
|
|
1205
|
+
detail_url=resolved_detail_url,
|
|
1206
|
+
include_news=not getattr(args, "no_news", False),
|
|
1207
|
+
config=config,
|
|
1208
|
+
track_summary=track_summary if isinstance(track_summary, dict) else None,
|
|
1209
|
+
)
|
|
1210
|
+
if args.output_json:
|
|
1211
|
+
write_daily_report(args.output_json, report)
|
|
1212
|
+
if args.output_card:
|
|
1213
|
+
write_daily_card(args.output_card, report["im_card_markdown"])
|
|
1214
|
+
if args.push or args.dry_run_push:
|
|
1215
|
+
report["push"] = push_daily_report(
|
|
1216
|
+
report,
|
|
1217
|
+
config=config,
|
|
1218
|
+
channels=args.channel,
|
|
1219
|
+
force=args.force_push,
|
|
1220
|
+
dry_run=args.dry_run_push,
|
|
1221
|
+
)
|
|
1222
|
+
else:
|
|
1223
|
+
directory = Path(args.pack_dir).expanduser() if args.pack_dir else pack.pack_dir(config)
|
|
1224
|
+
daily_pack = pack.load_pack(directory)
|
|
1225
|
+
runs = load_daily_report_runs(
|
|
1226
|
+
config,
|
|
1227
|
+
run_refs=args.run_id,
|
|
1228
|
+
runs_dir=runs_dir_path,
|
|
1229
|
+
trade_date=args.trade_date or daily_pack.trade_date,
|
|
1230
|
+
)
|
|
1231
|
+
explicit_expected_date = args.expected_trade_date
|
|
1232
|
+
resolved_expected_date = explicit_expected_date
|
|
1233
|
+
if not resolved_expected_date and args.push and not args.force_push and not args.trade_date:
|
|
1234
|
+
settled = latest_settled_close("cn")
|
|
1235
|
+
if settled is not None:
|
|
1236
|
+
resolved_expected_date = settled[0].isoformat()
|
|
1237
|
+
allow_stale = True if not explicit_expected_date else bool(args.allow_stale_pack)
|
|
1238
|
+
cache_root = config.llm_candidate_context_cache_dir or (config.data_dir / "candidate_context_cache")
|
|
1239
|
+
report = build_daily_report(
|
|
1240
|
+
daily_pack,
|
|
1241
|
+
trade_date=args.trade_date,
|
|
1242
|
+
expected_trade_date=resolved_expected_date,
|
|
1243
|
+
allow_stale_pack=allow_stale,
|
|
1244
|
+
detail_url=resolved_detail_url,
|
|
1245
|
+
strategy_runs=runs,
|
|
1246
|
+
include_announcements=not args.no_announcements,
|
|
1247
|
+
announcement_max_codes=args.announcement_max_codes,
|
|
1248
|
+
announcement_cache_dir=cache_root,
|
|
1249
|
+
include_news=not getattr(args, "no_news", False),
|
|
1250
|
+
news_cache_dir=cache_root,
|
|
1251
|
+
ai_brief_mode=args.ai_brief,
|
|
1252
|
+
config=config,
|
|
1253
|
+
track_comparison=(track_summary or {}).get("track_comparison") if isinstance(track_summary, dict) else None,
|
|
1254
|
+
track_summary=track_summary if isinstance(track_summary, dict) else None,
|
|
1255
|
+
pattern_replay=pattern_replay if isinstance(pattern_replay, dict) else None,
|
|
1256
|
+
warn_if_no_runs=bool(args.runs_dir or args.run_id),
|
|
1257
|
+
)
|
|
1258
|
+
if args.output_json:
|
|
1259
|
+
write_daily_report(args.output_json, report)
|
|
1260
|
+
if args.output_card:
|
|
1261
|
+
write_daily_card(args.output_card, report["im_card_markdown"])
|
|
1262
|
+
if args.output_html:
|
|
1263
|
+
write_daily_report_html(args.output_html, report, track_summary=track_summary)
|
|
1264
|
+
if args.push or args.dry_run_push:
|
|
1265
|
+
report["push"] = push_daily_report(
|
|
1266
|
+
report,
|
|
1267
|
+
config=config,
|
|
1268
|
+
channels=args.channel,
|
|
1269
|
+
force=args.force_push,
|
|
1270
|
+
dry_run=args.dry_run_push,
|
|
1271
|
+
)
|
|
1272
|
+
except (OSError, RuntimeError, ValueError, IndexError) as exc:
|
|
1273
|
+
parser.error(str(exc))
|
|
1274
|
+
if args.explain and not args.json:
|
|
1275
|
+
print(_format_daily_report_explain(report))
|
|
1276
|
+
else:
|
|
1277
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
1278
|
+
|
|
1279
|
+
elif args.command == "notify":
|
|
1280
|
+
from alphasift.notify import notify_readiness, send_test_notification
|
|
1281
|
+
|
|
1282
|
+
config = Config.from_env()
|
|
1283
|
+
if args.notify_action == "status":
|
|
1284
|
+
info = notify_readiness(config)
|
|
1285
|
+
if args.json:
|
|
1286
|
+
print(json.dumps(info, ensure_ascii=False, indent=2))
|
|
1287
|
+
else:
|
|
1288
|
+
chans = ", ".join(info["configured_channels"]) or "none"
|
|
1289
|
+
print(f"Configured channels: {chans}")
|
|
1290
|
+
print(f"Supported channels: {', '.join(info['supported_channels'])}")
|
|
1291
|
+
print(f"Idempotency ledger: {info['state_path']}")
|
|
1292
|
+
elif args.notify_action == "test":
|
|
1293
|
+
try:
|
|
1294
|
+
res = send_test_notification(
|
|
1295
|
+
config=config,
|
|
1296
|
+
channels=args.channel,
|
|
1297
|
+
dry_run=args.dry_run,
|
|
1298
|
+
)
|
|
1299
|
+
except ValueError as exc:
|
|
1300
|
+
parser.error(str(exc))
|
|
1301
|
+
if args.json:
|
|
1302
|
+
print(json.dumps(res, ensure_ascii=False, indent=2))
|
|
1303
|
+
else:
|
|
1304
|
+
print(
|
|
1305
|
+
f"notify_test status={res['status']} "
|
|
1306
|
+
f"sent={','.join(res['sent']) or 'none'} "
|
|
1307
|
+
f"skipped={len(res['skipped'])} errors={len(res['errors'])}"
|
|
1308
|
+
)
|
|
1309
|
+
for err in res["errors"]:
|
|
1310
|
+
print(f" error [{err['channel']}]: {err['error']}")
|
|
1311
|
+
|
|
1312
|
+
else:
|
|
1313
|
+
parser.print_help()
|
|
1314
|
+
sys.exit(1)
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def _run_quickstart(*, strategy: str = "dual_low", max_output: int = 5) -> None:
|
|
1318
|
+
"""One-shot showcase: list strategies, screen without LLM, print top picks.
|
|
1319
|
+
|
|
1320
|
+
Mirrors the AlphaEvo `showcase` UX: no API key required, prints a
|
|
1321
|
+
deterministic-looking summary that fits a single screen.
|
|
1322
|
+
"""
|
|
1323
|
+
print("=" * 60)
|
|
1324
|
+
print("AlphaSift Quickstart · 无 API key 演示")
|
|
1325
|
+
print("=" * 60)
|
|
1326
|
+
print()
|
|
1327
|
+
|
|
1328
|
+
config = Config.from_env()
|
|
1329
|
+
strategies = list_strategies(config.strategies_dir)
|
|
1330
|
+
print(f"[1/3] 可用策略 ({len(strategies)}):")
|
|
1331
|
+
for s in strategies:
|
|
1332
|
+
marker = "→" if s.name == strategy else " "
|
|
1333
|
+
print(f" {marker} {s.name:<20s} {s.display_name}")
|
|
1334
|
+
print()
|
|
1335
|
+
|
|
1336
|
+
print(f"[2/3] 执行 `{strategy}` 选股 (--no-llm, --no-post-analysis, top {max_output}) …")
|
|
1337
|
+
try:
|
|
1338
|
+
result = screen(
|
|
1339
|
+
strategy,
|
|
1340
|
+
market="cn",
|
|
1341
|
+
max_output=max_output,
|
|
1342
|
+
use_llm=False,
|
|
1343
|
+
post_analyzers=[],
|
|
1344
|
+
)
|
|
1345
|
+
except Exception as exc: # noqa: BLE001
|
|
1346
|
+
print(f" 失败: {exc}")
|
|
1347
|
+
print(" 提示: 检查网络,或设置 SNAPSHOT_SOURCE_PRIORITY / TUSHARE_TOKEN")
|
|
1348
|
+
sys.exit(2)
|
|
1349
|
+
|
|
1350
|
+
print(
|
|
1351
|
+
f" 全市场 {result.snapshot_count} 只 → 硬筛后 {result.after_filter_count} 只 "
|
|
1352
|
+
f"→ 输出 {len(result.picks)} 只 (源: {result.snapshot_source})"
|
|
1353
|
+
)
|
|
1354
|
+
print()
|
|
1355
|
+
|
|
1356
|
+
print("[3/3] 候选排名:")
|
|
1357
|
+
print(f" {'rank':<5}{'code':<10}{'name':<14}{'score':<8}{'price':<8}{'pe':<8}{'pb':<6}")
|
|
1358
|
+
for pick in result.picks:
|
|
1359
|
+
pe = f"{pick.pe_ratio:.1f}" if pick.pe_ratio is not None else "-"
|
|
1360
|
+
pb = f"{pick.pb_ratio:.2f}" if pick.pb_ratio is not None else "-"
|
|
1361
|
+
print(
|
|
1362
|
+
f" {pick.rank:<5}{pick.code:<10}{pick.name[:12]:<14}"
|
|
1363
|
+
f"{pick.final_score:<8.1f}{pick.price:<8.2f}{pe:<8}{pb:<6}"
|
|
1364
|
+
)
|
|
1365
|
+
print()
|
|
1366
|
+
print("下一步:")
|
|
1367
|
+
print(" alphasift screen <strategy> --explain # 查看入选理由和因子分")
|
|
1368
|
+
print(" alphasift screen <strategy> --save-run # 保存运行")
|
|
1369
|
+
print(" alphasift evaluate <run_id> --explain # T+N 评估")
|
|
1370
|
+
print(" alphasift strategies # 完整策略列表")
|
|
1371
|
+
|
|
1372
|
+
|
|
1373
|
+
def _overview_strategy_match_from_args(args) -> dict[str, object]:
|
|
1374
|
+
daily_required = _parse_daily_required(args.daily_required)
|
|
1375
|
+
return {
|
|
1376
|
+
"risk_profile": args.risk_profile or "",
|
|
1377
|
+
"holding_period": args.holding_period or "",
|
|
1378
|
+
"execution_style": args.execution_style or "",
|
|
1379
|
+
"market_regime": _split_csv_args(args.market_regime) or [],
|
|
1380
|
+
"capital_profile": args.capital_profile or "",
|
|
1381
|
+
"data_requirements": _split_csv_args(args.data_requirement) or [],
|
|
1382
|
+
"tags": _split_csv_args(args.tag) or [],
|
|
1383
|
+
"category": args.category or "",
|
|
1384
|
+
"daily_required": daily_required,
|
|
1385
|
+
"strict": bool(args.strict),
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def _format_overview_explain(payload: dict) -> str:
|
|
1390
|
+
summary = payload.get("summary", {}) or {}
|
|
1391
|
+
data_sources = payload.get("data_sources", {}) or {}
|
|
1392
|
+
health = data_sources.get("health_summary", {}) or {}
|
|
1393
|
+
freshness = data_sources.get("freshness_summary", {}) or {}
|
|
1394
|
+
lines = [
|
|
1395
|
+
(
|
|
1396
|
+
f"overview generated_at={payload.get('generated_at')} "
|
|
1397
|
+
f"strategies={summary.get('strategy_count')} "
|
|
1398
|
+
f"daily_strategies={summary.get('daily_strategy_count')} "
|
|
1399
|
+
f"runs={summary.get('recent_run_count')} "
|
|
1400
|
+
f"matches={summary.get('strategy_match_count')} "
|
|
1401
|
+
f"data_status={summary.get('data_source_status')} "
|
|
1402
|
+
f"live_check={summary.get('live_data_check')}"
|
|
1403
|
+
),
|
|
1404
|
+
]
|
|
1405
|
+
if health.get("snapshot"):
|
|
1406
|
+
lines.append(_format_source_health_summary("snapshot_health", health["snapshot"]))
|
|
1407
|
+
if health.get("daily"):
|
|
1408
|
+
lines.append(_format_source_health_summary("daily_health", health["daily"]))
|
|
1409
|
+
if freshness:
|
|
1410
|
+
lines.append(_format_freshness_summary(freshness))
|
|
1411
|
+
source_history = payload.get("data_source_history") or {}
|
|
1412
|
+
if source_history.get("run_count"):
|
|
1413
|
+
lines.append(_format_data_source_history_summary(source_history))
|
|
1414
|
+
performance = payload.get("performance_summary") or {}
|
|
1415
|
+
if performance.get("evaluation_count"):
|
|
1416
|
+
lines.append(_format_performance_summary_line(performance))
|
|
1417
|
+
groups = payload.get("strategy_groups", {}) or {}
|
|
1418
|
+
for title, key in (
|
|
1419
|
+
("categories", "by_category"),
|
|
1420
|
+
("risk_profiles", "by_risk_profile"),
|
|
1421
|
+
("holding_periods", "by_holding_period"),
|
|
1422
|
+
("data_requirements", "by_data_requirement"),
|
|
1423
|
+
):
|
|
1424
|
+
group_text = _format_overview_groups(groups.get(key, []) or [])
|
|
1425
|
+
if group_text:
|
|
1426
|
+
lines.append(f"{title}={group_text}")
|
|
1427
|
+
matches = payload.get("strategy_matches", []) or []
|
|
1428
|
+
if matches:
|
|
1429
|
+
lines.append("strategy_matches:")
|
|
1430
|
+
for item in matches:
|
|
1431
|
+
lines.append(_format_strategy_match_line(item))
|
|
1432
|
+
runs = payload.get("recent_runs", []) or []
|
|
1433
|
+
if runs:
|
|
1434
|
+
lines.append("recent_runs:")
|
|
1435
|
+
for item in runs:
|
|
1436
|
+
lines.append(
|
|
1437
|
+
f"- {item.get('run_id')} strategy={item.get('strategy')} "
|
|
1438
|
+
f"picks={item.get('picks')} source={item.get('snapshot_source') or '-'} "
|
|
1439
|
+
f"degraded={item.get('degradation_count', 0)}"
|
|
1440
|
+
)
|
|
1441
|
+
actions = payload.get("next_actions", []) or []
|
|
1442
|
+
if actions:
|
|
1443
|
+
lines.append("next_actions=" + " | ".join(str(item) for item in actions))
|
|
1444
|
+
return "\n".join(lines)
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def _format_overview_groups(groups: list[dict[str, object]], *, limit: int = 6) -> str:
|
|
1448
|
+
if not groups:
|
|
1449
|
+
return ""
|
|
1450
|
+
shown = groups[:limit]
|
|
1451
|
+
text = ",".join(f"{item.get('name')}:{item.get('count')}" for item in shown)
|
|
1452
|
+
if len(groups) > limit:
|
|
1453
|
+
text += f",+{len(groups) - limit}"
|
|
1454
|
+
return text
|
|
1455
|
+
|
|
1456
|
+
|
|
1457
|
+
def _format_data_source_history_summary(summary: dict) -> str:
|
|
1458
|
+
values = summary.get("summary") or {}
|
|
1459
|
+
watchlist = summary.get("watchlist") or []
|
|
1460
|
+
return (
|
|
1461
|
+
"source_history="
|
|
1462
|
+
f"runs={summary.get('run_count', 0)} "
|
|
1463
|
+
f"sources={summary.get('source_count', 0)} "
|
|
1464
|
+
f"status={values.get('stability_status', 'unknown')} "
|
|
1465
|
+
f"score={values.get('stability_score', '-')} "
|
|
1466
|
+
f"source_error_rate={values.get('source_error_rate', 0.0)} "
|
|
1467
|
+
f"degradation_rate={values.get('degradation_rate', 0.0)} "
|
|
1468
|
+
f"fallback_rate={values.get('fallback_rate', 0.0)} "
|
|
1469
|
+
f"watchlist={len(watchlist)}"
|
|
1470
|
+
)
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def _format_performance_summary_line(payload: dict) -> str:
|
|
1474
|
+
values = payload.get("summary") or {}
|
|
1475
|
+
leaderboard = payload.get("leaderboard") or []
|
|
1476
|
+
return (
|
|
1477
|
+
"performance="
|
|
1478
|
+
f"evaluations={payload.get('evaluation_count', 0)} "
|
|
1479
|
+
f"strategies={payload.get('strategy_count', 0)} "
|
|
1480
|
+
f"outcome={values.get('outcome', 'insufficient_data')} "
|
|
1481
|
+
f"score={_display_value(values.get('performance_score'))} "
|
|
1482
|
+
f"avg_return={_display_value(values.get('average_return_pct'))} "
|
|
1483
|
+
f"win_rate={_display_value(values.get('win_rate'))} "
|
|
1484
|
+
f"leaderboard={len(leaderboard)}"
|
|
1485
|
+
)
|
|
1486
|
+
|
|
1487
|
+
|
|
1488
|
+
def _format_performance_summary_explain(payload: dict) -> str:
|
|
1489
|
+
lines = [_format_performance_summary_line(payload)]
|
|
1490
|
+
rows = payload.get("leaderboard") or []
|
|
1491
|
+
if rows:
|
|
1492
|
+
lines.append("performance_leaderboard strategy evals score outcome avg_return win_rate latest_run")
|
|
1493
|
+
for item in rows[:10]:
|
|
1494
|
+
lines.append(
|
|
1495
|
+
f" {item.get('strategy')} "
|
|
1496
|
+
f"{item.get('evaluation_count', 0)} "
|
|
1497
|
+
f"{_display_value(item.get('performance_score'))} "
|
|
1498
|
+
f"{item.get('outcome', '-')} "
|
|
1499
|
+
f"{_display_value(item.get('average_return_pct'))} "
|
|
1500
|
+
f"{_display_value(item.get('win_rate'))} "
|
|
1501
|
+
f"{item.get('latest_run_id', '-')}"
|
|
1502
|
+
)
|
|
1503
|
+
actions = (payload.get("summary") or {}).get("next_actions") or []
|
|
1504
|
+
if actions:
|
|
1505
|
+
lines.append("performance_next_actions=" + " | ".join(str(item) for item in actions))
|
|
1506
|
+
return "\n".join(lines)
|
|
1507
|
+
|
|
1508
|
+
|
|
1509
|
+
def _display_value(value: object) -> object:
|
|
1510
|
+
return "-" if value is None else value
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def _format_strategies_explain(strategies) -> str:
|
|
1514
|
+
lines = [f"strategies={len(strategies)}"]
|
|
1515
|
+
for strategy in strategies:
|
|
1516
|
+
factors = _format_top_factor_weights(strategy.factor_weights)
|
|
1517
|
+
data = ",".join(strategy.data_requirements) or "-"
|
|
1518
|
+
filters = ",".join(strategy.active_filters[:8]) or "-"
|
|
1519
|
+
extra_filters = len(strategy.active_filters) - 8
|
|
1520
|
+
if extra_filters > 0:
|
|
1521
|
+
filters = f"{filters},+{extra_filters}"
|
|
1522
|
+
profiles = ",".join(strategy.profile_keys) or "-"
|
|
1523
|
+
tags = ",".join(strategy.tags) or "-"
|
|
1524
|
+
style = _format_strategy_style(strategy.style)
|
|
1525
|
+
required_fields = _format_required_strategy_fields(
|
|
1526
|
+
strategy.required_snapshot_fields,
|
|
1527
|
+
strategy.required_daily_fields,
|
|
1528
|
+
)
|
|
1529
|
+
lines.append(
|
|
1530
|
+
f"{strategy.name:<24} v{strategy.version:<5} [{strategy.category:<9}] "
|
|
1531
|
+
f"data={data:<32} daily_required={strategy.requires_daily_features!s:<5} "
|
|
1532
|
+
f"style={style:<40} factors={factors:<42} filters={filters} profiles={profiles} tags={tags}"
|
|
1533
|
+
)
|
|
1534
|
+
if required_fields:
|
|
1535
|
+
lines.append(f" required_fields={required_fields}")
|
|
1536
|
+
lines.append(f" {strategy.display_name}: {strategy.description}")
|
|
1537
|
+
return "\n".join(lines)
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
def _format_strategy_templates_explain(templates: list[dict[str, object]]) -> str:
|
|
1541
|
+
lines = [f"strategy_templates={len(templates)}"]
|
|
1542
|
+
for template in templates:
|
|
1543
|
+
style = template.get("style", {})
|
|
1544
|
+
if not isinstance(style, dict):
|
|
1545
|
+
style = {}
|
|
1546
|
+
tags = ",".join(str(value) for value in template.get("tags", []) or []) or "-"
|
|
1547
|
+
data = ",".join(str(value) for value in template.get("data_requirements", []) or []) or "-"
|
|
1548
|
+
lines.append(
|
|
1549
|
+
f"{str(template.get('name', '')):<28} [{str(template.get('category', '-')):<9}] "
|
|
1550
|
+
f"data={data:<28} style={_format_strategy_style(style):<40} tags={tags}"
|
|
1551
|
+
)
|
|
1552
|
+
lines.append(f" {template.get('display_name')}: {template.get('description')}")
|
|
1553
|
+
notes = template.get("notes", []) or []
|
|
1554
|
+
for note in notes:
|
|
1555
|
+
lines.append(f" note={note}")
|
|
1556
|
+
return "\n".join(lines)
|
|
1557
|
+
|
|
1558
|
+
|
|
1559
|
+
def _format_strategy_template_explain(template: dict[str, object]) -> str:
|
|
1560
|
+
style = template.get("style", {})
|
|
1561
|
+
if not isinstance(style, dict):
|
|
1562
|
+
style = {}
|
|
1563
|
+
data = ",".join(str(value) for value in template.get("data_requirements", []) or []) or "-"
|
|
1564
|
+
lines = [
|
|
1565
|
+
f"strategy_template={template.get('name')} display_name={template.get('display_name')}",
|
|
1566
|
+
(
|
|
1567
|
+
f"category={template.get('category')} data={data} "
|
|
1568
|
+
f"style={_format_strategy_style(style)}"
|
|
1569
|
+
),
|
|
1570
|
+
f"description={template.get('description')}",
|
|
1571
|
+
]
|
|
1572
|
+
notes = template.get("notes", []) or []
|
|
1573
|
+
for note in notes:
|
|
1574
|
+
lines.append(f"note={note}")
|
|
1575
|
+
lines.append("---")
|
|
1576
|
+
lines.append(str(template.get("yaml") or ""))
|
|
1577
|
+
return "\n".join(lines)
|
|
1578
|
+
|
|
1579
|
+
|
|
1580
|
+
def _format_strategy_compare_explain(payload: dict[str, object]) -> str:
|
|
1581
|
+
base = payload.get("base", {}) or {}
|
|
1582
|
+
target = payload.get("target", {}) or {}
|
|
1583
|
+
summary = payload.get("summary", {}) or {}
|
|
1584
|
+
differences = payload.get("differences", {}) or {}
|
|
1585
|
+
lines = [
|
|
1586
|
+
(
|
|
1587
|
+
f"strategy_compare base={base.get('name')} v{base.get('version')} "
|
|
1588
|
+
f"target={target.get('name')} v{target.get('version')} "
|
|
1589
|
+
f"changed_sections={','.join(summary.get('changed_sections', []) or []) or '-'} "
|
|
1590
|
+
f"change_count={summary.get('change_count', 0)}"
|
|
1591
|
+
)
|
|
1592
|
+
]
|
|
1593
|
+
notes = summary.get("compatibility_notes", []) or []
|
|
1594
|
+
if notes:
|
|
1595
|
+
lines.append("compatibility_notes=" + " | ".join(str(item) for item in notes))
|
|
1596
|
+
for section in (
|
|
1597
|
+
"identity",
|
|
1598
|
+
"tags",
|
|
1599
|
+
"style",
|
|
1600
|
+
"data_requirements",
|
|
1601
|
+
"required_snapshot_fields",
|
|
1602
|
+
"required_daily_fields",
|
|
1603
|
+
"active_filters",
|
|
1604
|
+
"hard_filter_values",
|
|
1605
|
+
"factor_weights",
|
|
1606
|
+
"profile_keys",
|
|
1607
|
+
):
|
|
1608
|
+
text = _format_diff_section(differences.get(section, {}))
|
|
1609
|
+
if text:
|
|
1610
|
+
lines.append(f"{section}: {text}")
|
|
1611
|
+
return "\n".join(lines)
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
def _format_diff_section(diff: object) -> str:
|
|
1615
|
+
if not isinstance(diff, dict):
|
|
1616
|
+
return ""
|
|
1617
|
+
parts = []
|
|
1618
|
+
for key in ("added", "removed"):
|
|
1619
|
+
value = diff.get(key)
|
|
1620
|
+
if value:
|
|
1621
|
+
parts.append(f"{key}={_compact_diff_value(value)}")
|
|
1622
|
+
changed = diff.get("changed")
|
|
1623
|
+
if changed:
|
|
1624
|
+
parts.append("changed=" + _compact_changed_values(changed))
|
|
1625
|
+
nested_parts = []
|
|
1626
|
+
for key, value in diff.items():
|
|
1627
|
+
if key in {"added", "removed", "changed", "shared"}:
|
|
1628
|
+
continue
|
|
1629
|
+
if isinstance(value, dict):
|
|
1630
|
+
nested = _format_diff_section(value)
|
|
1631
|
+
if nested:
|
|
1632
|
+
nested_parts.append(f"{key}[{nested}]")
|
|
1633
|
+
parts.extend(nested_parts)
|
|
1634
|
+
return " ".join(parts)
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
def _compact_changed_values(changed: object, *, limit: int = 8) -> str:
|
|
1638
|
+
if not isinstance(changed, dict):
|
|
1639
|
+
return _compact_diff_value(changed)
|
|
1640
|
+
items = []
|
|
1641
|
+
for idx, (key, value) in enumerate(changed.items()):
|
|
1642
|
+
if idx >= limit:
|
|
1643
|
+
items.append(f"+{len(changed) - limit}")
|
|
1644
|
+
break
|
|
1645
|
+
if isinstance(value, dict) and "base" in value and "target" in value:
|
|
1646
|
+
base = _compact_diff_value(value.get("base"))
|
|
1647
|
+
target = _compact_diff_value(value.get("target"))
|
|
1648
|
+
if "delta" in value:
|
|
1649
|
+
items.append(f"{key}:{base}->{target}({value.get('delta'):+g})")
|
|
1650
|
+
else:
|
|
1651
|
+
items.append(f"{key}:{base}->{target}")
|
|
1652
|
+
else:
|
|
1653
|
+
items.append(f"{key}:{_compact_diff_value(value)}")
|
|
1654
|
+
return ",".join(items)
|
|
1655
|
+
|
|
1656
|
+
|
|
1657
|
+
def _compact_diff_value(value: object, *, limit: int = 8) -> str:
|
|
1658
|
+
if isinstance(value, list):
|
|
1659
|
+
shown = [str(item) for item in value[:limit]]
|
|
1660
|
+
if len(value) > limit:
|
|
1661
|
+
shown.append(f"+{len(value) - limit}")
|
|
1662
|
+
return ",".join(shown)
|
|
1663
|
+
if isinstance(value, dict):
|
|
1664
|
+
items = []
|
|
1665
|
+
for idx, (key, item) in enumerate(value.items()):
|
|
1666
|
+
if idx >= limit:
|
|
1667
|
+
items.append(f"+{len(value) - limit}")
|
|
1668
|
+
break
|
|
1669
|
+
items.append(f"{key}:{item}")
|
|
1670
|
+
return ",".join(items)
|
|
1671
|
+
return str(value)
|
|
1672
|
+
|
|
1673
|
+
|
|
1674
|
+
def _has_strategy_match_args(args) -> bool:
|
|
1675
|
+
return any((
|
|
1676
|
+
bool(args.risk_profile),
|
|
1677
|
+
bool(args.holding_period),
|
|
1678
|
+
bool(args.execution_style),
|
|
1679
|
+
bool(args.market_regime),
|
|
1680
|
+
bool(args.capital_profile),
|
|
1681
|
+
bool(args.data_requirement),
|
|
1682
|
+
bool(args.tag),
|
|
1683
|
+
bool(args.category),
|
|
1684
|
+
args.daily_required != "any",
|
|
1685
|
+
bool(args.strict),
|
|
1686
|
+
args.limit is not None,
|
|
1687
|
+
))
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
def _strategy_match_criteria_from_args(args) -> dict[str, object]:
|
|
1691
|
+
criteria: dict[str, object] = {}
|
|
1692
|
+
for attr in ("risk_profile", "holding_period", "execution_style", "capital_profile", "category"):
|
|
1693
|
+
value = getattr(args, attr)
|
|
1694
|
+
if value:
|
|
1695
|
+
criteria[attr] = value
|
|
1696
|
+
for attr, key in (
|
|
1697
|
+
("market_regime", "market_regime"),
|
|
1698
|
+
("data_requirement", "data_requirements"),
|
|
1699
|
+
("tag", "tags"),
|
|
1700
|
+
):
|
|
1701
|
+
value = _split_csv_args(getattr(args, attr)) or []
|
|
1702
|
+
if value:
|
|
1703
|
+
criteria[key] = value
|
|
1704
|
+
daily_required = _parse_daily_required(args.daily_required)
|
|
1705
|
+
if daily_required is not None:
|
|
1706
|
+
criteria["daily_required"] = daily_required
|
|
1707
|
+
if args.strict:
|
|
1708
|
+
criteria["strict"] = True
|
|
1709
|
+
if args.limit is not None:
|
|
1710
|
+
criteria["limit"] = args.limit
|
|
1711
|
+
return criteria
|
|
1712
|
+
|
|
1713
|
+
|
|
1714
|
+
def _parse_daily_required(value: str) -> bool | None:
|
|
1715
|
+
if value == "true":
|
|
1716
|
+
return True
|
|
1717
|
+
if value == "false":
|
|
1718
|
+
return False
|
|
1719
|
+
return None
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
def _format_strategy_matches_explain(matches: list[dict[str, object]], *, criteria: dict[str, object]) -> str:
|
|
1723
|
+
lines = [
|
|
1724
|
+
f"strategy_matches={len(matches)} criteria={_format_match_criteria(criteria)}",
|
|
1725
|
+
]
|
|
1726
|
+
if not matches:
|
|
1727
|
+
return "\n".join(lines)
|
|
1728
|
+
lines.append("score strategy category style data daily matched missing")
|
|
1729
|
+
for item in matches:
|
|
1730
|
+
lines.append(_format_strategy_match_line(item))
|
|
1731
|
+
return "\n".join(lines)
|
|
1732
|
+
|
|
1733
|
+
|
|
1734
|
+
def _format_strategy_match_line(item: dict[str, object]) -> str:
|
|
1735
|
+
style = item.get("style", {})
|
|
1736
|
+
if not isinstance(style, dict):
|
|
1737
|
+
style = {}
|
|
1738
|
+
data = ",".join(str(value) for value in item.get("data_requirements", []) or []) or "-"
|
|
1739
|
+
matched = _format_match_tokens(item.get("matched", []) or [])
|
|
1740
|
+
missing = _format_match_tokens(item.get("missing", []) or [])
|
|
1741
|
+
return (
|
|
1742
|
+
f"{float(item.get('score', 0.0)):>4.1f} "
|
|
1743
|
+
f"{str(item.get('name', '')):<24} "
|
|
1744
|
+
f"{str(item.get('category', '-')):<9} "
|
|
1745
|
+
f"style={_format_strategy_style(style):<40} "
|
|
1746
|
+
f"data={data:<32} "
|
|
1747
|
+
f"daily={str(item.get('requires_daily_features', False)):<5} "
|
|
1748
|
+
f"matched={matched} missing={missing}"
|
|
1749
|
+
)
|
|
1750
|
+
|
|
1751
|
+
|
|
1752
|
+
def _format_match_criteria(criteria: dict[str, object]) -> str:
|
|
1753
|
+
if not criteria:
|
|
1754
|
+
return "-"
|
|
1755
|
+
parts = []
|
|
1756
|
+
for key, value in criteria.items():
|
|
1757
|
+
if isinstance(value, list):
|
|
1758
|
+
value_text = ",".join(str(item) for item in value)
|
|
1759
|
+
else:
|
|
1760
|
+
value_text = str(value).lower() if isinstance(value, bool) else str(value)
|
|
1761
|
+
parts.append(f"{key}={value_text}")
|
|
1762
|
+
return ";".join(parts)
|
|
1763
|
+
|
|
1764
|
+
|
|
1765
|
+
def _format_match_tokens(values: object, *, limit: int = 6) -> str:
|
|
1766
|
+
if not isinstance(values, list):
|
|
1767
|
+
return "-"
|
|
1768
|
+
shown = [str(item) for item in values[:limit]]
|
|
1769
|
+
if not shown:
|
|
1770
|
+
return "-"
|
|
1771
|
+
suffix = f",+{len(values) - limit}" if len(values) > limit else ""
|
|
1772
|
+
return ",".join(shown) + suffix
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
def _format_top_factor_weights(weights: dict[str, float], *, limit: int = 4) -> str:
|
|
1776
|
+
if not weights:
|
|
1777
|
+
return "-"
|
|
1778
|
+
ordered = sorted(weights.items(), key=lambda item: (-float(item[1]), item[0]))[:limit]
|
|
1779
|
+
return ",".join(f"{name}:{float(value):.2f}" for name, value in ordered)
|
|
1780
|
+
|
|
1781
|
+
|
|
1782
|
+
def _format_strategy_style(style: dict[str, object]) -> str:
|
|
1783
|
+
if not style:
|
|
1784
|
+
return "-"
|
|
1785
|
+
regime = ",".join(str(item) for item in style.get("market_regime", []) or [])
|
|
1786
|
+
parts = [
|
|
1787
|
+
str(style.get("risk_profile") or "-"),
|
|
1788
|
+
str(style.get("holding_period") or "-"),
|
|
1789
|
+
str(style.get("execution_style") or "-"),
|
|
1790
|
+
]
|
|
1791
|
+
if regime:
|
|
1792
|
+
parts.append(regime)
|
|
1793
|
+
return "/".join(parts)
|
|
1794
|
+
|
|
1795
|
+
|
|
1796
|
+
def _format_required_strategy_fields(
|
|
1797
|
+
snapshot_fields: list[str],
|
|
1798
|
+
daily_fields: list[str],
|
|
1799
|
+
*,
|
|
1800
|
+
limit: int = 8,
|
|
1801
|
+
) -> str:
|
|
1802
|
+
groups = []
|
|
1803
|
+
if snapshot_fields:
|
|
1804
|
+
groups.append(f"snapshot[{_format_limited_csv(snapshot_fields, limit=limit)}]")
|
|
1805
|
+
if daily_fields:
|
|
1806
|
+
groups.append(f"daily_k[{_format_limited_csv(daily_fields, limit=limit)}]")
|
|
1807
|
+
return " ".join(groups)
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
def _format_limited_csv(values: list[str], *, limit: int) -> str:
|
|
1811
|
+
shown = values[:limit]
|
|
1812
|
+
suffix = f",+{len(values) - limit}" if len(values) > limit else ""
|
|
1813
|
+
return ",".join(shown) + suffix
|
|
1814
|
+
|
|
1815
|
+
|
|
1816
|
+
def _format_screen_explain(result) -> str:
|
|
1817
|
+
lines = [
|
|
1818
|
+
f"run_id={result.run_id} strategy={result.strategy} market={result.market}",
|
|
1819
|
+
(
|
|
1820
|
+
f"snapshot={result.snapshot_count} after_filter={result.after_filter_count} "
|
|
1821
|
+
f"source={result.snapshot_source or '-'} llm_ranked={result.llm_ranked}"
|
|
1822
|
+
),
|
|
1823
|
+
]
|
|
1824
|
+
if result.post_analyzers:
|
|
1825
|
+
lines.append(f"post_analyzers={','.join(result.post_analyzers)}")
|
|
1826
|
+
if result.llm_market_view:
|
|
1827
|
+
lines.append(f"llm_market_view={result.llm_market_view}")
|
|
1828
|
+
if result.llm_selection_logic:
|
|
1829
|
+
lines.append(f"llm_selection_logic={result.llm_selection_logic}")
|
|
1830
|
+
if result.llm_portfolio_risk:
|
|
1831
|
+
lines.append(f"llm_portfolio_risk={result.llm_portfolio_risk}")
|
|
1832
|
+
if result.portfolio_concentration_notes:
|
|
1833
|
+
lines.append("portfolio_concentration=" + " | ".join(result.portfolio_concentration_notes))
|
|
1834
|
+
if result.saved_path:
|
|
1835
|
+
lines.append(f"saved_path={result.saved_path}")
|
|
1836
|
+
if result.degradation:
|
|
1837
|
+
lines.append("degradation=" + " | ".join(result.degradation))
|
|
1838
|
+
lines.append("rank code name final screen risk sector penalty reason")
|
|
1839
|
+
for pick in result.picks:
|
|
1840
|
+
reason = (
|
|
1841
|
+
pick.llm_thesis
|
|
1842
|
+
or pick.ranking_reason
|
|
1843
|
+
or pick.post_analysis_summaries.get("scorecard", "")
|
|
1844
|
+
)
|
|
1845
|
+
lines.append(
|
|
1846
|
+
f"{pick.rank:<4} {pick.code:<8} {pick.name:<10} "
|
|
1847
|
+
f"{pick.final_score:>6.1f} {pick.screen_score:>6.1f} "
|
|
1848
|
+
f"{pick.risk_level or '-':<6} {pick.llm_sector or '-':<8} "
|
|
1849
|
+
f"{pick.portfolio_penalty:>4.1f} {reason[:48]}"
|
|
1850
|
+
)
|
|
1851
|
+
return "\n".join(lines)
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
def _format_evaluation_explain(result) -> str:
|
|
1855
|
+
lines = [
|
|
1856
|
+
f"run_id={result.run_id} strategy={result.strategy} elapsed_days={result.elapsed_days}",
|
|
1857
|
+
(
|
|
1858
|
+
f"avg_return={result.average_return_pct} "
|
|
1859
|
+
f"median_return={result.median_return_pct} win_rate={result.win_rate}"
|
|
1860
|
+
),
|
|
1861
|
+
]
|
|
1862
|
+
next_open = result.entry_mode == "next_open"
|
|
1863
|
+
if result.horizon_days is not None:
|
|
1864
|
+
lines.append(
|
|
1865
|
+
f"window=T+{result.horizon_days} entry_mode={result.entry_mode} "
|
|
1866
|
+
f"pending={result.pending_count} avg_excess={_fmt_pct(result.average_excess_return_pct)}"
|
|
1867
|
+
)
|
|
1868
|
+
if next_open:
|
|
1869
|
+
lines.append(
|
|
1870
|
+
f"untradable={result.untradable_count} "
|
|
1871
|
+
f"untradable_share={_fmt_pct(result.untradable_share_pct)}"
|
|
1872
|
+
)
|
|
1873
|
+
if result.saved_path:
|
|
1874
|
+
lines.append(f"saved_path={result.saved_path}")
|
|
1875
|
+
if result.run_snapshot_source or result.daily_source_counts or result.daily_quality_flag_counts:
|
|
1876
|
+
lines.append(
|
|
1877
|
+
"run_data_quality "
|
|
1878
|
+
f"snapshot={result.run_snapshot_source or '-'} "
|
|
1879
|
+
f"daily_sources={result.daily_source_counts or {}} "
|
|
1880
|
+
f"daily_flags={result.daily_quality_flag_counts or {}}"
|
|
1881
|
+
)
|
|
1882
|
+
if result.degradation:
|
|
1883
|
+
lines.append("degradation=" + " | ".join(result.degradation))
|
|
1884
|
+
columns = "rank code name entry current return_pct status shape max_dd max_runup"
|
|
1885
|
+
lines.append(columns + (" path_status flags" if next_open else ""))
|
|
1886
|
+
for pick in result.picks:
|
|
1887
|
+
entry = _fmt_optional_float(pick.entry_open if next_open else pick.entry_price)
|
|
1888
|
+
current = "-" if pick.current_price is None else f"{pick.current_price:.2f}"
|
|
1889
|
+
ret = "-" if pick.return_pct is None else f"{pick.return_pct:.2f}%"
|
|
1890
|
+
lines.append(
|
|
1891
|
+
f"{pick.rank:<4} {pick.code:<8} {pick.name:<10} "
|
|
1892
|
+
f"{entry:<8} {current:<8} {ret:<9} {pick.status:<10} "
|
|
1893
|
+
f"{pick.shape_status or '-':<24} "
|
|
1894
|
+
f"{_fmt_pct(pick.max_drawdown_pct):<8} {_fmt_pct(pick.max_runup_pct)}"
|
|
1895
|
+
+ (f" {pick.path_status or '-'} {','.join(pick.tradability_flags) or '-'}" if next_open else "")
|
|
1896
|
+
)
|
|
1897
|
+
return "\n".join(lines)
|
|
1898
|
+
|
|
1899
|
+
|
|
1900
|
+
def _format_evaluation_batch_explain(result: dict) -> str:
|
|
1901
|
+
summary = result.get("summary", {})
|
|
1902
|
+
lines = [
|
|
1903
|
+
(
|
|
1904
|
+
f"evaluated_at={result.get('evaluated_at')} "
|
|
1905
|
+
f"source={result.get('snapshot_source') or '-'} "
|
|
1906
|
+
f"runs={summary.get('run_count')} picks={summary.get('pick_count')} "
|
|
1907
|
+
f"cost_bps={result.get('cost_bps')} "
|
|
1908
|
+
f"follow_through={result.get('follow_through_pct')} "
|
|
1909
|
+
f"failed_breakout={result.get('failed_breakout_pct')} "
|
|
1910
|
+
f"price_path={result.get('with_price_path')}"
|
|
1911
|
+
),
|
|
1912
|
+
(
|
|
1913
|
+
f"avg_return={summary.get('average_return_pct')} "
|
|
1914
|
+
f"median_return={summary.get('median_return_pct')} "
|
|
1915
|
+
f"win_rate={summary.get('win_rate')} "
|
|
1916
|
+
f"missing={summary.get('missing_count')} "
|
|
1917
|
+
f"path_picks={summary.get('path_pick_count')} "
|
|
1918
|
+
f"avg_max_dd={summary.get('average_max_drawdown_pct')} "
|
|
1919
|
+
f"avg_max_runup={summary.get('average_max_runup_pct')}"
|
|
1920
|
+
),
|
|
1921
|
+
]
|
|
1922
|
+
if result.get("source_errors"):
|
|
1923
|
+
lines.append("source_errors=" + " | ".join(result["source_errors"]))
|
|
1924
|
+
if result.get("by_strategy"):
|
|
1925
|
+
lines.append("strategy run_count pick_count avg_return median_return win_rate missing")
|
|
1926
|
+
for strategy, item in sorted(result["by_strategy"].items()):
|
|
1927
|
+
lines.append(
|
|
1928
|
+
f"{strategy:<20} {item.get('run_count'):<9} {item.get('pick_count'):<10} "
|
|
1929
|
+
f"{item.get('average_return_pct')!s:<10} {item.get('median_return_pct')!s:<13} "
|
|
1930
|
+
f"{item.get('win_rate')!s:<8} {item.get('missing_count')}"
|
|
1931
|
+
)
|
|
1932
|
+
dimensions = result.get("dimensions", {})
|
|
1933
|
+
for title, key in (
|
|
1934
|
+
("top_sectors", "by_sector"),
|
|
1935
|
+
("top_themes", "by_theme"),
|
|
1936
|
+
("top_llm_catalysts", "by_llm_catalyst"),
|
|
1937
|
+
("top_llm_risks", "by_llm_risk"),
|
|
1938
|
+
("top_post_tags", "by_post_analysis_tag"),
|
|
1939
|
+
("top_risk_flags", "by_risk_flag"),
|
|
1940
|
+
("shape_status", "by_shape_status"),
|
|
1941
|
+
("shape_tags", "by_shape_tag"),
|
|
1942
|
+
("path_status", "by_path_status"),
|
|
1943
|
+
("holding_periods", "by_holding_period"),
|
|
1944
|
+
):
|
|
1945
|
+
items = _top_dimension_items(dimensions.get(key, {}))
|
|
1946
|
+
if items:
|
|
1947
|
+
lines.append(f"{title}=" + " | ".join(items))
|
|
1948
|
+
lines.extend(_format_data_quality_review_explain(result.get("data_quality_review", {})))
|
|
1949
|
+
lines.extend(_format_event_signal_review_explain(result.get("event_signal_review", {})))
|
|
1950
|
+
lines.extend(_format_failure_review_explain(result.get("failure_review", {})))
|
|
1951
|
+
return "\n".join(lines)
|
|
1952
|
+
|
|
1953
|
+
|
|
1954
|
+
def _format_evaluate_strategies_explain(result: dict) -> str:
|
|
1955
|
+
lines = [
|
|
1956
|
+
(
|
|
1957
|
+
f"evaluated_at={result.get('evaluated_at')} "
|
|
1958
|
+
f"source={result.get('snapshot_source') or '-'} "
|
|
1959
|
+
f"limit={result.get('limit')} strategy_filter={result.get('strategy_filter') or '-'} "
|
|
1960
|
+
f"price_path={result.get('with_price_path')} cost_bps={result.get('cost_bps')}"
|
|
1961
|
+
),
|
|
1962
|
+
]
|
|
1963
|
+
if result.get("price_path_window_days"):
|
|
1964
|
+
windows = ",".join(f"{item}d" for item in result.get("price_path_window_days", []))
|
|
1965
|
+
lines.append(f"windows={windows} entry_mode={result.get('entry_mode', 'close')}")
|
|
1966
|
+
if result.get("strategy_summaries", []) and isinstance(result.get("strategy_summaries"), list):
|
|
1967
|
+
sample = result["strategy_summaries"][0]
|
|
1968
|
+
if isinstance(sample, dict) and sample.get("window_summaries") is not None:
|
|
1969
|
+
lines.append(
|
|
1970
|
+
"strategy windows T+N: ret=avg return, bench=benchmark, excess=ret-bench, "
|
|
1971
|
+
"beat=% picks beating benchmark, win, dd, runup, pending, missing"
|
|
1972
|
+
)
|
|
1973
|
+
else:
|
|
1974
|
+
lines.append(
|
|
1975
|
+
"strategy runs picks avg_return median_return win_rate max_dd max_runup outcome shapes"
|
|
1976
|
+
)
|
|
1977
|
+
if result.get("source_errors"):
|
|
1978
|
+
lines.append("source_errors=" + " | ".join(result["source_errors"]))
|
|
1979
|
+
for item in result.get("strategy_summaries", []):
|
|
1980
|
+
windows = item.get("window_summaries")
|
|
1981
|
+
if windows:
|
|
1982
|
+
line_parts = [
|
|
1983
|
+
f"{item.get('strategy'):<20} "
|
|
1984
|
+
f"{item.get('window_count', len(windows))!s:>3}w "
|
|
1985
|
+
]
|
|
1986
|
+
for window in windows:
|
|
1987
|
+
window_days = window.get("window_days", "-")
|
|
1988
|
+
line_parts.append(
|
|
1989
|
+
(
|
|
1990
|
+
f"T+{window_days}:"
|
|
1991
|
+
f"ret={window.get('average_return_pct')!s} "
|
|
1992
|
+
f"bench={window.get('average_benchmark_return_pct')!s} "
|
|
1993
|
+
f"excess={window.get('average_excess_return_pct')!s} "
|
|
1994
|
+
+ _format_partial_benchmark(window)
|
|
1995
|
+
+ f"beat={window.get('beat_benchmark_rate')!s} "
|
|
1996
|
+
f"win={window.get('win_rate')!s} "
|
|
1997
|
+
f"dd={window.get('average_max_drawdown_pct')!s} "
|
|
1998
|
+
f"runup={window.get('average_max_runup_pct')!s} "
|
|
1999
|
+
f"f={window.get('failed_breakout_count', 0)} "
|
|
2000
|
+
f"t={window.get('breakout_follow_through_count', 0)} "
|
|
2001
|
+
f"pending={window.get('pending_count', 0)} "
|
|
2002
|
+
f"m={window.get('missing_count', 0)}"
|
|
2003
|
+
+ (
|
|
2004
|
+
f" untradable={window.get('untradable_count', 0)} "
|
|
2005
|
+
f"untradable_share={_fmt_pct(window.get('untradable_share_pct'))}"
|
|
2006
|
+
if result.get("entry_mode") == "next_open" else ""
|
|
2007
|
+
)
|
|
2008
|
+
+ "".join(
|
|
2009
|
+
f" {flag}={count}" for flag, count in window.get("tradability_flag_counts", {}).items()
|
|
2010
|
+
)
|
|
2011
|
+
+ (
|
|
2012
|
+
f" bench_error={window['benchmark_errors'][0]}"
|
|
2013
|
+
if window.get("benchmark_errors") else ""
|
|
2014
|
+
)
|
|
2015
|
+
+ "; "
|
|
2016
|
+
)
|
|
2017
|
+
)
|
|
2018
|
+
lines.append("".join(line_parts).strip())
|
|
2019
|
+
else:
|
|
2020
|
+
shapes = item.get("shape_status_counts", {}) or {}
|
|
2021
|
+
shape_text = ",".join(f"{name}:{count}" for name, count in sorted(shapes.items())) or "-"
|
|
2022
|
+
lines.append(
|
|
2023
|
+
f"{item.get('strategy'):<20} {item.get('run_count'):<4} {item.get('pick_count'):<5} "
|
|
2024
|
+
f"{item.get('average_return_pct')!s:<10} {item.get('median_return_pct')!s:<13} "
|
|
2025
|
+
f"{item.get('win_rate')!s:<8} {item.get('average_max_drawdown_pct')!s:<8} "
|
|
2026
|
+
f"{item.get('average_max_runup_pct')!s:<9} {item.get('outcome'):<17} {shape_text}"
|
|
2027
|
+
)
|
|
2028
|
+
window_reviews = result.get("window_reviews")
|
|
2029
|
+
if isinstance(window_reviews, list) and window_reviews:
|
|
2030
|
+
for review in window_reviews:
|
|
2031
|
+
if not isinstance(review, dict):
|
|
2032
|
+
continue
|
|
2033
|
+
lines.append(f"-- T+{review.get('window_days')} reviews --")
|
|
2034
|
+
lines.extend(_format_data_quality_review_explain(review.get("data_quality_review", {})))
|
|
2035
|
+
lines.extend(_format_event_signal_review_explain(review.get("event_signal_review", {}), limit=5))
|
|
2036
|
+
lines.extend(_format_failure_review_explain(review.get("failure_review", {}), include_samples=False))
|
|
2037
|
+
return "\n".join(lines)
|
|
2038
|
+
lines.extend(_format_data_quality_review_explain(result.get("data_quality_review", {})))
|
|
2039
|
+
lines.extend(_format_event_signal_review_explain(result.get("event_signal_review", {}), limit=5))
|
|
2040
|
+
lines.extend(_format_failure_review_explain(result.get("failure_review", {}), include_samples=False))
|
|
2041
|
+
return "\n".join(lines)
|
|
2042
|
+
|
|
2043
|
+
|
|
2044
|
+
def _format_data_quality_review_explain(review: object) -> list[str]:
|
|
2045
|
+
if not isinstance(review, dict) or not review:
|
|
2046
|
+
return []
|
|
2047
|
+
cd = review.get("clean_vs_degraded", {}) if isinstance(review.get("clean_vs_degraded"), dict) else {}
|
|
2048
|
+
clean_avg = (cd.get("clean") or {}).get("average_return_pct") if isinstance(cd.get("clean"), dict) else None
|
|
2049
|
+
deg_avg = (cd.get("degraded") or {}).get("average_return_pct") if isinstance(cd.get("degraded"), dict) else None
|
|
2050
|
+
gap = cd.get("return_gap_pct")
|
|
2051
|
+
lines = [
|
|
2052
|
+
(
|
|
2053
|
+
"data_quality_review "
|
|
2054
|
+
f"runs={review.get('run_count', 0)} "
|
|
2055
|
+
f"clean={review.get('clean_run_count', 0)} "
|
|
2056
|
+
f"degraded={review.get('degraded_run_count', 0)} "
|
|
2057
|
+
f"snapshot_sources={review.get('snapshot_source_counts', {})} "
|
|
2058
|
+
f"daily_sources={review.get('daily_source_counts', {})} "
|
|
2059
|
+
f"daily_flags={review.get('daily_quality_flag_counts', {})} "
|
|
2060
|
+
f"reasons={review.get('degraded_reason_counts', {})} "
|
|
2061
|
+
f"clean_avg={clean_avg} degraded_avg={deg_avg} gap={gap}"
|
|
2062
|
+
)
|
|
2063
|
+
]
|
|
2064
|
+
for hint in review.get("hints", []) or []:
|
|
2065
|
+
lines.append(f" data_quality_hint: {hint}")
|
|
2066
|
+
return lines
|
|
2067
|
+
|
|
2068
|
+
|
|
2069
|
+
def _format_partial_benchmark(window: dict) -> str:
|
|
2070
|
+
"""When only some picks have benchmark data, bench/excess cover just
|
|
2071
|
+
those picks; show how many and their own average return."""
|
|
2072
|
+
evaluated = int(window.get("evaluated_pick_count") or 0)
|
|
2073
|
+
matched = int(window.get("benchmark_pick_count") or 0)
|
|
2074
|
+
if not evaluated or matched >= evaluated:
|
|
2075
|
+
return ""
|
|
2076
|
+
return f"bench_n={matched}/{evaluated} matched_ret={window.get('average_matched_return_pct')!s} "
|
|
2077
|
+
|
|
2078
|
+
|
|
2079
|
+
def _format_event_signal_review_explain(
|
|
2080
|
+
review: object,
|
|
2081
|
+
*,
|
|
2082
|
+
limit: int = 8,
|
|
2083
|
+
) -> list[str]:
|
|
2084
|
+
if not isinstance(review, dict) or not review:
|
|
2085
|
+
return []
|
|
2086
|
+
summary = review.get("summary", {})
|
|
2087
|
+
if not isinstance(summary, dict):
|
|
2088
|
+
summary = {}
|
|
2089
|
+
lines = [
|
|
2090
|
+
(
|
|
2091
|
+
"event_signal_review "
|
|
2092
|
+
f"signals={summary.get('signal_count', 0)} "
|
|
2093
|
+
f"occurrences={summary.get('signal_occurrence_count', 0)} "
|
|
2094
|
+
f"positive={summary.get('positive_signal_count', 0)} "
|
|
2095
|
+
f"negative={summary.get('negative_signal_count', 0)} "
|
|
2096
|
+
f"mixed={summary.get('mixed_signal_count', 0)} "
|
|
2097
|
+
f"patches={summary.get('patch_suggestion_count', 0)}"
|
|
2098
|
+
)
|
|
2099
|
+
]
|
|
2100
|
+
signals = review.get("signals", [])
|
|
2101
|
+
if isinstance(signals, list) and signals:
|
|
2102
|
+
lines.append("event_signals signal action picks avg_return win_rate failures codes")
|
|
2103
|
+
for item in signals[:limit]:
|
|
2104
|
+
if not isinstance(item, dict):
|
|
2105
|
+
continue
|
|
2106
|
+
codes = ",".join(str(value) for value in item.get("sample_codes", [])[:3]) or "-"
|
|
2107
|
+
lines.append(
|
|
2108
|
+
f"{str(item.get('signal') or ''):<28} {str(item.get('action') or ''):<16} "
|
|
2109
|
+
f"{item.get('pick_count')!s:<5} {item.get('average_return_pct')!s:<10} "
|
|
2110
|
+
f"{item.get('win_rate')!s:<8} {item.get('failure_count')!s:<8} {codes}"
|
|
2111
|
+
)
|
|
2112
|
+
patch_suggestions = review.get("strategy_patch_suggestions", [])
|
|
2113
|
+
if isinstance(patch_suggestions, list) and patch_suggestions:
|
|
2114
|
+
lines.append("event_signal_strategy_patches strategy prefer avoid evidence")
|
|
2115
|
+
for item in patch_suggestions[:limit]:
|
|
2116
|
+
if not isinstance(item, dict):
|
|
2117
|
+
continue
|
|
2118
|
+
preferred = ",".join(str(value) for value in item.get("preferred_event_tags", [])[:3])
|
|
2119
|
+
avoided = ",".join(str(value) for value in item.get("avoided_event_tags", [])[:3])
|
|
2120
|
+
evidence_items = item.get("evidence", [])
|
|
2121
|
+
if not isinstance(evidence_items, list):
|
|
2122
|
+
evidence_items = []
|
|
2123
|
+
evidence = ",".join(
|
|
2124
|
+
str(value.get("signal", ""))
|
|
2125
|
+
for value in evidence_items[:3]
|
|
2126
|
+
if isinstance(value, dict)
|
|
2127
|
+
)
|
|
2128
|
+
lines.append(
|
|
2129
|
+
f"{str(item.get('strategy') or ''):<20} "
|
|
2130
|
+
f"{preferred or '-':<28} {avoided or '-':<32} {evidence or '-'}"
|
|
2131
|
+
)
|
|
2132
|
+
recommendations = review.get("recommendations", [])
|
|
2133
|
+
if isinstance(recommendations, list) and recommendations:
|
|
2134
|
+
lines.append("event_signal_next_actions=" + " | ".join(str(item) for item in recommendations))
|
|
2135
|
+
return lines
|
|
2136
|
+
|
|
2137
|
+
|
|
2138
|
+
def _format_failure_review_explain(
|
|
2139
|
+
review: object,
|
|
2140
|
+
*,
|
|
2141
|
+
include_samples: bool = True,
|
|
2142
|
+
) -> list[str]:
|
|
2143
|
+
if not isinstance(review, dict) or not review:
|
|
2144
|
+
return []
|
|
2145
|
+
summary = review.get("summary", {})
|
|
2146
|
+
if not isinstance(summary, dict):
|
|
2147
|
+
summary = {}
|
|
2148
|
+
lines = [
|
|
2149
|
+
(
|
|
2150
|
+
"failure_review "
|
|
2151
|
+
f"failures={summary.get('failure_count', 0)} "
|
|
2152
|
+
f"shown={summary.get('shown_failure_count', 0)} "
|
|
2153
|
+
f"negative={summary.get('negative_pick_count', 0)} "
|
|
2154
|
+
f"missing={summary.get('missing_count', 0)} "
|
|
2155
|
+
f"failed_breakout={summary.get('failed_breakout_count', 0)} "
|
|
2156
|
+
f"severe_drawdown={summary.get('severe_drawdown_count', 0)} "
|
|
2157
|
+
f"worst_return={summary.get('worst_return_pct')}"
|
|
2158
|
+
)
|
|
2159
|
+
]
|
|
2160
|
+
dimensions = review.get("dimensions", {})
|
|
2161
|
+
if isinstance(dimensions, dict):
|
|
2162
|
+
for title, key in (
|
|
2163
|
+
("failure_strategies", "by_strategy"),
|
|
2164
|
+
("failure_reasons", "by_failure_reason"),
|
|
2165
|
+
("failure_event_signals", "by_event_signal"),
|
|
2166
|
+
("failure_llm_risks", "by_llm_risk"),
|
|
2167
|
+
("failure_risk_flags", "by_risk_flag"),
|
|
2168
|
+
("failure_shapes", "by_shape_status"),
|
|
2169
|
+
):
|
|
2170
|
+
items = _top_failure_dimension_items(dimensions.get(key, {}))
|
|
2171
|
+
if items:
|
|
2172
|
+
lines.append(f"{title}=" + " | ".join(items))
|
|
2173
|
+
if include_samples:
|
|
2174
|
+
samples = review.get("failure_samples", [])
|
|
2175
|
+
if isinstance(samples, list) and samples:
|
|
2176
|
+
lines.append("failure_samples run strategy rank code return status reasons")
|
|
2177
|
+
for item in samples:
|
|
2178
|
+
if not isinstance(item, dict):
|
|
2179
|
+
continue
|
|
2180
|
+
reason_values = item.get("failure_reasons", [])
|
|
2181
|
+
if not isinstance(reason_values, list):
|
|
2182
|
+
reason_values = []
|
|
2183
|
+
reasons = ",".join(str(value) for value in reason_values[:4]) or "-"
|
|
2184
|
+
ret = item.get("return_pct")
|
|
2185
|
+
ret_text = "-" if ret is None else f"{float(ret):.2f}%"
|
|
2186
|
+
lines.append(
|
|
2187
|
+
f"{str(item.get('run_id') or ''):<16} {str(item.get('strategy') or ''):<20} "
|
|
2188
|
+
f"{item.get('rank')!s:<4} {str(item.get('code') or ''):<8} "
|
|
2189
|
+
f"{ret_text:<8} {str(item.get('status') or ''):<10} {reasons}"
|
|
2190
|
+
)
|
|
2191
|
+
recommendations = review.get("recommendations", [])
|
|
2192
|
+
if isinstance(recommendations, list) and recommendations:
|
|
2193
|
+
lines.append("failure_next_actions=" + " | ".join(str(item) for item in recommendations))
|
|
2194
|
+
return lines
|
|
2195
|
+
|
|
2196
|
+
|
|
2197
|
+
def _format_hotspots_explain(hotspots: list, *, provider: str = "") -> str:
|
|
2198
|
+
provider_text = getattr(hotspots, "provider_used", "") or provider or "-"
|
|
2199
|
+
metadata_bits = [f"hotspots={len(hotspots)}", f"provider={provider_text}", "schema_version=2"]
|
|
2200
|
+
if getattr(hotspots, "fallback_used", False):
|
|
2201
|
+
metadata_bits.append("fallback=True")
|
|
2202
|
+
if getattr(hotspots, "stale", False):
|
|
2203
|
+
metadata_bits.append("stale=True")
|
|
2204
|
+
source_errors = getattr(hotspots, "source_errors", []) or []
|
|
2205
|
+
if source_errors:
|
|
2206
|
+
metadata_bits.append("source_errors=" + " | ".join(source_errors))
|
|
2207
|
+
if not hotspots:
|
|
2208
|
+
return " ".join(metadata_bits)
|
|
2209
|
+
lines = [
|
|
2210
|
+
" ".join(metadata_bits),
|
|
2211
|
+
"rank topic source src_rank change heat trend persistence cooling state stage sample quality leaders",
|
|
2212
|
+
]
|
|
2213
|
+
for idx, item in enumerate(hotspots, start=1):
|
|
2214
|
+
leaders = ",".join(item.leaders[:3]) if getattr(item, "leaders", None) else "-"
|
|
2215
|
+
lines.append(
|
|
2216
|
+
f"{idx:<4} {item.topic:<14} {item.source or '-':<8} "
|
|
2217
|
+
f"{item.rank if item.rank is not None else '-':<8} "
|
|
2218
|
+
f"{_fmt_pct(item.change_pct):<8} "
|
|
2219
|
+
f"{item.heat_score:<6.1f} "
|
|
2220
|
+
f"{_fmt_optional_float(item.trend_score):<8} "
|
|
2221
|
+
f"{_fmt_optional_float(item.persistence_score):<11} "
|
|
2222
|
+
f"{_fmt_optional_float(item.cooling_score):<7} "
|
|
2223
|
+
f"{item.state or '-':<14} {item.stage:<8} "
|
|
2224
|
+
f"{item.sample_stock_count:<6} {getattr(item, 'quality_status', '-') or '-':<8} {leaders}"
|
|
2225
|
+
)
|
|
2226
|
+
return "\n".join(lines)
|
|
2227
|
+
|
|
2228
|
+
|
|
2229
|
+
def _format_hotspot_detail_explain(detail) -> str:
|
|
2230
|
+
summary = detail.summary
|
|
2231
|
+
leaders = ",".join(summary.leaders[:3]) if summary.leaders else "-"
|
|
2232
|
+
lines = [
|
|
2233
|
+
(
|
|
2234
|
+
f"topic={summary.topic} source={summary.source or '-'} "
|
|
2235
|
+
f"canonical={getattr(summary, 'canonical_topic', '') or '-'} "
|
|
2236
|
+
f"src_rank={summary.rank if summary.rank is not None else '-'} "
|
|
2237
|
+
f"change={_fmt_pct(summary.change_pct)} heat={summary.heat_score:.1f} "
|
|
2238
|
+
f"trend={_fmt_optional_float(summary.trend_score)} "
|
|
2239
|
+
f"persistence={_fmt_optional_float(summary.persistence_score)} "
|
|
2240
|
+
f"cooling={_fmt_optional_float(summary.cooling_score)} "
|
|
2241
|
+
f"state={summary.state or '-'} stage={summary.stage} "
|
|
2242
|
+
f"sample={summary.sample_stock_count} leaders={leaders} "
|
|
2243
|
+
f"quality={getattr(summary, 'quality_status', '-') or '-'} "
|
|
2244
|
+
f"provider={summary.provider_used or '-'} fallback={summary.fallback_used}"
|
|
2245
|
+
),
|
|
2246
|
+
"rank code name role score change amount turnover volume_ratio net_inflow active evidence",
|
|
2247
|
+
]
|
|
2248
|
+
missing_fields = getattr(summary, "missing_fields", []) or []
|
|
2249
|
+
if missing_fields:
|
|
2250
|
+
lines.append("missing_fields=" + ",".join(missing_fields))
|
|
2251
|
+
if summary.source_errors:
|
|
2252
|
+
lines.append("source_errors=" + " | ".join(summary.source_errors))
|
|
2253
|
+
for idx, stock in enumerate(detail.stocks, start=1):
|
|
2254
|
+
lines.append(
|
|
2255
|
+
f"{idx:<4} {stock.code:<8} {stock.name:<10} {stock.role or '-':<8} "
|
|
2256
|
+
f"{stock.hot_stock_score:<6.1f} {_fmt_pct(stock.change_pct):<8} "
|
|
2257
|
+
f"{_fmt_optional_float(stock.amount):<10} "
|
|
2258
|
+
f"{_fmt_optional_float(stock.turnover_rate):<8} "
|
|
2259
|
+
f"{_fmt_optional_float(stock.volume_ratio):<12} "
|
|
2260
|
+
f"{_fmt_optional_float(stock.net_inflow):<10} "
|
|
2261
|
+
f"{stock.active_days:<6} {stock.evidence_count}"
|
|
2262
|
+
)
|
|
2263
|
+
if detail.timeline:
|
|
2264
|
+
lines.append("timeline date source type impact title codes")
|
|
2265
|
+
for event in detail.timeline:
|
|
2266
|
+
codes = ",".join(event.related_codes) if event.related_codes else "-"
|
|
2267
|
+
lines.append(
|
|
2268
|
+
f"{event.date:<12} {event.source:<8} {event.event_type:<10} "
|
|
2269
|
+
f"{event.impact_score:<6.1f} {event.title[:40]} {codes}"
|
|
2270
|
+
)
|
|
2271
|
+
if getattr(detail, "route", None):
|
|
2272
|
+
lines.append("route date source type impact title description")
|
|
2273
|
+
for item in detail.route:
|
|
2274
|
+
lines.append(
|
|
2275
|
+
f"{item.date:<12} {item.source:<8} {item.event_type:<10} "
|
|
2276
|
+
f"{item.impact_score:<6.1f} {item.title[:32]} {item.description[:80]}"
|
|
2277
|
+
)
|
|
2278
|
+
return "\n".join(lines)
|
|
2279
|
+
|
|
2280
|
+
|
|
2281
|
+
def _top_dimension_items(items: dict, *, limit: int = 5) -> list[str]:
|
|
2282
|
+
ranked = sorted(
|
|
2283
|
+
items.items(),
|
|
2284
|
+
key=lambda item: (
|
|
2285
|
+
item[1].get("pick_count") or 0,
|
|
2286
|
+
item[1].get("average_return_pct") or -999999,
|
|
2287
|
+
),
|
|
2288
|
+
reverse=True,
|
|
2289
|
+
)
|
|
2290
|
+
return [
|
|
2291
|
+
(
|
|
2292
|
+
f"{label}:n={stats.get('pick_count')},"
|
|
2293
|
+
f"avg={stats.get('average_return_pct')},win={stats.get('win_rate')}"
|
|
2294
|
+
)
|
|
2295
|
+
for label, stats in ranked[:limit]
|
|
2296
|
+
]
|
|
2297
|
+
|
|
2298
|
+
|
|
2299
|
+
def _top_failure_dimension_items(items: object, *, limit: int = 5) -> list[str]:
|
|
2300
|
+
if not isinstance(items, dict):
|
|
2301
|
+
return []
|
|
2302
|
+
ranked = sorted(
|
|
2303
|
+
(
|
|
2304
|
+
(str(label), stats)
|
|
2305
|
+
for label, stats in items.items()
|
|
2306
|
+
if isinstance(stats, dict)
|
|
2307
|
+
),
|
|
2308
|
+
key=lambda item: (
|
|
2309
|
+
-int(item[1].get("failure_count", 0) or 0),
|
|
2310
|
+
item[1].get("worst_return_pct") is None,
|
|
2311
|
+
float(item[1].get("worst_return_pct") or 0),
|
|
2312
|
+
item[0],
|
|
2313
|
+
),
|
|
2314
|
+
)
|
|
2315
|
+
return [
|
|
2316
|
+
(
|
|
2317
|
+
f"{label}:n={stats.get('failure_count')},"
|
|
2318
|
+
f"avg={stats.get('average_return_pct')},worst={stats.get('worst_return_pct')}"
|
|
2319
|
+
)
|
|
2320
|
+
for label, stats in ranked[:limit]
|
|
2321
|
+
]
|
|
2322
|
+
|
|
2323
|
+
|
|
2324
|
+
def _fmt_pct(value: float | None) -> str:
|
|
2325
|
+
return "-" if value is None else f"{float(value):.2f}%"
|
|
2326
|
+
|
|
2327
|
+
|
|
2328
|
+
def _fmt_optional_float(value: float | None) -> str:
|
|
2329
|
+
return "-" if value is None else f"{float(value):.2f}"
|
|
2330
|
+
|
|
2331
|
+
|
|
2332
|
+
def _format_audit_explain(result: dict) -> str:
|
|
2333
|
+
profile = result.get("profile_coverage", {})
|
|
2334
|
+
lines = [
|
|
2335
|
+
f"project={result.get('project')} positioning={result.get('positioning')}",
|
|
2336
|
+
f"strategies={result.get('strategy_count')} categories={result.get('categories')}",
|
|
2337
|
+
"profile_coverage="
|
|
2338
|
+
+ ", ".join(
|
|
2339
|
+
f"{name}:{item.get('configured')}/{result.get('strategy_count')}"
|
|
2340
|
+
for name, item in profile.items()
|
|
2341
|
+
),
|
|
2342
|
+
]
|
|
2343
|
+
lines.append("strengths:")
|
|
2344
|
+
for item in result.get("strengths", []):
|
|
2345
|
+
lines.append(f"- [{item.get('area')}] {item.get('message')}")
|
|
2346
|
+
|
|
2347
|
+
findings = result.get("strategy_findings", [])
|
|
2348
|
+
if findings:
|
|
2349
|
+
lines.append("strategy_findings:")
|
|
2350
|
+
for item in findings:
|
|
2351
|
+
lines.append(
|
|
2352
|
+
f"- [{item.get('severity')}] {item.get('strategy')} "
|
|
2353
|
+
f"{item.get('area')}: {item.get('message')} "
|
|
2354
|
+
f"next={item.get('recommendation')}"
|
|
2355
|
+
)
|
|
2356
|
+
|
|
2357
|
+
lines.append("project_gaps:")
|
|
2358
|
+
for item in result.get("project_gaps", []):
|
|
2359
|
+
lines.append(
|
|
2360
|
+
f"- [{item.get('severity')}] {item.get('area')}: "
|
|
2361
|
+
f"{item.get('message')} next={item.get('recommendation')}"
|
|
2362
|
+
)
|
|
2363
|
+
|
|
2364
|
+
lines.append("next_priorities:")
|
|
2365
|
+
for item in result.get("next_priorities", []):
|
|
2366
|
+
lines.append(f"- {item}")
|
|
2367
|
+
return "\n".join(lines)
|
|
2368
|
+
|
|
2369
|
+
|
|
2370
|
+
def _format_data_sources_doctor_explain(result: dict) -> str:
|
|
2371
|
+
snapshot = result.get("snapshot", {}) or {}
|
|
2372
|
+
daily = result.get("daily", {}) or {}
|
|
2373
|
+
config = result.get("config", {}) or {}
|
|
2374
|
+
lines = [
|
|
2375
|
+
f"status={result.get('status')} generated_at={result.get('generated_at')}",
|
|
2376
|
+
(
|
|
2377
|
+
"snapshot "
|
|
2378
|
+
f"status={snapshot.get('status')} source={snapshot.get('source') or '-'} "
|
|
2379
|
+
f"rows={snapshot.get('rows', 0)} fallback={snapshot.get('fallback_used')} "
|
|
2380
|
+
f"stale={snapshot.get('stale')} sources={','.join(snapshot.get('sources') or [])}"
|
|
2381
|
+
),
|
|
2382
|
+
]
|
|
2383
|
+
strategy = result.get("strategy_requirements") or {}
|
|
2384
|
+
if strategy:
|
|
2385
|
+
if strategy.get("mode") == "all":
|
|
2386
|
+
lines.append(
|
|
2387
|
+
f"strategy_scope=all count={strategy.get('strategy_count')} "
|
|
2388
|
+
f"daily_required_count={strategy.get('daily_strategy_count')} "
|
|
2389
|
+
f"data={','.join(strategy.get('data_requirements') or [])}"
|
|
2390
|
+
)
|
|
2391
|
+
else:
|
|
2392
|
+
lines.append(
|
|
2393
|
+
f"strategy={strategy.get('strategy')} category={strategy.get('category')} "
|
|
2394
|
+
f"data={','.join(strategy.get('data_requirements') or [])} "
|
|
2395
|
+
f"daily_required={strategy.get('requires_daily_features')}"
|
|
2396
|
+
)
|
|
2397
|
+
if snapshot.get("required_fields"):
|
|
2398
|
+
lines.append("snapshot_required=" + ",".join(str(item) for item in snapshot.get("required_fields") or []))
|
|
2399
|
+
if snapshot.get("missing_fields"):
|
|
2400
|
+
lines.append("snapshot_missing=" + ",".join(str(item) for item in snapshot.get("missing_fields") or []))
|
|
2401
|
+
if snapshot.get("errors"):
|
|
2402
|
+
lines.append("snapshot_errors=" + " | ".join(str(item) for item in snapshot.get("errors") or []))
|
|
2403
|
+
quality = snapshot.get("quality_summary") or {}
|
|
2404
|
+
if quality:
|
|
2405
|
+
anomalies = ",".join(str(item) for item in (quality.get("anomalies") or [])[:6]) or "-"
|
|
2406
|
+
lines.append(
|
|
2407
|
+
f"snapshot_quality status={quality.get('status')} "
|
|
2408
|
+
f"anomalies={anomalies}"
|
|
2409
|
+
)
|
|
2410
|
+
health_summary = result.get("health_summary") or {}
|
|
2411
|
+
snapshot_health = health_summary.get("snapshot") or {}
|
|
2412
|
+
if snapshot_health:
|
|
2413
|
+
lines.append(_format_source_health_summary("snapshot_health", snapshot_health))
|
|
2414
|
+
freshness = result.get("freshness_summary") or {}
|
|
2415
|
+
if freshness:
|
|
2416
|
+
lines.append(_format_freshness_summary(freshness))
|
|
2417
|
+
readiness = result.get("strategy_readiness_summary") or {}
|
|
2418
|
+
if readiness:
|
|
2419
|
+
lines.append(_format_strategy_readiness_summary(readiness))
|
|
2420
|
+
reconciliation = result.get("snapshot_reconciliation") or {}
|
|
2421
|
+
if reconciliation:
|
|
2422
|
+
lines.extend(_format_snapshot_reconciliation_explain(reconciliation))
|
|
2423
|
+
if daily:
|
|
2424
|
+
lines.append(
|
|
2425
|
+
"daily "
|
|
2426
|
+
f"status={daily.get('status')} source={daily.get('source') or '-'} "
|
|
2427
|
+
f"rows={daily.get('rows', 0)} stale={daily.get('stale')} "
|
|
2428
|
+
f"code={config.get('daily_code') or '-'} requested={config.get('daily_source') or '-'}"
|
|
2429
|
+
)
|
|
2430
|
+
if daily.get("required_fields"):
|
|
2431
|
+
lines.append("daily_required=" + ",".join(str(item) for item in daily.get("required_fields") or []))
|
|
2432
|
+
if daily.get("missing_fields"):
|
|
2433
|
+
lines.append("daily_missing=" + ",".join(str(item) for item in daily.get("missing_fields") or []))
|
|
2434
|
+
if daily.get("errors"):
|
|
2435
|
+
lines.append("daily_errors=" + " | ".join(str(item) for item in daily.get("errors") or []))
|
|
2436
|
+
daily_health = health_summary.get("daily") or {}
|
|
2437
|
+
if daily_health:
|
|
2438
|
+
lines.append(_format_source_health_summary("daily_health", daily_health))
|
|
2439
|
+
lines.append(f"tushare_configured={config.get('tushare_configured')} live_checks={config.get('live_checks')}")
|
|
2440
|
+
recommendations = result.get("recommendations") or []
|
|
2441
|
+
if recommendations:
|
|
2442
|
+
lines.append("recommendations=" + " | ".join(str(item) for item in recommendations))
|
|
2443
|
+
coverage = result.get("strategy_coverage") or []
|
|
2444
|
+
if coverage:
|
|
2445
|
+
lines.append("strategy_coverage:")
|
|
2446
|
+
for item in coverage:
|
|
2447
|
+
parts = [
|
|
2448
|
+
f"- {item.get('strategy')} status={item.get('status')}",
|
|
2449
|
+
f"category={item.get('category')}",
|
|
2450
|
+
f"data={','.join(item.get('data_requirements') or [])}",
|
|
2451
|
+
f"snapshot_fields={len(item.get('required_snapshot_fields') or [])}",
|
|
2452
|
+
f"daily_fields={len(item.get('required_daily_fields') or [])}",
|
|
2453
|
+
]
|
|
2454
|
+
if item.get("snapshot_missing_fields"):
|
|
2455
|
+
parts.append("snapshot_missing=" + ",".join(item.get("snapshot_missing_fields") or []))
|
|
2456
|
+
if item.get("daily_missing_fields"):
|
|
2457
|
+
parts.append("daily_missing=" + ",".join(item.get("daily_missing_fields") or []))
|
|
2458
|
+
lines.append(" ".join(parts))
|
|
2459
|
+
return "\n".join(lines)
|
|
2460
|
+
|
|
2461
|
+
|
|
2462
|
+
def _format_strategy_readiness_summary(summary: dict) -> str:
|
|
2463
|
+
return (
|
|
2464
|
+
"strategy_readiness "
|
|
2465
|
+
f"ready={summary.get('ready_strategy_count', 0)} "
|
|
2466
|
+
f"attention={summary.get('attention_strategy_count', 0)} "
|
|
2467
|
+
f"unchecked={summary.get('unchecked_strategy_count', 0)} "
|
|
2468
|
+
f"daily_required={summary.get('daily_strategy_count', 0)}"
|
|
2469
|
+
)
|
|
2470
|
+
|
|
2471
|
+
|
|
2472
|
+
def _format_source_health_summary(label: str, summary: dict) -> str:
|
|
2473
|
+
return (
|
|
2474
|
+
f"{label} "
|
|
2475
|
+
f"available={summary.get('available_source_count', 0)} "
|
|
2476
|
+
f"healthy={_join_or_dash(summary.get('healthy_sources') or [])} "
|
|
2477
|
+
f"failing={_join_or_dash(summary.get('failing_sources') or [])} "
|
|
2478
|
+
f"disabled={_join_or_dash(summary.get('disabled_sources') or [])} "
|
|
2479
|
+
f"never_seen={_join_or_dash(summary.get('never_seen_sources') or [])} "
|
|
2480
|
+
f"errors={summary.get('error_count', 0)}"
|
|
2481
|
+
)
|
|
2482
|
+
|
|
2483
|
+
|
|
2484
|
+
def _format_snapshot_reconciliation_explain(reconciliation: dict) -> list[str]:
|
|
2485
|
+
summary = reconciliation.get("summary", {}) or {}
|
|
2486
|
+
lines = [
|
|
2487
|
+
(
|
|
2488
|
+
"snapshot_reconciliation "
|
|
2489
|
+
f"status={reconciliation.get('status')} "
|
|
2490
|
+
f"baseline={reconciliation.get('baseline_source') or '-'} "
|
|
2491
|
+
f"sources={summary.get('source_count', 0)} "
|
|
2492
|
+
f"ok={summary.get('ok_source_count', 0)} "
|
|
2493
|
+
f"degraded={summary.get('degraded_source_count', 0)} "
|
|
2494
|
+
f"failed={summary.get('failed_source_count', 0)}"
|
|
2495
|
+
)
|
|
2496
|
+
]
|
|
2497
|
+
sources = reconciliation.get("sources", []) or []
|
|
2498
|
+
if sources:
|
|
2499
|
+
lines.append("snapshot_sources source status rows overlap missing quality errors")
|
|
2500
|
+
for item in sources:
|
|
2501
|
+
missing = _join_or_dash(item.get("missing_fields") or [])
|
|
2502
|
+
errors = _join_or_dash(item.get("errors") or [])
|
|
2503
|
+
overlap = item.get("overlap_with_baseline_ratio")
|
|
2504
|
+
overlap_text = "-" if overlap is None else f"{float(overlap):.2f}"
|
|
2505
|
+
lines.append(
|
|
2506
|
+
f"{str(item.get('source') or ''):<16} {str(item.get('status') or ''):<9} "
|
|
2507
|
+
f"{item.get('rows', 0)!s:<6} {overlap_text:<7} "
|
|
2508
|
+
f"{missing:<24} {str(item.get('quality_status') or '-'):<8} {errors}"
|
|
2509
|
+
)
|
|
2510
|
+
warnings = summary.get("warnings", []) or []
|
|
2511
|
+
if warnings:
|
|
2512
|
+
lines.append("snapshot_reconciliation_warnings=" + " | ".join(str(item) for item in warnings))
|
|
2513
|
+
return lines
|
|
2514
|
+
|
|
2515
|
+
|
|
2516
|
+
def _format_freshness_summary(summary: dict) -> str:
|
|
2517
|
+
snapshot = summary.get("snapshot", {}) or {}
|
|
2518
|
+
daily = summary.get("daily", {}) or {}
|
|
2519
|
+
warnings = summary.get("warnings", []) or []
|
|
2520
|
+
return (
|
|
2521
|
+
"freshness "
|
|
2522
|
+
f"fresh_enough={summary.get('fresh_enough')} "
|
|
2523
|
+
f"snapshot={snapshot.get('data_state', '-')}:{snapshot.get('cache_state', '-')} "
|
|
2524
|
+
f"daily={daily.get('data_state', '-')}:{daily.get('cache_state', '-')} "
|
|
2525
|
+
f"fallbacks={summary.get('fallback_family_count', 0)} "
|
|
2526
|
+
f"stale={summary.get('stale_family_count', 0)} "
|
|
2527
|
+
f"unchecked={summary.get('not_checked_family_count', 0)} "
|
|
2528
|
+
f"warnings={_join_or_dash(warnings)}"
|
|
2529
|
+
)
|
|
2530
|
+
|
|
2531
|
+
|
|
2532
|
+
def _join_or_dash(values: list[str]) -> str:
|
|
2533
|
+
return ",".join(str(item) for item in values) if values else "-"
|
|
2534
|
+
|
|
2535
|
+
|
|
2536
|
+
def _format_dsa_readiness_explain(result: dict) -> str:
|
|
2537
|
+
return "\n".join([
|
|
2538
|
+
(
|
|
2539
|
+
f"dsa status={result.get('status')} available={result.get('available')} "
|
|
2540
|
+
f"endpoint={result.get('endpoint') or '-'} http_status={result.get('http_status')}"
|
|
2541
|
+
),
|
|
2542
|
+
f"error={result.get('error') or '-'}",
|
|
2543
|
+
])
|
|
2544
|
+
|
|
2545
|
+
|
|
2546
|
+
def _write_industry_cache_metadata(
|
|
2547
|
+
output_path: Path,
|
|
2548
|
+
*,
|
|
2549
|
+
provider: str,
|
|
2550
|
+
max_boards: int,
|
|
2551
|
+
rows: int,
|
|
2552
|
+
notes: list[str],
|
|
2553
|
+
generated_at: str | None = None,
|
|
2554
|
+
history_path: Path | None = None,
|
|
2555
|
+
) -> Path:
|
|
2556
|
+
metadata_path = output_path.with_suffix(output_path.suffix + ".meta.json")
|
|
2557
|
+
metadata = {
|
|
2558
|
+
"generated_at": generated_at or datetime.now().isoformat(),
|
|
2559
|
+
"provider": provider,
|
|
2560
|
+
"max_boards": max_boards,
|
|
2561
|
+
"rows": rows,
|
|
2562
|
+
"history_path": str(history_path) if history_path is not None else "",
|
|
2563
|
+
"notes": notes,
|
|
2564
|
+
}
|
|
2565
|
+
metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
2566
|
+
return metadata_path
|
|
2567
|
+
|
|
2568
|
+
|
|
2569
|
+
def _write_hotspot_cache_metadata(
|
|
2570
|
+
output_path: Path,
|
|
2571
|
+
*,
|
|
2572
|
+
provider: str,
|
|
2573
|
+
max_boards: int,
|
|
2574
|
+
rows: int,
|
|
2575
|
+
generated_at: str | None = None,
|
|
2576
|
+
history_path: Path | None = None,
|
|
2577
|
+
fallback_used: bool = False,
|
|
2578
|
+
source_errors: list[str] | None = None,
|
|
2579
|
+
history_appended: bool = True,
|
|
2580
|
+
) -> Path:
|
|
2581
|
+
metadata_path = output_path.with_suffix(output_path.suffix + ".meta.json")
|
|
2582
|
+
metadata = {
|
|
2583
|
+
"generated_at": generated_at or datetime.now().isoformat(),
|
|
2584
|
+
"schema_version": 2,
|
|
2585
|
+
"provider": provider,
|
|
2586
|
+
"max_boards": max_boards,
|
|
2587
|
+
"rows": rows,
|
|
2588
|
+
"history_path": str(history_path) if history_path is not None else "",
|
|
2589
|
+
"fallback_used": fallback_used,
|
|
2590
|
+
"source_errors": source_errors or [],
|
|
2591
|
+
"history_appended": history_appended,
|
|
2592
|
+
}
|
|
2593
|
+
metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
2594
|
+
return metadata_path
|
|
2595
|
+
|
|
2596
|
+
|
|
2597
|
+
def _append_industry_cache_history(
|
|
2598
|
+
output_path: Path,
|
|
2599
|
+
*,
|
|
2600
|
+
mapping: dict[str, dict[str, object]],
|
|
2601
|
+
generated_at: str,
|
|
2602
|
+
) -> Path:
|
|
2603
|
+
history_path = output_path.with_suffix(output_path.suffix + ".history.jsonl")
|
|
2604
|
+
history_path.parent.mkdir(parents=True, exist_ok=True)
|
|
2605
|
+
records = _industry_cache_history_records(mapping, generated_at=generated_at)
|
|
2606
|
+
if records:
|
|
2607
|
+
with history_path.open("a", encoding="utf-8") as handle:
|
|
2608
|
+
for record in records:
|
|
2609
|
+
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
2610
|
+
else:
|
|
2611
|
+
history_path.touch()
|
|
2612
|
+
return history_path
|
|
2613
|
+
|
|
2614
|
+
|
|
2615
|
+
def _industry_cache_history_records(
|
|
2616
|
+
mapping: dict[str, dict[str, object]],
|
|
2617
|
+
*,
|
|
2618
|
+
generated_at: str,
|
|
2619
|
+
) -> list[dict[str, object]]:
|
|
2620
|
+
grouped: dict[str, dict[str, object]] = {}
|
|
2621
|
+
for code, item in mapping.items():
|
|
2622
|
+
summaries = _split_board_heat_summary(item.get("board_heat_summary", ""))
|
|
2623
|
+
heat_score = _safe_float(item.get("board_heat_score"))
|
|
2624
|
+
for summary in summaries:
|
|
2625
|
+
board = summary.split(":", 1)[0].strip()
|
|
2626
|
+
if not board:
|
|
2627
|
+
continue
|
|
2628
|
+
record = grouped.setdefault(summary, {
|
|
2629
|
+
"generated_at": generated_at,
|
|
2630
|
+
"board": board,
|
|
2631
|
+
"summary": summary,
|
|
2632
|
+
"code_count": 0,
|
|
2633
|
+
"max_board_heat_score": None,
|
|
2634
|
+
"sample_codes": [],
|
|
2635
|
+
})
|
|
2636
|
+
record["code_count"] = int(record["code_count"]) + 1
|
|
2637
|
+
current_heat = _safe_float(record.get("max_board_heat_score"))
|
|
2638
|
+
if heat_score is not None and (current_heat is None or heat_score > current_heat):
|
|
2639
|
+
record["max_board_heat_score"] = heat_score
|
|
2640
|
+
sample_codes = record["sample_codes"]
|
|
2641
|
+
if isinstance(sample_codes, list) and len(sample_codes) < 20:
|
|
2642
|
+
sample_codes.append(code)
|
|
2643
|
+
return sorted(grouped.values(), key=lambda item: str(item.get("summary", "")))
|
|
2644
|
+
|
|
2645
|
+
|
|
2646
|
+
def _split_board_heat_summary(value: object) -> list[str]:
|
|
2647
|
+
summaries = []
|
|
2648
|
+
for item in str(value or "").split("|"):
|
|
2649
|
+
summary = item.strip()
|
|
2650
|
+
if summary and summary.lower() not in {"nan", "none", "<na>"}:
|
|
2651
|
+
summaries.append(summary)
|
|
2652
|
+
return summaries
|
|
2653
|
+
|
|
2654
|
+
|
|
2655
|
+
def _safe_float(value: object) -> float | None:
|
|
2656
|
+
if value is None:
|
|
2657
|
+
return None
|
|
2658
|
+
text = str(value).strip().replace("%", "").replace(",", "")
|
|
2659
|
+
if not text or text.lower() in {"nan", "none", "<na>"}:
|
|
2660
|
+
return None
|
|
2661
|
+
try:
|
|
2662
|
+
return float(text)
|
|
2663
|
+
except (TypeError, ValueError):
|
|
2664
|
+
return None
|
|
2665
|
+
|
|
2666
|
+
|
|
2667
|
+
def _apply_env_file_args(env_files: list[str] | None) -> None:
|
|
2668
|
+
if not env_files:
|
|
2669
|
+
return
|
|
2670
|
+
existing = os.environ.get("ALPHASIFT_ENV_FILES", "")
|
|
2671
|
+
items = [item for item in existing.split(os.pathsep) if item]
|
|
2672
|
+
items.extend(env_files)
|
|
2673
|
+
os.environ["ALPHASIFT_ENV_FILES"] = os.pathsep.join(items)
|
|
2674
|
+
|
|
2675
|
+
|
|
2676
|
+
def _parse_window_list(raw: str | None) -> list[int] | None:
|
|
2677
|
+
if raw is None:
|
|
2678
|
+
return None
|
|
2679
|
+
values: list[int] = []
|
|
2680
|
+
seen: set[int] = set()
|
|
2681
|
+
for item in str(raw).split(","):
|
|
2682
|
+
token = item.strip()
|
|
2683
|
+
if not token:
|
|
2684
|
+
continue
|
|
2685
|
+
try:
|
|
2686
|
+
value = int(token)
|
|
2687
|
+
except ValueError as exc:
|
|
2688
|
+
raise ValueError(f"Invalid --window value: {token}") from exc
|
|
2689
|
+
if value <= 0:
|
|
2690
|
+
raise ValueError("--window values must be positive integers")
|
|
2691
|
+
if value in seen:
|
|
2692
|
+
continue
|
|
2693
|
+
seen.add(value)
|
|
2694
|
+
values.append(value)
|
|
2695
|
+
return sorted(values)
|
|
2696
|
+
|
|
2697
|
+
|
|
2698
|
+
def _split_csv_args(values: list[str] | None) -> list[str] | None:
|
|
2699
|
+
if values is None:
|
|
2700
|
+
return None
|
|
2701
|
+
result = []
|
|
2702
|
+
for value in values:
|
|
2703
|
+
result.extend(item.strip() for item in value.split(",") if item.strip())
|
|
2704
|
+
return result
|
|
2705
|
+
|
|
2706
|
+
|
|
2707
|
+
def _format_market_stats_explain(items: list) -> str:
|
|
2708
|
+
lines = ["date stage up% lu brk seal% ld maxLB prevLU% amt_yi"]
|
|
2709
|
+
for item in items:
|
|
2710
|
+
seal = "-" if item.seal_rate_pct is None else f"{item.seal_rate_pct:5.1f}"
|
|
2711
|
+
prev_ret = "-" if item.prev_limit_up_avg_return_pct is None else f"{item.prev_limit_up_avg_return_pct:+6.2f}"
|
|
2712
|
+
amt = "-" if item.total_amount_yi is None else f"{item.total_amount_yi:8.1f}"
|
|
2713
|
+
stage_disp = f"{item.regime_stage}({item.regime_stage_label})"
|
|
2714
|
+
lines.append(
|
|
2715
|
+
f"{item.trade_date} {stage_disp:<11} {item.advance_ratio_pct:5.1f} "
|
|
2716
|
+
f"{item.non_st_limit_up_count:4d} {item.non_st_broken_board_count:4d} {seal:>6} "
|
|
2717
|
+
f"{item.non_st_limit_down_count:4d} {item.max_consecutive_limit_up:6d} {prev_ret:>8} {amt:>8}"
|
|
2718
|
+
)
|
|
2719
|
+
if items:
|
|
2720
|
+
last = items[-1]
|
|
2721
|
+
ladder = ", ".join(f"{k}板:{v}" for k, v in last.consecutive_board_ladder.items()) or "无"
|
|
2722
|
+
lines.append(f"ladder={ladder} reasons={'; '.join(last.regime_reasons)} policy={last.usage_policy}")
|
|
2723
|
+
return "\n".join(lines)
|
|
2724
|
+
|
|
2725
|
+
|
|
2726
|
+
def _format_pattern_scan_explain(scan_result, *, limit: int = 20) -> str:
|
|
2727
|
+
reg = scan_result.market_regime
|
|
2728
|
+
lines = [
|
|
2729
|
+
f"trade_date={scan_result.trade_date} universe={scan_result.universe_count} "
|
|
2730
|
+
f"regime={reg.regime_stage}({reg.regime_stage_label}) lu={reg.non_st_limit_up_count} "
|
|
2731
|
+
f"ld={reg.non_st_limit_down_count} policy={scan_result.usage_policy}"
|
|
2732
|
+
]
|
|
2733
|
+
for pattern_name in scan_result.patterns_evaluated:
|
|
2734
|
+
items = scan_result.signals_by_pattern.get(pattern_name, [])
|
|
2735
|
+
lines.append(f"[{pattern_name}] hits={len(items)}")
|
|
2736
|
+
for sig in items[: max(1, int(limit))]:
|
|
2737
|
+
obs = f" obs={sig.observe_date}(-{sig.observe_lag_days}d)" if sig.observe_date else ""
|
|
2738
|
+
ov = f"{sig.overhead_supply_10pct:.1f}%" if sig.overhead_supply_10pct is not None else "-"
|
|
2739
|
+
amt_m = f"{sig.proxy_amount / 1e8:.2f}亿" if sig.proxy_amount is not None else "-"
|
|
2740
|
+
lines.append(
|
|
2741
|
+
f" {sig.code} {sig.name or '-':<8} {sig.industry or '-':<8} "
|
|
2742
|
+
f"chg={sig.change_pct:+5.2f}% amt={amt_m:<7} ov10={ov}{obs}"
|
|
2743
|
+
)
|
|
2744
|
+
return "\n".join(lines)
|
|
2745
|
+
|
|
2746
|
+
|
|
2747
|
+
def _load_daily_report_runs(
|
|
2748
|
+
config: Config,
|
|
2749
|
+
*,
|
|
2750
|
+
run_refs: list[str] | None,
|
|
2751
|
+
runs_dir: Path | None,
|
|
2752
|
+
trade_date: str,
|
|
2753
|
+
) -> list:
|
|
2754
|
+
from alphasift.daily_report import load_daily_report_runs
|
|
2755
|
+
|
|
2756
|
+
return load_daily_report_runs(
|
|
2757
|
+
config,
|
|
2758
|
+
run_refs=run_refs,
|
|
2759
|
+
runs_dir=runs_dir,
|
|
2760
|
+
trade_date=trade_date,
|
|
2761
|
+
)
|
|
2762
|
+
|
|
2763
|
+
|
|
2764
|
+
def _format_radar_doctor_explain(payload: dict) -> str:
|
|
2765
|
+
pk = payload.get("pack") or {}
|
|
2766
|
+
pt = payload.get("patterns") or {}
|
|
2767
|
+
nt = payload.get("notify") or {}
|
|
2768
|
+
llm = payload.get("llm") or {}
|
|
2769
|
+
lines = [
|
|
2770
|
+
f"radar_doctor status={payload.get('status')} pack_valid={pk.get('valid')} "
|
|
2771
|
+
f"pack_date={pk.get('trade_date')} expected={pk.get('expected_trade_date')} fresh={pk.get('fresh')}",
|
|
2772
|
+
f"patterns total={pt.get('total')} active={pt.get('active_count')} "
|
|
2773
|
+
f"experimental={pt.get('experimental_count')} sync_ok={pt.get('mirror_sync_ok')}",
|
|
2774
|
+
f"notify channels={','.join(nt.get('configured_channels') or []) or 'none'} "
|
|
2775
|
+
f"llm={llm.get('ai_track_mode')}",
|
|
2776
|
+
]
|
|
2777
|
+
for rec in payload.get("recommendations") or []:
|
|
2778
|
+
lines.append(f" recommendation: {rec}")
|
|
2779
|
+
return "\n".join(lines)
|
|
2780
|
+
|
|
2781
|
+
|
|
2782
|
+
def _format_daily_report_explain(report: dict) -> str:
|
|
2783
|
+
lines = [
|
|
2784
|
+
report.get("im_card_markdown", ""),
|
|
2785
|
+
f"--- im_card_chars={report.get('im_card_chars')} schema=DailyReport v{report.get('schema_version')}",
|
|
2786
|
+
]
|
|
2787
|
+
push = report.get("push")
|
|
2788
|
+
if isinstance(push, dict):
|
|
2789
|
+
lines.append(
|
|
2790
|
+
f"push status={push.get('status')} sent={push.get('sent')} "
|
|
2791
|
+
f"skipped={len(push.get('skipped') or [])} errors={len(push.get('errors') or [])}"
|
|
2792
|
+
)
|
|
2793
|
+
return "\n".join(lines)
|
|
2794
|
+
|
|
2795
|
+
|
|
2796
|
+
if __name__ == "__main__":
|
|
2797
|
+
main()
|