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/server.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Read-only HTTP API surface for UI and agent integrations."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import base64
|
|
7
|
+
import hashlib
|
|
8
|
+
import html
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import asdict
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import parse_qs, urlparse
|
|
16
|
+
|
|
17
|
+
from alphasift.config import Config
|
|
18
|
+
from alphasift.daily_report import build_daily_report, load_daily_report_runs
|
|
19
|
+
from alphasift.daily_report_html import _safe_detail_url, render_daily_report_html
|
|
20
|
+
from alphasift.doctor import doctor_data_sources, doctor_radar_readiness
|
|
21
|
+
from alphasift.market_regime import compute_market_regime, compute_market_regime_series
|
|
22
|
+
from alphasift.overview import build_overview
|
|
23
|
+
from alphasift.pack import PackError, load_pack, pack_dir
|
|
24
|
+
from alphasift.patterns import extract_mini_kline_bars, list_patterns, scan_patterns
|
|
25
|
+
from alphasift.performance_history import build_strategy_performance_summary
|
|
26
|
+
from alphasift.report import build_run_report_payload
|
|
27
|
+
from alphasift.result_schema import daily_report_schema, screen_result_schema
|
|
28
|
+
from alphasift.run_history import build_strategy_run_summary
|
|
29
|
+
from alphasift.source_history import build_data_source_history
|
|
30
|
+
from alphasift.store import list_saved_runs, load_screen_result
|
|
31
|
+
from alphasift.strategy import compare_strategies, list_strategies, match_strategies, strategy_facets
|
|
32
|
+
from alphasift.strategy_cards import build_strategy_cards
|
|
33
|
+
from alphasift.strategy_templates import get_strategy_template, list_strategy_templates
|
|
34
|
+
from alphasift.workbench_ui import render_workbench_html
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def build_api_response(
|
|
38
|
+
config: Config,
|
|
39
|
+
path: str,
|
|
40
|
+
*,
|
|
41
|
+
query: str = "",
|
|
42
|
+
) -> tuple[int, dict[str, Any]]:
|
|
43
|
+
"""Return an HTTP-ish status and JSON payload for a read-only API route."""
|
|
44
|
+
params = parse_qs(query, keep_blank_values=False)
|
|
45
|
+
if path in {"", "/"}:
|
|
46
|
+
return 200, _index_payload()
|
|
47
|
+
if path == "/health":
|
|
48
|
+
return 200, {"status": "ok", "service": "alphasift", "schema_version": 1}
|
|
49
|
+
if path == "/result-schema":
|
|
50
|
+
return 200, screen_result_schema()
|
|
51
|
+
if path == "/daily-report-schema":
|
|
52
|
+
return 200, daily_report_schema()
|
|
53
|
+
if path == "/overview":
|
|
54
|
+
strategy_arg = _single(params, "strategy") or None
|
|
55
|
+
if strategy_arg and _find_strategy(config, strategy_arg) is None:
|
|
56
|
+
return 404, {
|
|
57
|
+
"error": "strategy_not_found",
|
|
58
|
+
"message": f"Strategy '{strategy_arg}' not found.",
|
|
59
|
+
"strategy": strategy_arg,
|
|
60
|
+
}
|
|
61
|
+
try:
|
|
62
|
+
return 200, build_overview(
|
|
63
|
+
config,
|
|
64
|
+
strategy_name=strategy_arg,
|
|
65
|
+
runs_limit=_int_param(params, "runs_limit", 5, min_val=1, max_val=200),
|
|
66
|
+
live_data_check=_bool_param(params, "live", False),
|
|
67
|
+
strategy_match=_strategy_match_params(params),
|
|
68
|
+
match_limit=_int_param(params, "match_limit", 5, min_val=1, max_val=100),
|
|
69
|
+
)
|
|
70
|
+
except ValueError as exc:
|
|
71
|
+
return 400, {"error": "invalid_request", "message": str(exc)}
|
|
72
|
+
if path == "/strategies":
|
|
73
|
+
criteria = _strategy_match_params(params)
|
|
74
|
+
if _has_match_criteria(criteria):
|
|
75
|
+
return 200, {
|
|
76
|
+
"schema_version": 1,
|
|
77
|
+
"strategies": match_strategies(
|
|
78
|
+
config.strategies_dir,
|
|
79
|
+
**criteria,
|
|
80
|
+
limit=_int_param(params, "limit", 20),
|
|
81
|
+
),
|
|
82
|
+
}
|
|
83
|
+
return 200, {
|
|
84
|
+
"schema_version": 1,
|
|
85
|
+
"strategies": [asdict(item) for item in list_strategies(config.strategies_dir)],
|
|
86
|
+
}
|
|
87
|
+
if path == "/strategy":
|
|
88
|
+
strategy_name = _single(params, "name")
|
|
89
|
+
if not strategy_name:
|
|
90
|
+
return 400, {
|
|
91
|
+
"error": "missing_strategy_name",
|
|
92
|
+
"message": "Query parameter `name` is required.",
|
|
93
|
+
}
|
|
94
|
+
strategy = _find_strategy(config, strategy_name)
|
|
95
|
+
if strategy is None:
|
|
96
|
+
return 404, {
|
|
97
|
+
"error": "strategy_not_found",
|
|
98
|
+
"message": f"Strategy '{strategy_name}' not found.",
|
|
99
|
+
"name": strategy_name,
|
|
100
|
+
}
|
|
101
|
+
return 200, {"schema_version": 1, "strategy": asdict(strategy)}
|
|
102
|
+
if path == "/strategy-compare":
|
|
103
|
+
base_name = _single(params, "base")
|
|
104
|
+
target_name = _single(params, "target")
|
|
105
|
+
if not base_name or not target_name:
|
|
106
|
+
return 400, {
|
|
107
|
+
"error": "missing_strategy_compare_params",
|
|
108
|
+
"message": "Query parameters `base` and `target` are required.",
|
|
109
|
+
}
|
|
110
|
+
try:
|
|
111
|
+
comparison = compare_strategies(base_name, target_name, config.strategies_dir)
|
|
112
|
+
except ValueError as exc:
|
|
113
|
+
return 404, {
|
|
114
|
+
"error": "strategy_not_found",
|
|
115
|
+
"message": str(exc),
|
|
116
|
+
"base": base_name,
|
|
117
|
+
"target": target_name,
|
|
118
|
+
}
|
|
119
|
+
return 200, {"schema_version": 1, "comparison": comparison}
|
|
120
|
+
if path == "/strategy-facets":
|
|
121
|
+
return 200, strategy_facets(config.strategies_dir)
|
|
122
|
+
if path == "/strategy-cards":
|
|
123
|
+
try:
|
|
124
|
+
return 200, build_strategy_cards(
|
|
125
|
+
config,
|
|
126
|
+
strategy_name=_single(params, "strategy") or None,
|
|
127
|
+
runs_limit=_int_param(params, "limit", 100),
|
|
128
|
+
live_data_check=_bool_param(params, "live", False),
|
|
129
|
+
)
|
|
130
|
+
except ValueError as exc:
|
|
131
|
+
return 404, {
|
|
132
|
+
"error": "strategy_not_found",
|
|
133
|
+
"message": str(exc),
|
|
134
|
+
"strategy": _single(params, "strategy"),
|
|
135
|
+
}
|
|
136
|
+
if path == "/strategy-readiness":
|
|
137
|
+
strategy_name = _single(params, "strategy") or None
|
|
138
|
+
try:
|
|
139
|
+
result = doctor_data_sources(
|
|
140
|
+
config,
|
|
141
|
+
snapshot_sources=_multi(params, "snapshot_source") or None,
|
|
142
|
+
daily_source=_single(params, "daily_source") or None,
|
|
143
|
+
daily_code=_single(params, "daily_code") or "000001",
|
|
144
|
+
run_live=_bool_param(params, "live", False),
|
|
145
|
+
check_daily=not _bool_param(params, "no_daily", False),
|
|
146
|
+
strategy_name=strategy_name,
|
|
147
|
+
all_strategies=strategy_name is None,
|
|
148
|
+
).to_dict()
|
|
149
|
+
except ValueError as exc:
|
|
150
|
+
return 404, {
|
|
151
|
+
"error": "strategy_not_found",
|
|
152
|
+
"message": str(exc),
|
|
153
|
+
"strategy": strategy_name or "",
|
|
154
|
+
}
|
|
155
|
+
return 200, {
|
|
156
|
+
"schema_version": 1,
|
|
157
|
+
"status": result.get("status"),
|
|
158
|
+
"config": result.get("config", {}),
|
|
159
|
+
"strategy_requirements": result.get("strategy_requirements", {}),
|
|
160
|
+
"strategy_coverage": result.get("strategy_coverage", []),
|
|
161
|
+
"strategy_readiness_summary": result.get("strategy_readiness_summary", {}),
|
|
162
|
+
"health_summary": result.get("health_summary", {}),
|
|
163
|
+
"freshness_summary": result.get("freshness_summary", {}),
|
|
164
|
+
"recommendations": result.get("recommendations", []),
|
|
165
|
+
}
|
|
166
|
+
if path == "/strategy-templates":
|
|
167
|
+
return 200, {"schema_version": 1, "templates": list_strategy_templates()}
|
|
168
|
+
if path == "/strategy-template":
|
|
169
|
+
template_name = _single(params, "name")
|
|
170
|
+
if not template_name:
|
|
171
|
+
return 400, {
|
|
172
|
+
"error": "missing_template_name",
|
|
173
|
+
"message": "Query parameter `name` is required.",
|
|
174
|
+
}
|
|
175
|
+
try:
|
|
176
|
+
template = get_strategy_template(
|
|
177
|
+
template_name,
|
|
178
|
+
include_yaml=_bool_param(params, "include_yaml", True),
|
|
179
|
+
)
|
|
180
|
+
except ValueError as exc:
|
|
181
|
+
return 404, {
|
|
182
|
+
"error": "strategy_template_not_found",
|
|
183
|
+
"message": str(exc),
|
|
184
|
+
"name": template_name,
|
|
185
|
+
}
|
|
186
|
+
return 200, {"schema_version": 1, "template": template}
|
|
187
|
+
if path == "/strategy-run-summary":
|
|
188
|
+
return 200, build_strategy_run_summary(
|
|
189
|
+
data_dir=config.data_dir,
|
|
190
|
+
limit=_int_param(params, "limit", 100, min_val=1, max_val=200),
|
|
191
|
+
strategy=_single(params, "strategy") or None,
|
|
192
|
+
)
|
|
193
|
+
if path == "/data-source-history":
|
|
194
|
+
return 200, build_data_source_history(
|
|
195
|
+
data_dir=config.data_dir,
|
|
196
|
+
limit=_int_param(params, "limit", 100, min_val=1, max_val=200),
|
|
197
|
+
strategy=_single(params, "strategy") or None,
|
|
198
|
+
)
|
|
199
|
+
if path == "/strategy-performance":
|
|
200
|
+
return 200, build_strategy_performance_summary(
|
|
201
|
+
data_dir=config.data_dir,
|
|
202
|
+
limit=_int_param(params, "limit", 100, min_val=1, max_val=200),
|
|
203
|
+
strategy=_single(params, "strategy") or None,
|
|
204
|
+
)
|
|
205
|
+
if path == "/runs":
|
|
206
|
+
return 200, {
|
|
207
|
+
"schema_version": 1,
|
|
208
|
+
"runs": list_saved_runs(
|
|
209
|
+
data_dir=config.data_dir,
|
|
210
|
+
limit=_int_param(params, "limit", 20, min_val=1, max_val=200),
|
|
211
|
+
strategy=_single(params, "strategy") or None,
|
|
212
|
+
),
|
|
213
|
+
}
|
|
214
|
+
if path == "/report":
|
|
215
|
+
run_ref = _single(params, "run")
|
|
216
|
+
if not run_ref:
|
|
217
|
+
return 400, {"error": "missing_run", "message": "Query parameter `run` is required."}
|
|
218
|
+
try:
|
|
219
|
+
safe_run_path = _validate_safe_run_file(run_ref, data_dir=config.data_dir)
|
|
220
|
+
run = load_screen_result(safe_run_path, data_dir=config.data_dir)
|
|
221
|
+
except ValueError as exc:
|
|
222
|
+
return 400, {"error": "invalid_run_id", "message": str(exc), "run": run_ref}
|
|
223
|
+
except FileNotFoundError as exc:
|
|
224
|
+
return 404, {"error": "run_not_found", "message": str(exc), "run": run_ref}
|
|
225
|
+
return 200, build_run_report_payload(
|
|
226
|
+
run,
|
|
227
|
+
max_picks=_int_param(params, "max_picks", 10, min_val=1, max_val=200),
|
|
228
|
+
)
|
|
229
|
+
if path == "/doctor/data-sources":
|
|
230
|
+
try:
|
|
231
|
+
result = doctor_data_sources(
|
|
232
|
+
config,
|
|
233
|
+
snapshot_sources=_multi(params, "snapshot_source") or None,
|
|
234
|
+
daily_source=_single(params, "daily_source") or None,
|
|
235
|
+
daily_code=_single(params, "daily_code") or "000001",
|
|
236
|
+
run_live=_bool_param(params, "live", False),
|
|
237
|
+
check_daily=not _bool_param(params, "no_daily", False),
|
|
238
|
+
strategy_name=_single(params, "strategy") or None,
|
|
239
|
+
all_strategies=_bool_param(params, "all_strategies", False),
|
|
240
|
+
compare_snapshot_sources=_bool_param(params, "compare_snapshot_sources", False),
|
|
241
|
+
)
|
|
242
|
+
except ValueError as exc:
|
|
243
|
+
return 400, {"error": "invalid_request", "message": str(exc)}
|
|
244
|
+
return 200, result.to_dict()
|
|
245
|
+
if path == "/doctor/radar":
|
|
246
|
+
try:
|
|
247
|
+
return 200, doctor_radar_readiness(
|
|
248
|
+
config,
|
|
249
|
+
trade_date=_single(params, "trade_date") or None,
|
|
250
|
+
)
|
|
251
|
+
except ValueError as exc:
|
|
252
|
+
return 400, {"error": "invalid_request", "message": str(exc)}
|
|
253
|
+
if path == "/patterns":
|
|
254
|
+
include_exp = _bool_param(params, "include_experimental", True)
|
|
255
|
+
return 200, {
|
|
256
|
+
"schema_version": 1,
|
|
257
|
+
"patterns": [asdict(item) for item in list_patterns(include_experimental=include_exp)],
|
|
258
|
+
}
|
|
259
|
+
if path in {"/market-stats", "/patterns/scan", "/daily-report"}:
|
|
260
|
+
safe_run_paths: list[str] = []
|
|
261
|
+
if path == "/daily-report":
|
|
262
|
+
requested_ai_brief = (_single(params, "ai_brief") or "off").lower()
|
|
263
|
+
if requested_ai_brief == "on":
|
|
264
|
+
return 403, {
|
|
265
|
+
"error": "llm_get_disabled",
|
|
266
|
+
"message": "HTTP GET /daily-report does not spend LLM credits; use CLI daily-report --ai-brief on.",
|
|
267
|
+
}
|
|
268
|
+
for raw_id in _multi(params, "run_id"):
|
|
269
|
+
try:
|
|
270
|
+
safe_run_paths.append(str(_validate_safe_run_file(raw_id, data_dir=config.data_dir)))
|
|
271
|
+
except ValueError as exc:
|
|
272
|
+
return 400, {"error": "invalid_run_id", "message": str(exc), "run_id": raw_id}
|
|
273
|
+
try:
|
|
274
|
+
daily_pack = load_pack(pack_dir(config))
|
|
275
|
+
except (OSError, PackError, ValueError) as exc:
|
|
276
|
+
return 503, {
|
|
277
|
+
"error": "pack_unavailable",
|
|
278
|
+
"message": f"CN DailyPack unavailable: {exc}",
|
|
279
|
+
}
|
|
280
|
+
trade_date = _single(params, "trade_date") or None
|
|
281
|
+
try:
|
|
282
|
+
if path == "/market-stats":
|
|
283
|
+
days = max(1, min(250, _int_param(params, "days", 1)))
|
|
284
|
+
if days <= 1:
|
|
285
|
+
return 200, compute_market_regime(daily_pack, trade_date=trade_date).to_dict()
|
|
286
|
+
if trade_date is not None:
|
|
287
|
+
dates = [str(d) for d in daily_pack.dates]
|
|
288
|
+
if trade_date not in dates:
|
|
289
|
+
raise ValueError(f"trade_date {trade_date!r} not found in DailyPack")
|
|
290
|
+
end_idx = dates.index(trade_date)
|
|
291
|
+
else:
|
|
292
|
+
end_idx = len(daily_pack.dates) - 1
|
|
293
|
+
series = compute_market_regime_series(daily_pack, end_index=end_idx)[-days:]
|
|
294
|
+
return 200, {"schema_version": 1, "days": [item.to_dict() for item in series]}
|
|
295
|
+
if path == "/patterns/scan":
|
|
296
|
+
raw_patterns = _multi(params, "pattern")
|
|
297
|
+
include_exp = _bool_param(params, "include_experimental", False)
|
|
298
|
+
selected_patterns: list[str] | None = None
|
|
299
|
+
if raw_patterns:
|
|
300
|
+
known = {spec.name for spec in list_patterns(include_experimental=True)}
|
|
301
|
+
deduped: list[str] = []
|
|
302
|
+
for item in raw_patterns:
|
|
303
|
+
if "/" in item or "\\" in item or ".." in item or item not in known:
|
|
304
|
+
return 400, {
|
|
305
|
+
"error": "invalid_pattern",
|
|
306
|
+
"message": f"Unknown or unsafe pattern name: {item!r}",
|
|
307
|
+
"pattern": item,
|
|
308
|
+
}
|
|
309
|
+
if item not in deduped:
|
|
310
|
+
deduped.append(item)
|
|
311
|
+
if len(deduped) > 32:
|
|
312
|
+
return 400, {
|
|
313
|
+
"error": "too_many_patterns",
|
|
314
|
+
"message": "Too many patterns requested (max 32).",
|
|
315
|
+
}
|
|
316
|
+
selected_patterns = deduped
|
|
317
|
+
payload = scan_patterns(
|
|
318
|
+
daily_pack,
|
|
319
|
+
patterns=selected_patterns,
|
|
320
|
+
trade_date=trade_date,
|
|
321
|
+
include_experimental=include_exp,
|
|
322
|
+
).to_dict()
|
|
323
|
+
if _bool_param(params, "with_kline", False):
|
|
324
|
+
sig_codes: list[str] = []
|
|
325
|
+
for items in (payload.get("signals_by_pattern") or {}).values():
|
|
326
|
+
for item in list(items)[:12]:
|
|
327
|
+
code = str(item.get("code") or "")
|
|
328
|
+
if code:
|
|
329
|
+
sig_codes.append(code)
|
|
330
|
+
if sig_codes:
|
|
331
|
+
klines = extract_mini_kline_bars(
|
|
332
|
+
daily_pack,
|
|
333
|
+
sig_codes,
|
|
334
|
+
trade_date=payload.get("trade_date"),
|
|
335
|
+
bars=20,
|
|
336
|
+
)
|
|
337
|
+
for items in (payload.get("signals_by_pattern") or {}).values():
|
|
338
|
+
for item in items:
|
|
339
|
+
item["kline"] = klines.get(str(item.get("code") or ""), [])
|
|
340
|
+
return 200, payload
|
|
341
|
+
# /daily-report
|
|
342
|
+
include_ann = _bool_param(params, "announcements", False)
|
|
343
|
+
include_runs = _bool_param(params, "include_runs", True)
|
|
344
|
+
run_ids = safe_run_paths or None
|
|
345
|
+
expected_date = _single(params, "expected_trade_date") or None
|
|
346
|
+
allow_stale = _bool_param(params, "allow_stale_pack", True)
|
|
347
|
+
default_detail = _safe_detail_url(config.dashboard_url, fallback="../index.html")
|
|
348
|
+
detail_url = _safe_detail_url(_single(params, "detail_url") or default_detail, fallback=default_detail)
|
|
349
|
+
# Read-only HTTP GET never spends paid LLM credits by default.
|
|
350
|
+
ai_brief = "off"
|
|
351
|
+
ann_max = max(0, min(30, _int_param(params, "announcement_max_codes", 8)))
|
|
352
|
+
strategy_runs = (
|
|
353
|
+
load_daily_report_runs(
|
|
354
|
+
config,
|
|
355
|
+
run_refs=run_ids,
|
|
356
|
+
trade_date=trade_date or daily_pack.trade_date,
|
|
357
|
+
)
|
|
358
|
+
if include_runs
|
|
359
|
+
else []
|
|
360
|
+
)
|
|
361
|
+
return 200, build_daily_report(
|
|
362
|
+
daily_pack,
|
|
363
|
+
trade_date=trade_date,
|
|
364
|
+
expected_trade_date=expected_date,
|
|
365
|
+
allow_stale_pack=allow_stale,
|
|
366
|
+
detail_url=detail_url,
|
|
367
|
+
strategy_runs=strategy_runs,
|
|
368
|
+
include_announcements=include_ann,
|
|
369
|
+
announcement_max_codes=ann_max,
|
|
370
|
+
announcement_cache_dir=(
|
|
371
|
+
config.llm_candidate_context_cache_dir
|
|
372
|
+
or (config.data_dir / "candidate_context_cache")
|
|
373
|
+
),
|
|
374
|
+
ai_brief_mode=ai_brief,
|
|
375
|
+
config=config,
|
|
376
|
+
)
|
|
377
|
+
except (ValueError, IndexError, FileNotFoundError) as exc:
|
|
378
|
+
return 400, {"error": "invalid_request", "message": str(exc)}
|
|
379
|
+
return 404, {
|
|
380
|
+
"error": "not_found",
|
|
381
|
+
"path": path,
|
|
382
|
+
"available_endpoints": _index_payload()["endpoints"],
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def build_html_response(
|
|
387
|
+
config: Config,
|
|
388
|
+
path: str,
|
|
389
|
+
*,
|
|
390
|
+
query: str = "",
|
|
391
|
+
) -> tuple[int, str]:
|
|
392
|
+
"""Return HTTP status and HTML content for standalone UI and report endpoints."""
|
|
393
|
+
if path in {"/ui", "/"}:
|
|
394
|
+
return 200, render_workbench_html()
|
|
395
|
+
if path != "/daily-report.html":
|
|
396
|
+
return 404, (
|
|
397
|
+
"<!doctype html><meta charset='utf-8'><h1>404 Not Found</h1>"
|
|
398
|
+
f"<p>{html.escape(path)}</p>"
|
|
399
|
+
)
|
|
400
|
+
status, payload = build_api_response(config, "/daily-report", query=query)
|
|
401
|
+
if status != 200:
|
|
402
|
+
msg = html.escape(str(payload.get("message") or payload.get("error") or "Error"))
|
|
403
|
+
return status, (
|
|
404
|
+
f"<!doctype html><meta charset='utf-8'><h1>{status}</h1><p>{msg}</p>"
|
|
405
|
+
)
|
|
406
|
+
return 200, render_daily_report_html(payload)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _parse_accept_q(params: list[str]) -> float:
|
|
410
|
+
for p in params:
|
|
411
|
+
if "=" in p:
|
|
412
|
+
k, v = p.split("=", 1)
|
|
413
|
+
if k.strip().lower() == "q":
|
|
414
|
+
try:
|
|
415
|
+
return max(0.0, min(1.0, float(v.strip())))
|
|
416
|
+
except ValueError:
|
|
417
|
+
return 0.0
|
|
418
|
+
return 1.0
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _prefers_html(accept_header: str, query: str) -> bool:
|
|
422
|
+
params = parse_qs(query, keep_blank_values=False)
|
|
423
|
+
if (params.get("format") or [""])[-1].strip().lower() == "json":
|
|
424
|
+
return False
|
|
425
|
+
best_html_q = 0.0
|
|
426
|
+
best_json_q = 0.0
|
|
427
|
+
for raw_range in str(accept_header or "").split(","):
|
|
428
|
+
tokens = [tok.strip() for tok in raw_range.split(";") if tok.strip()]
|
|
429
|
+
if not tokens:
|
|
430
|
+
continue
|
|
431
|
+
media = tokens[0].lower()
|
|
432
|
+
q = _parse_accept_q(tokens[1:])
|
|
433
|
+
if q <= 0.0:
|
|
434
|
+
continue
|
|
435
|
+
if media in {"text/html", "application/xhtml+xml"}:
|
|
436
|
+
best_html_q = max(best_html_q, q)
|
|
437
|
+
elif media == "application/json":
|
|
438
|
+
best_json_q = max(best_json_q, q)
|
|
439
|
+
if best_html_q <= 0.0:
|
|
440
|
+
return False
|
|
441
|
+
return best_html_q >= best_json_q
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _script_src_csp(html_content: str) -> str:
|
|
445
|
+
scripts = re.findall(r"<script>([\s\S]*?)</script>", html_content)
|
|
446
|
+
if not scripts:
|
|
447
|
+
return "'none'"
|
|
448
|
+
hashes = []
|
|
449
|
+
for body in scripts:
|
|
450
|
+
digest = hashlib.sha256(body.encode("utf-8")).digest()
|
|
451
|
+
hashes.append(f"'sha256-{base64.b64encode(digest).decode('ascii')}'")
|
|
452
|
+
return " ".join(hashes)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
_WORKBENCH_SCRIPT_CSP = _script_src_csp(render_workbench_html())
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def serve_api(
|
|
459
|
+
config: Config,
|
|
460
|
+
*,
|
|
461
|
+
host: str = "127.0.0.1",
|
|
462
|
+
port: int = 8765,
|
|
463
|
+
) -> None:
|
|
464
|
+
"""Start the local read-only AlphaSift HTTP API."""
|
|
465
|
+
handler = _handler_for_config(config)
|
|
466
|
+
server = ThreadingHTTPServer((host, int(port)), handler)
|
|
467
|
+
try:
|
|
468
|
+
print(f"AlphaSift API listening on http://{host}:{int(port)}")
|
|
469
|
+
server.serve_forever()
|
|
470
|
+
finally:
|
|
471
|
+
server.server_close()
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _handler_for_config(config: Config):
|
|
475
|
+
class AlphaSiftApiHandler(BaseHTTPRequestHandler):
|
|
476
|
+
server_version = "AlphaSiftAPI/1"
|
|
477
|
+
|
|
478
|
+
def do_GET(self) -> None: # noqa: N802 - required by BaseHTTPRequestHandler.
|
|
479
|
+
parsed = urlparse(self.path)
|
|
480
|
+
vary_accept = parsed.path == "/"
|
|
481
|
+
if parsed.path in {"/ui", "/daily-report.html"} or (
|
|
482
|
+
parsed.path == "/" and _prefers_html(self.headers.get("Accept", ""), parsed.query)
|
|
483
|
+
):
|
|
484
|
+
status, html_body = build_html_response(config, parsed.path, query=parsed.query)
|
|
485
|
+
is_workbench = parsed.path in {"/ui", "/"} and status == 200
|
|
486
|
+
self._send_html(
|
|
487
|
+
status,
|
|
488
|
+
html_body,
|
|
489
|
+
vary_accept=vary_accept,
|
|
490
|
+
script_csp=_WORKBENCH_SCRIPT_CSP if is_workbench else "'none'",
|
|
491
|
+
)
|
|
492
|
+
return
|
|
493
|
+
status, payload = build_api_response(config, parsed.path, query=parsed.query)
|
|
494
|
+
self._send_json(status, payload, vary_accept=vary_accept)
|
|
495
|
+
|
|
496
|
+
def log_message(self, format: str, *args) -> None: # noqa: A002 - stdlib signature.
|
|
497
|
+
return
|
|
498
|
+
|
|
499
|
+
def _send_html(
|
|
500
|
+
self,
|
|
501
|
+
status: int,
|
|
502
|
+
content: str,
|
|
503
|
+
*,
|
|
504
|
+
vary_accept: bool = False,
|
|
505
|
+
script_csp: str = "'none'",
|
|
506
|
+
) -> None:
|
|
507
|
+
body = content.encode("utf-8")
|
|
508
|
+
self.send_response(status)
|
|
509
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
510
|
+
self.send_header("Cache-Control", "no-store")
|
|
511
|
+
if vary_accept:
|
|
512
|
+
self.send_header("Vary", "Accept")
|
|
513
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
514
|
+
self.send_header("X-Frame-Options", "DENY")
|
|
515
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
516
|
+
self.send_header(
|
|
517
|
+
"Content-Security-Policy",
|
|
518
|
+
f"default-src 'self'; script-src {script_csp}; "
|
|
519
|
+
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; "
|
|
520
|
+
"connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
|
|
521
|
+
)
|
|
522
|
+
self.send_header("Content-Length", str(len(body)))
|
|
523
|
+
self.end_headers()
|
|
524
|
+
self.wfile.write(body)
|
|
525
|
+
|
|
526
|
+
def _send_json(self, status: int, payload: dict[str, Any], *, vary_accept: bool = False) -> None:
|
|
527
|
+
body = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
|
|
528
|
+
self.send_response(status)
|
|
529
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
530
|
+
self.send_header("Cache-Control", "no-store")
|
|
531
|
+
if vary_accept:
|
|
532
|
+
self.send_header("Vary", "Accept")
|
|
533
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
534
|
+
self.send_header("Content-Length", str(len(body)))
|
|
535
|
+
self.end_headers()
|
|
536
|
+
self.wfile.write(body)
|
|
537
|
+
|
|
538
|
+
return AlphaSiftApiHandler
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _index_payload() -> dict[str, Any]:
|
|
542
|
+
return {
|
|
543
|
+
"service": "alphasift",
|
|
544
|
+
"schema_version": 1,
|
|
545
|
+
"endpoints": [
|
|
546
|
+
"/health",
|
|
547
|
+
"/ui",
|
|
548
|
+
"/result-schema",
|
|
549
|
+
"/daily-report-schema",
|
|
550
|
+
"/overview",
|
|
551
|
+
"/strategies",
|
|
552
|
+
"/strategy",
|
|
553
|
+
"/strategy-compare",
|
|
554
|
+
"/strategy-facets",
|
|
555
|
+
"/strategy-cards",
|
|
556
|
+
"/strategy-readiness",
|
|
557
|
+
"/strategy-run-summary",
|
|
558
|
+
"/data-source-history",
|
|
559
|
+
"/strategy-performance",
|
|
560
|
+
"/strategy-templates",
|
|
561
|
+
"/strategy-template",
|
|
562
|
+
"/runs",
|
|
563
|
+
"/report",
|
|
564
|
+
"/doctor/data-sources",
|
|
565
|
+
"/doctor/radar",
|
|
566
|
+
"/market-stats",
|
|
567
|
+
"/patterns",
|
|
568
|
+
"/patterns/scan",
|
|
569
|
+
"/daily-report",
|
|
570
|
+
"/daily-report.html",
|
|
571
|
+
],
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _strategy_match_params(params: dict[str, list[str]]) -> dict[str, Any]:
|
|
576
|
+
return {
|
|
577
|
+
"risk_profile": _single(params, "risk_profile"),
|
|
578
|
+
"holding_period": _single(params, "holding_period"),
|
|
579
|
+
"execution_style": _single(params, "execution_style"),
|
|
580
|
+
"market_regime": _multi(params, "market_regime"),
|
|
581
|
+
"capital_profile": _single(params, "capital_profile"),
|
|
582
|
+
"data_requirements": _multi(params, "data_requirement"),
|
|
583
|
+
"tags": _multi(params, "tag"),
|
|
584
|
+
"category": _single(params, "category"),
|
|
585
|
+
"daily_required": _optional_bool_param(params, "daily_required"),
|
|
586
|
+
"strict": _bool_param(params, "strict", False),
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _has_match_criteria(criteria: dict[str, Any]) -> bool:
|
|
591
|
+
return any(
|
|
592
|
+
bool(criteria.get(key))
|
|
593
|
+
for key in (
|
|
594
|
+
"risk_profile",
|
|
595
|
+
"holding_period",
|
|
596
|
+
"execution_style",
|
|
597
|
+
"market_regime",
|
|
598
|
+
"capital_profile",
|
|
599
|
+
"data_requirements",
|
|
600
|
+
"tags",
|
|
601
|
+
"category",
|
|
602
|
+
)
|
|
603
|
+
) or criteria.get("daily_required") is not None or bool(criteria.get("strict"))
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
_SAFE_RUN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _validate_safe_run_file(run_ref: str, *, data_dir: Path) -> Path:
|
|
610
|
+
cleaned = str(run_ref or "").strip()
|
|
611
|
+
if (
|
|
612
|
+
not cleaned
|
|
613
|
+
or "/" in cleaned
|
|
614
|
+
or "\\" in cleaned
|
|
615
|
+
or ".." in cleaned
|
|
616
|
+
or not _SAFE_RUN_ID_RE.fullmatch(cleaned)
|
|
617
|
+
):
|
|
618
|
+
raise ValueError(f"Unsafe run identifier: {cleaned!r}")
|
|
619
|
+
runs_root = (data_dir / "runs").resolve()
|
|
620
|
+
raw_path = runs_root / f"{cleaned}.json"
|
|
621
|
+
if raw_path.is_symlink():
|
|
622
|
+
raise ValueError(f"Symlink run file is not allowed: {cleaned!r}")
|
|
623
|
+
candidate = raw_path.resolve()
|
|
624
|
+
if not candidate.is_relative_to(runs_root):
|
|
625
|
+
raise ValueError(f"Run path escapes runs directory: {cleaned!r}")
|
|
626
|
+
return candidate
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _find_strategy(config: Config, strategy_name: str) -> Any | None:
|
|
630
|
+
for item in list_strategies(config.strategies_dir):
|
|
631
|
+
if item.name == strategy_name:
|
|
632
|
+
return item
|
|
633
|
+
return None
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _single(params: dict[str, list[str]], key: str) -> str:
|
|
637
|
+
values = params.get(key) or []
|
|
638
|
+
return str(values[-1]).strip() if values else ""
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _multi(params: dict[str, list[str]], key: str) -> list[str]:
|
|
642
|
+
values: list[str] = []
|
|
643
|
+
for raw in params.get(key, []) or []:
|
|
644
|
+
values.extend(str(item).strip() for item in str(raw).split(","))
|
|
645
|
+
return [item for item in dict.fromkeys(values) if item]
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _int_param(
|
|
649
|
+
params: dict[str, list[str]],
|
|
650
|
+
key: str,
|
|
651
|
+
default: int,
|
|
652
|
+
*,
|
|
653
|
+
min_val: int | None = None,
|
|
654
|
+
max_val: int | None = None,
|
|
655
|
+
) -> int:
|
|
656
|
+
try:
|
|
657
|
+
val = int(_single(params, key) or default)
|
|
658
|
+
except ValueError:
|
|
659
|
+
val = default
|
|
660
|
+
if min_val is not None:
|
|
661
|
+
val = max(min_val, val)
|
|
662
|
+
if max_val is not None:
|
|
663
|
+
val = min(max_val, val)
|
|
664
|
+
return val
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _optional_bool_param(params: dict[str, list[str]], key: str) -> bool | None:
|
|
668
|
+
value = _single(params, key).lower()
|
|
669
|
+
if value in {"", "any"}:
|
|
670
|
+
return None
|
|
671
|
+
if value in {"1", "true", "yes", "y", "on"}:
|
|
672
|
+
return True
|
|
673
|
+
if value in {"0", "false", "no", "n", "off"}:
|
|
674
|
+
return False
|
|
675
|
+
return None
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _bool_param(params: dict[str, list[str]], key: str, default: bool) -> bool:
|
|
679
|
+
value = _optional_bool_param(params, key)
|
|
680
|
+
return default if value is None else value
|