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
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Shared guardrails for unstable external data-source calls."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from queue import Queue
|
|
8
|
+
import threading
|
|
9
|
+
from typing import Any, Callable, TypeVar
|
|
10
|
+
|
|
11
|
+
T = TypeVar("T")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SourceCallTimeout(TimeoutError):
|
|
15
|
+
"""Raised when a source wrapper exceeds AlphaSift's caller-side timeout."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_source_timeout_seconds(
|
|
19
|
+
specific_env: str,
|
|
20
|
+
*,
|
|
21
|
+
default: float,
|
|
22
|
+
fallback_env: str = "ALPHASIFT_SOURCE_CALL_TIMEOUT_SEC",
|
|
23
|
+
) -> float | None:
|
|
24
|
+
"""Return a positive timeout, or ``None`` when timeout guarding is disabled."""
|
|
25
|
+
raw = os.getenv(specific_env)
|
|
26
|
+
if raw is None:
|
|
27
|
+
raw = os.getenv(fallback_env)
|
|
28
|
+
if raw is None:
|
|
29
|
+
return float(default)
|
|
30
|
+
cleaned = raw.strip().lower()
|
|
31
|
+
if cleaned in {"", "0", "false", "off", "none", "disabled"}:
|
|
32
|
+
return None
|
|
33
|
+
timeout = float(cleaned)
|
|
34
|
+
return timeout if timeout > 0 else None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def call_with_timeout(
|
|
38
|
+
func: Callable[..., T],
|
|
39
|
+
*args: Any,
|
|
40
|
+
timeout_sec: float | None,
|
|
41
|
+
label: str,
|
|
42
|
+
**kwargs: Any,
|
|
43
|
+
) -> T:
|
|
44
|
+
"""Run ``func`` with a bounded wait for the caller.
|
|
45
|
+
|
|
46
|
+
Python cannot force-stop a thread that is already blocked inside a third-party
|
|
47
|
+
library. The worker is daemonized so the caller can fall back promptly and a
|
|
48
|
+
finished CLI process is not kept alive by a stuck wrapper call.
|
|
49
|
+
"""
|
|
50
|
+
if timeout_sec is None:
|
|
51
|
+
return func(*args, **kwargs)
|
|
52
|
+
|
|
53
|
+
result_queue: Queue[tuple[bool, object]] = Queue(maxsize=1)
|
|
54
|
+
|
|
55
|
+
def run() -> None:
|
|
56
|
+
try:
|
|
57
|
+
result_queue.put((True, func(*args, **kwargs)))
|
|
58
|
+
except BaseException as exc: # noqa: BLE001 - propagate worker failures to caller.
|
|
59
|
+
result_queue.put((False, exc))
|
|
60
|
+
|
|
61
|
+
worker = threading.Thread(target=run, name=f"alphasift-source:{label}", daemon=True)
|
|
62
|
+
worker.start()
|
|
63
|
+
worker.join(float(timeout_sec))
|
|
64
|
+
if worker.is_alive():
|
|
65
|
+
raise SourceCallTimeout(f"{label} timed out after {float(timeout_sec):g}s")
|
|
66
|
+
|
|
67
|
+
ok, payload = result_queue.get_nowait()
|
|
68
|
+
if ok:
|
|
69
|
+
return payload # type: ignore[return-value]
|
|
70
|
+
raise payload
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Saved-run data-source reliability summaries for UI and agents."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from alphasift.store import list_saved_runs
|
|
10
|
+
from alphasift.timeutil import MIN_TIMESTAMP, parse_timestamp
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_data_source_history(
|
|
14
|
+
*,
|
|
15
|
+
data_dir: Path,
|
|
16
|
+
limit: int = 100,
|
|
17
|
+
strategy: str | None = None,
|
|
18
|
+
) -> dict[str, object]:
|
|
19
|
+
"""Summarize recent saved-run source reliability without loading full runs."""
|
|
20
|
+
runs = list_saved_runs(data_dir=data_dir, limit=limit, strategy=strategy)
|
|
21
|
+
source_rows = [_source_summary(items) for items in _group_runs_by_snapshot_source(runs).values()]
|
|
22
|
+
source_rows.sort(
|
|
23
|
+
key=lambda item: (
|
|
24
|
+
float(item.get("source_error_rate") or 0.0) + float(item.get("degradation_rate") or 0.0),
|
|
25
|
+
_parse_created_at(str(item.get("latest_created_at") or "")),
|
|
26
|
+
str(item.get("snapshot_source") or ""),
|
|
27
|
+
),
|
|
28
|
+
reverse=True,
|
|
29
|
+
)
|
|
30
|
+
return {
|
|
31
|
+
"schema_version": 1,
|
|
32
|
+
"run_count": len(runs),
|
|
33
|
+
"source_count": len(source_rows),
|
|
34
|
+
"limit": int(limit),
|
|
35
|
+
"strategy_filter": strategy or "",
|
|
36
|
+
"summary": _history_summary(runs),
|
|
37
|
+
"snapshot_sources": source_rows,
|
|
38
|
+
"watchlist": _watchlist(source_rows),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _group_runs_by_snapshot_source(
|
|
43
|
+
runs: list[dict[str, object]],
|
|
44
|
+
) -> dict[str, list[dict[str, object]]]:
|
|
45
|
+
groups: dict[str, list[dict[str, object]]] = {}
|
|
46
|
+
for item in runs:
|
|
47
|
+
source_name = str(item.get("snapshot_source") or "unknown")
|
|
48
|
+
groups.setdefault(source_name, []).append(item)
|
|
49
|
+
return groups
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _source_summary(runs: list[dict[str, object]]) -> dict[str, object]:
|
|
53
|
+
ordered = sorted(runs, key=_run_sort_key, reverse=True)
|
|
54
|
+
latest = ordered[0] if ordered else {}
|
|
55
|
+
source_error_runs = [
|
|
56
|
+
item for item in ordered if _int_value(item.get("source_error_count")) > 0
|
|
57
|
+
]
|
|
58
|
+
degraded_runs = [
|
|
59
|
+
item for item in ordered if _int_value(item.get("degradation_count")) > 0
|
|
60
|
+
]
|
|
61
|
+
fallback_run_count = sum(
|
|
62
|
+
1 for item in ordered if str(item.get("snapshot_source") or "") == "last_good_cache"
|
|
63
|
+
)
|
|
64
|
+
source_error_rate = _rate(len(source_error_runs), len(ordered))
|
|
65
|
+
degradation_rate = _rate(len(degraded_runs), len(ordered))
|
|
66
|
+
fallback_rate = _rate(fallback_run_count, len(ordered))
|
|
67
|
+
stability_status = _stability_status(
|
|
68
|
+
run_count=len(ordered),
|
|
69
|
+
source_error_rate=source_error_rate,
|
|
70
|
+
degradation_rate=degradation_rate,
|
|
71
|
+
fallback_rate=fallback_rate,
|
|
72
|
+
)
|
|
73
|
+
source_name = str(latest.get("snapshot_source") or "unknown")
|
|
74
|
+
return {
|
|
75
|
+
"snapshot_source": source_name,
|
|
76
|
+
"run_count": len(ordered),
|
|
77
|
+
"strategy_count": len(_unique_values(item.get("strategy") for item in ordered)),
|
|
78
|
+
"strategies": _unique_values(item.get("strategy") for item in ordered),
|
|
79
|
+
"latest_run_id": str(latest.get("run_id") or ""),
|
|
80
|
+
"latest_created_at": str(latest.get("created_at") or ""),
|
|
81
|
+
"total_picks": sum(_int_value(item.get("picks")) for item in ordered),
|
|
82
|
+
"average_picks": _average(_int_value(item.get("picks")) for item in ordered),
|
|
83
|
+
"runs_with_source_errors": len(source_error_runs),
|
|
84
|
+
"source_error_count": sum(_int_value(item.get("source_error_count")) for item in ordered),
|
|
85
|
+
"source_error_rate": source_error_rate,
|
|
86
|
+
"source_error_samples": _sample_values(ordered, "source_errors"),
|
|
87
|
+
"runs_with_degradation": len(degraded_runs),
|
|
88
|
+
"degradation_count": sum(_int_value(item.get("degradation_count")) for item in ordered),
|
|
89
|
+
"degradation_rate": degradation_rate,
|
|
90
|
+
"degradation_samples": _sample_values(ordered, "degradation"),
|
|
91
|
+
"fallback_run_count": fallback_run_count,
|
|
92
|
+
"fallback_rate": fallback_rate,
|
|
93
|
+
"stability_status": stability_status,
|
|
94
|
+
"stability_score": _stability_score(
|
|
95
|
+
run_count=len(ordered),
|
|
96
|
+
source_error_rate=source_error_rate,
|
|
97
|
+
degradation_rate=degradation_rate,
|
|
98
|
+
fallback_rate=fallback_rate,
|
|
99
|
+
),
|
|
100
|
+
"next_actions": _stability_actions(
|
|
101
|
+
stability_status,
|
|
102
|
+
snapshot_source=source_name,
|
|
103
|
+
),
|
|
104
|
+
"daily_enriched_runs": sum(1 for item in ordered if bool(item.get("daily_enriched"))),
|
|
105
|
+
"daily_enrich_count": sum(_int_value(item.get("daily_enrich_count")) for item in ordered),
|
|
106
|
+
"recent_runs": [_compact_run(item) for item in ordered[:5]],
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _history_summary(runs: list[dict[str, object]]) -> dict[str, object]:
|
|
111
|
+
ordered = sorted(runs, key=_run_sort_key, reverse=True)
|
|
112
|
+
error_runs = [item for item in runs if _int_value(item.get("source_error_count")) > 0]
|
|
113
|
+
degraded_runs = [item for item in runs if _int_value(item.get("degradation_count")) > 0]
|
|
114
|
+
fallback_runs = [
|
|
115
|
+
item for item in runs if str(item.get("snapshot_source") or "") == "last_good_cache"
|
|
116
|
+
]
|
|
117
|
+
source_error_rate = _rate(len(error_runs), len(runs))
|
|
118
|
+
degradation_rate = _rate(len(degraded_runs), len(runs))
|
|
119
|
+
fallback_rate = _rate(len(fallback_runs), len(runs))
|
|
120
|
+
stability_status = _stability_status(
|
|
121
|
+
run_count=len(runs),
|
|
122
|
+
source_error_rate=source_error_rate,
|
|
123
|
+
degradation_rate=degradation_rate,
|
|
124
|
+
fallback_rate=fallback_rate,
|
|
125
|
+
)
|
|
126
|
+
return {
|
|
127
|
+
"runs_with_source_errors": len(error_runs),
|
|
128
|
+
"source_error_rate": source_error_rate,
|
|
129
|
+
"source_error_samples": _sample_values(ordered, "source_errors"),
|
|
130
|
+
"runs_with_degradation": len(degraded_runs),
|
|
131
|
+
"degradation_rate": degradation_rate,
|
|
132
|
+
"degradation_samples": _sample_values(ordered, "degradation"),
|
|
133
|
+
"fallback_run_count": len(fallback_runs),
|
|
134
|
+
"fallback_rate": fallback_rate,
|
|
135
|
+
"stability_status": stability_status,
|
|
136
|
+
"stability_score": _stability_score(
|
|
137
|
+
run_count=len(runs),
|
|
138
|
+
source_error_rate=source_error_rate,
|
|
139
|
+
degradation_rate=degradation_rate,
|
|
140
|
+
fallback_rate=fallback_rate,
|
|
141
|
+
),
|
|
142
|
+
"next_actions": _stability_actions(stability_status),
|
|
143
|
+
"daily_enriched_runs": sum(1 for item in runs if bool(item.get("daily_enriched"))),
|
|
144
|
+
"snapshot_sources": _unique_values(item.get("snapshot_source") for item in runs),
|
|
145
|
+
"latest_run": _compact_run(ordered[0]) if ordered else {},
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _watchlist(source_rows: list[dict[str, object]]) -> list[dict[str, object]]:
|
|
150
|
+
rows = []
|
|
151
|
+
for item in source_rows:
|
|
152
|
+
if (
|
|
153
|
+
float(item.get("source_error_rate") or 0.0) > 0
|
|
154
|
+
or float(item.get("degradation_rate") or 0.0) > 0
|
|
155
|
+
or _int_value(item.get("fallback_run_count")) > 0
|
|
156
|
+
):
|
|
157
|
+
rows.append(
|
|
158
|
+
{
|
|
159
|
+
"snapshot_source": item.get("snapshot_source", ""),
|
|
160
|
+
"run_count": item.get("run_count", 0),
|
|
161
|
+
"source_error_rate": item.get("source_error_rate", 0.0),
|
|
162
|
+
"degradation_rate": item.get("degradation_rate", 0.0),
|
|
163
|
+
"fallback_run_count": item.get("fallback_run_count", 0),
|
|
164
|
+
"fallback_rate": item.get("fallback_rate", 0.0),
|
|
165
|
+
"stability_status": item.get("stability_status", "unknown"),
|
|
166
|
+
"stability_score": item.get("stability_score"),
|
|
167
|
+
"latest_run_id": item.get("latest_run_id", ""),
|
|
168
|
+
"strategies": item.get("strategies", []),
|
|
169
|
+
"source_error_samples": item.get("source_error_samples", []),
|
|
170
|
+
"degradation_samples": item.get("degradation_samples", []),
|
|
171
|
+
"next_actions": item.get("next_actions", []),
|
|
172
|
+
}
|
|
173
|
+
)
|
|
174
|
+
rows.sort(
|
|
175
|
+
key=lambda item: (
|
|
176
|
+
_status_rank(str(item.get("stability_status") or "")),
|
|
177
|
+
float(item.get("source_error_rate") or 0.0) + float(item.get("degradation_rate") or 0.0),
|
|
178
|
+
_int_value(item.get("fallback_run_count")),
|
|
179
|
+
str(item.get("snapshot_source") or ""),
|
|
180
|
+
),
|
|
181
|
+
reverse=True,
|
|
182
|
+
)
|
|
183
|
+
return rows
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _compact_run(item: dict[str, object]) -> dict[str, object]:
|
|
187
|
+
return {
|
|
188
|
+
"run_id": str(item.get("run_id") or ""),
|
|
189
|
+
"strategy": str(item.get("strategy") or ""),
|
|
190
|
+
"created_at": str(item.get("created_at") or ""),
|
|
191
|
+
"picks": _int_value(item.get("picks")),
|
|
192
|
+
"snapshot_source": str(item.get("snapshot_source") or ""),
|
|
193
|
+
"source_error_count": _int_value(item.get("source_error_count")),
|
|
194
|
+
"source_errors": _sample_list(item.get("source_errors"), limit=3),
|
|
195
|
+
"degradation_count": _int_value(item.get("degradation_count")),
|
|
196
|
+
"degradation": _sample_list(item.get("degradation"), limit=3),
|
|
197
|
+
"report_path": str(item.get("report_path") or ""),
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _unique_values(values) -> list[str]:
|
|
202
|
+
return list(dict.fromkeys(str(value) for value in values if str(value or "")))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _sample_values(
|
|
206
|
+
runs: list[dict[str, object]],
|
|
207
|
+
field: str,
|
|
208
|
+
*,
|
|
209
|
+
limit: int = 5,
|
|
210
|
+
) -> list[str]:
|
|
211
|
+
values: list[str] = []
|
|
212
|
+
for item in runs:
|
|
213
|
+
values.extend(_sample_list(item.get(field), limit=limit))
|
|
214
|
+
return list(dict.fromkeys(values))[:limit]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _sample_list(value: object, *, limit: int) -> list[str]:
|
|
218
|
+
if isinstance(value, list):
|
|
219
|
+
return [str(item) for item in value if str(item)][:limit]
|
|
220
|
+
if isinstance(value, str) and value:
|
|
221
|
+
return [item.strip() for item in value.split(",") if item.strip()][:limit]
|
|
222
|
+
return []
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _average(values) -> float | None:
|
|
226
|
+
items = [float(value) for value in values]
|
|
227
|
+
if not items:
|
|
228
|
+
return None
|
|
229
|
+
return round(sum(items) / len(items), 4)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _rate(count: int, total: int) -> float:
|
|
233
|
+
if total <= 0:
|
|
234
|
+
return 0.0
|
|
235
|
+
return round(float(count) / float(total), 4)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _stability_status(
|
|
239
|
+
*,
|
|
240
|
+
run_count: int,
|
|
241
|
+
source_error_rate: float,
|
|
242
|
+
degradation_rate: float,
|
|
243
|
+
fallback_rate: float,
|
|
244
|
+
) -> str:
|
|
245
|
+
if run_count <= 0:
|
|
246
|
+
return "unknown"
|
|
247
|
+
if fallback_rate > 0:
|
|
248
|
+
return "fallback"
|
|
249
|
+
if source_error_rate >= 0.5 or degradation_rate >= 0.5:
|
|
250
|
+
return "degraded"
|
|
251
|
+
if source_error_rate > 0 or degradation_rate > 0:
|
|
252
|
+
return "watch"
|
|
253
|
+
return "ok"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _stability_score(
|
|
257
|
+
*,
|
|
258
|
+
run_count: int,
|
|
259
|
+
source_error_rate: float,
|
|
260
|
+
degradation_rate: float,
|
|
261
|
+
fallback_rate: float,
|
|
262
|
+
) -> float | None:
|
|
263
|
+
if run_count <= 0:
|
|
264
|
+
return None
|
|
265
|
+
score = 100.0 - (source_error_rate * 45.0) - (degradation_rate * 35.0) - (fallback_rate * 30.0)
|
|
266
|
+
return round(max(0.0, score), 1)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _stability_actions(status: str, *, snapshot_source: str = "") -> list[str]:
|
|
270
|
+
if status == "unknown":
|
|
271
|
+
return ["Run saved screens to collect data-source history."]
|
|
272
|
+
if status == "fallback":
|
|
273
|
+
return ["Refresh live snapshot providers before relying on last-good cache runs."]
|
|
274
|
+
if status == "degraded":
|
|
275
|
+
source = f" `{snapshot_source}`" if snapshot_source else ""
|
|
276
|
+
return [f"Compare{source} with alternate snapshot providers and inspect issue samples."]
|
|
277
|
+
if status == "watch":
|
|
278
|
+
source = f" `{snapshot_source}`" if snapshot_source else ""
|
|
279
|
+
return [f"Monitor{source} over the next saved runs and keep alternate providers configured."]
|
|
280
|
+
return []
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _status_rank(status: str) -> int:
|
|
284
|
+
return {
|
|
285
|
+
"fallback": 4,
|
|
286
|
+
"degraded": 3,
|
|
287
|
+
"watch": 2,
|
|
288
|
+
"ok": 1,
|
|
289
|
+
"unknown": 0,
|
|
290
|
+
}.get(status, 0)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _int_value(value: object) -> int:
|
|
294
|
+
try:
|
|
295
|
+
return int(value or 0)
|
|
296
|
+
except (TypeError, ValueError):
|
|
297
|
+
return 0
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _run_sort_key(item: dict[str, object]) -> tuple[datetime, str]:
|
|
301
|
+
return (_parse_created_at(str(item.get("created_at") or "")), str(item.get("run_id") or ""))
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _parse_created_at(value: str) -> datetime:
|
|
305
|
+
# Aware for both old naive and new offset timestamps, so they sort together.
|
|
306
|
+
return parse_timestamp(value) or MIN_TIMESTAMP
|
alphasift/store.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Persistence helpers for screen runs and evaluations."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import asdict, fields
|
|
8
|
+
from math import isfinite
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from alphasift.models import EvaluationResult, Pick, PickEvaluation, ScreenResult
|
|
12
|
+
|
|
13
|
+
_RUN_METADATA_SUFFIX = ".meta"
|
|
14
|
+
_RUN_SOURCE_ERROR_SAMPLE_LIMIT = 5
|
|
15
|
+
_RUN_DEGRADATION_SAMPLE_LIMIT = 8
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def save_screen_result(
|
|
19
|
+
result: ScreenResult,
|
|
20
|
+
*,
|
|
21
|
+
data_dir: Path,
|
|
22
|
+
path: str | Path | None = None,
|
|
23
|
+
jsonl: bool = False,
|
|
24
|
+
) -> Path:
|
|
25
|
+
"""Persist a screen result and return the written path."""
|
|
26
|
+
output_path = Path(path) if path is not None else data_dir / "runs" / f"{result.run_id}.json"
|
|
27
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
result.saved_path = str(output_path)
|
|
29
|
+
if jsonl:
|
|
30
|
+
output_path.write_text("\n".join(screen_result_to_jsonl(result)) + "\n", encoding="utf-8")
|
|
31
|
+
else:
|
|
32
|
+
output_path.write_text(
|
|
33
|
+
json.dumps(asdict(result), ensure_ascii=False, indent=2),
|
|
34
|
+
encoding="utf-8",
|
|
35
|
+
)
|
|
36
|
+
_write_screen_result_metadata(result, output_path)
|
|
37
|
+
return output_path
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_screen_result(run_ref: str | Path, *, data_dir: Path) -> ScreenResult:
|
|
41
|
+
"""Load a saved screen result by run_id or path."""
|
|
42
|
+
path = resolve_run_path(run_ref, data_dir=data_dir)
|
|
43
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
44
|
+
raw_picks = data.get("picks")
|
|
45
|
+
pick_items = raw_picks if isinstance(raw_picks, list) else []
|
|
46
|
+
pick_fields = {field.name for field in fields(Pick)}
|
|
47
|
+
result_fields = {field.name for field in fields(ScreenResult)}
|
|
48
|
+
data["picks"] = [
|
|
49
|
+
Pick(**{key: value for key, value in item.items() if key in pick_fields})
|
|
50
|
+
for item in pick_items
|
|
51
|
+
if isinstance(item, dict)
|
|
52
|
+
]
|
|
53
|
+
filtered = {key: value for key, value in data.items() if key in result_fields}
|
|
54
|
+
# Runs without a market predate multi-market support and were A-share.
|
|
55
|
+
filtered["market"] = filtered.get("market") or "cn"
|
|
56
|
+
if not filtered.get("track"):
|
|
57
|
+
filtered["track"] = "ai" if filtered.get("llm_ranked") else "rules"
|
|
58
|
+
filtered["daily_source_counts"] = _int_count_dict(filtered.get("daily_source_counts"))
|
|
59
|
+
filtered["daily_quality_flag_counts"] = _int_count_dict(filtered.get("daily_quality_flag_counts"))
|
|
60
|
+
loaded = ScreenResult(**filtered)
|
|
61
|
+
loaded.saved_path = str(path)
|
|
62
|
+
return loaded
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def save_evaluation_result(
|
|
66
|
+
result: EvaluationResult,
|
|
67
|
+
*,
|
|
68
|
+
data_dir: Path,
|
|
69
|
+
path: str | Path | None = None,
|
|
70
|
+
jsonl: bool = False,
|
|
71
|
+
) -> Path:
|
|
72
|
+
output_path = Path(path) if path is not None else data_dir / "evaluations" / f"{result.run_id}.json"
|
|
73
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
result.saved_path = str(output_path)
|
|
75
|
+
if jsonl:
|
|
76
|
+
output_path.write_text("\n".join(evaluation_result_to_jsonl(result)) + "\n", encoding="utf-8")
|
|
77
|
+
else:
|
|
78
|
+
output_path.write_text(
|
|
79
|
+
json.dumps(asdict(result), ensure_ascii=False, indent=2),
|
|
80
|
+
encoding="utf-8",
|
|
81
|
+
)
|
|
82
|
+
return output_path
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def list_saved_runs(
|
|
86
|
+
*,
|
|
87
|
+
data_dir: Path,
|
|
88
|
+
limit: int = 20,
|
|
89
|
+
strategy: str | None = None,
|
|
90
|
+
market: str | None = None,
|
|
91
|
+
) -> list[dict[str, object]]:
|
|
92
|
+
runs_dir = data_dir / "runs"
|
|
93
|
+
if not runs_dir.is_dir():
|
|
94
|
+
return []
|
|
95
|
+
limit = int(limit)
|
|
96
|
+
if limit <= 0:
|
|
97
|
+
return []
|
|
98
|
+
items = []
|
|
99
|
+
for path in sorted(runs_dir.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True):
|
|
100
|
+
metadata = _read_run_metadata(path)
|
|
101
|
+
if metadata is None:
|
|
102
|
+
continue
|
|
103
|
+
if strategy and metadata.get("strategy") != strategy:
|
|
104
|
+
continue
|
|
105
|
+
if market and metadata.get("market") != market:
|
|
106
|
+
continue
|
|
107
|
+
items.append(metadata)
|
|
108
|
+
if len(items) >= limit:
|
|
109
|
+
break
|
|
110
|
+
return items
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _write_screen_result_metadata(result: ScreenResult, output_path: Path) -> None:
|
|
114
|
+
metadata_path = _run_metadata_path(output_path)
|
|
115
|
+
metadata = {
|
|
116
|
+
"schema_version": 3,
|
|
117
|
+
"run_id": result.run_id or output_path.stem,
|
|
118
|
+
"strategy": result.strategy,
|
|
119
|
+
"market": result.market,
|
|
120
|
+
"strategy_version": result.strategy_version,
|
|
121
|
+
"strategy_category": result.strategy_category,
|
|
122
|
+
"created_at": result.created_at,
|
|
123
|
+
"picks": len(result.picks),
|
|
124
|
+
"snapshot_count": result.snapshot_count,
|
|
125
|
+
"after_filter_count": result.after_filter_count,
|
|
126
|
+
"snapshot_source": result.snapshot_source,
|
|
127
|
+
"source_error_count": len(result.source_errors),
|
|
128
|
+
"source_errors": list(result.source_errors)[:_RUN_SOURCE_ERROR_SAMPLE_LIMIT],
|
|
129
|
+
"degradation_count": len(result.degradation),
|
|
130
|
+
"degradation": list(result.degradation)[:_RUN_DEGRADATION_SAMPLE_LIMIT],
|
|
131
|
+
"llm_ranked": bool(result.llm_ranked),
|
|
132
|
+
"llm_coverage": result.llm_coverage,
|
|
133
|
+
"daily_enriched": bool(result.daily_enriched),
|
|
134
|
+
"daily_enrich_count": result.daily_enrich_count,
|
|
135
|
+
"daily_source_counts": _int_count_dict(result.daily_source_counts),
|
|
136
|
+
"daily_quality_flag_counts": _int_count_dict(result.daily_quality_flag_counts),
|
|
137
|
+
"post_analyzers": list(result.post_analyzers),
|
|
138
|
+
"path": str(output_path),
|
|
139
|
+
"report_path": str(output_path.with_suffix(".md")),
|
|
140
|
+
}
|
|
141
|
+
metadata_path.write_text(
|
|
142
|
+
json.dumps(metadata, ensure_ascii=False, indent=2),
|
|
143
|
+
encoding="utf-8",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _run_metadata_path(run_path: Path) -> Path:
|
|
148
|
+
return run_path.with_suffix(run_path.suffix + _RUN_METADATA_SUFFIX)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _read_run_metadata(path: Path) -> dict[str, object] | None:
|
|
152
|
+
metadata_path = _run_metadata_path(path)
|
|
153
|
+
if metadata_path.is_file():
|
|
154
|
+
try:
|
|
155
|
+
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
|
|
156
|
+
if isinstance(metadata, dict):
|
|
157
|
+
return _normalize_run_metadata(metadata, path)
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
try:
|
|
161
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
162
|
+
except Exception:
|
|
163
|
+
return None
|
|
164
|
+
if not isinstance(data, dict):
|
|
165
|
+
return None
|
|
166
|
+
return _normalize_run_metadata(data, path)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _normalize_run_metadata(data: dict, path: Path) -> dict[str, object]:
|
|
170
|
+
picks = data.get("picks", [])
|
|
171
|
+
if isinstance(picks, list):
|
|
172
|
+
pick_count = len(picks)
|
|
173
|
+
else:
|
|
174
|
+
try:
|
|
175
|
+
pick_count = int(picks)
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
pick_count = 0
|
|
178
|
+
return {
|
|
179
|
+
"schema_version": int(_metadata_value(data, "schema_version", 1) or 1),
|
|
180
|
+
"run_id": data.get("run_id", path.stem),
|
|
181
|
+
"strategy": data.get("strategy", ""),
|
|
182
|
+
"market": data.get("market") or "cn",
|
|
183
|
+
"strategy_version": data.get("strategy_version", ""),
|
|
184
|
+
"strategy_category": data.get("strategy_category", ""),
|
|
185
|
+
"created_at": data.get("created_at", ""),
|
|
186
|
+
"picks": pick_count,
|
|
187
|
+
"snapshot_count": int(_metadata_value(data, "snapshot_count", 0) or 0),
|
|
188
|
+
"after_filter_count": int(_metadata_value(data, "after_filter_count", 0) or 0),
|
|
189
|
+
"snapshot_source": data.get("snapshot_source", ""),
|
|
190
|
+
"source_error_count": int(_metadata_value(data, "source_error_count", _list_count(data.get("source_errors"))) or 0),
|
|
191
|
+
"source_errors": _string_list(data.get("source_errors", []))[:_RUN_SOURCE_ERROR_SAMPLE_LIMIT],
|
|
192
|
+
"degradation_count": int(_metadata_value(data, "degradation_count", _list_count(data.get("degradation"))) or 0),
|
|
193
|
+
"degradation": _string_list(data.get("degradation", []))[:_RUN_DEGRADATION_SAMPLE_LIMIT],
|
|
194
|
+
"llm_ranked": bool(data.get("llm_ranked", False)),
|
|
195
|
+
"llm_coverage": data.get("llm_coverage"),
|
|
196
|
+
"daily_enriched": bool(data.get("daily_enriched", False)),
|
|
197
|
+
"daily_enrich_count": int(_metadata_value(data, "daily_enrich_count", 0) or 0),
|
|
198
|
+
"daily_source_counts": _int_count_dict(data.get("daily_source_counts")),
|
|
199
|
+
"daily_quality_flag_counts": _int_count_dict(data.get("daily_quality_flag_counts")),
|
|
200
|
+
"post_analyzers": _string_list(data.get("post_analyzers", [])),
|
|
201
|
+
"path": str(path),
|
|
202
|
+
"report_path": str(data.get("report_path") or path.with_suffix(".md")),
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _int_count_dict(value: object) -> dict[str, int]:
|
|
207
|
+
if not isinstance(value, dict):
|
|
208
|
+
return {}
|
|
209
|
+
result: dict[str, int] = {}
|
|
210
|
+
for key, count in value.items():
|
|
211
|
+
name = str(key or "").strip()
|
|
212
|
+
if not name or isinstance(count, bool):
|
|
213
|
+
continue
|
|
214
|
+
if isinstance(count, float) and not isfinite(count):
|
|
215
|
+
continue
|
|
216
|
+
try:
|
|
217
|
+
parsed = int(count)
|
|
218
|
+
except (TypeError, ValueError, OverflowError):
|
|
219
|
+
continue
|
|
220
|
+
if parsed > 0:
|
|
221
|
+
result[name] = parsed
|
|
222
|
+
return result
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _metadata_value(data: dict, key: str, default: object) -> object:
|
|
226
|
+
value = data.get(key, default)
|
|
227
|
+
return default if value is None else value
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _list_count(value: object) -> int:
|
|
231
|
+
return len(value) if isinstance(value, list) else 0
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _string_list(value: object) -> list[str]:
|
|
235
|
+
if isinstance(value, list):
|
|
236
|
+
return [str(item) for item in value]
|
|
237
|
+
if isinstance(value, str) and value:
|
|
238
|
+
return [item.strip() for item in value.split(",") if item.strip()]
|
|
239
|
+
return []
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def resolve_run_path(run_ref: str | Path, *, data_dir: Path) -> Path:
|
|
243
|
+
if isinstance(run_ref, Path):
|
|
244
|
+
if run_ref.is_file():
|
|
245
|
+
return run_ref
|
|
246
|
+
raise FileNotFoundError(f"Saved run not found: {run_ref}")
|
|
247
|
+
raw = str(run_ref)
|
|
248
|
+
candidate = data_dir / "runs" / f"{raw}.json"
|
|
249
|
+
# Prefer data_dir/runs/<id>.json over same-named CWD files when given a bare run ID.
|
|
250
|
+
if "/" not in raw and "\\" not in raw and candidate.is_file():
|
|
251
|
+
return candidate
|
|
252
|
+
path = Path(raw)
|
|
253
|
+
if path.is_file():
|
|
254
|
+
return path
|
|
255
|
+
if candidate.is_file():
|
|
256
|
+
return candidate
|
|
257
|
+
raise FileNotFoundError(f"Saved run not found: {run_ref}")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def screen_result_to_jsonl(result: ScreenResult) -> list[str]:
|
|
261
|
+
data = asdict(result)
|
|
262
|
+
picks = data.pop("picks", [])
|
|
263
|
+
lines = [json.dumps({"type": "run", **data}, ensure_ascii=False)]
|
|
264
|
+
for pick in picks:
|
|
265
|
+
lines.append(json.dumps({"type": "pick", "run_id": result.run_id, **pick}, ensure_ascii=False))
|
|
266
|
+
return lines
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def evaluation_result_to_jsonl(result: EvaluationResult) -> list[str]:
|
|
270
|
+
data = asdict(result)
|
|
271
|
+
picks = data.pop("picks", [])
|
|
272
|
+
lines = [json.dumps({"type": "evaluation", **data}, ensure_ascii=False)]
|
|
273
|
+
for pick in picks:
|
|
274
|
+
lines.append(json.dumps({"type": "pick_evaluation", "run_id": result.run_id, **pick}, ensure_ascii=False))
|
|
275
|
+
return lines
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def evaluation_from_dict(data: dict) -> EvaluationResult:
|
|
279
|
+
pick_fields = {field.name for field in fields(PickEvaluation)}
|
|
280
|
+
result_fields = {field.name for field in fields(EvaluationResult)}
|
|
281
|
+
data = dict(data)
|
|
282
|
+
raw_picks = data.get("picks")
|
|
283
|
+
pick_items = raw_picks if isinstance(raw_picks, list) else []
|
|
284
|
+
data["picks"] = [
|
|
285
|
+
PickEvaluation(**{key: value for key, value in item.items() if key in pick_fields})
|
|
286
|
+
for item in pick_items
|
|
287
|
+
if isinstance(item, dict)
|
|
288
|
+
]
|
|
289
|
+
data["run_snapshot_source"] = str(data.get("run_snapshot_source") or "")
|
|
290
|
+
data["run_source_errors"] = _string_list(data.get("run_source_errors"))
|
|
291
|
+
data["run_degradation"] = _string_list(data.get("run_degradation"))
|
|
292
|
+
data["daily_source_counts"] = _int_count_dict(data.get("daily_source_counts"))
|
|
293
|
+
data["daily_quality_flag_counts"] = _int_count_dict(data.get("daily_quality_flag_counts"))
|
|
294
|
+
return EvaluationResult(**{key: value for key, value in data.items() if key in result_fields})
|