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/dsa.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Optional DSA integration for L3 deep analysis."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
|
|
12
|
+
from alphasift.models import Pick
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
_DEFAULT_ANALYZE_PATH = "/api/v1/analysis/analyze"
|
|
16
|
+
_ADVICE_SCORE_MAP = {
|
|
17
|
+
"强烈买入": 10.0,
|
|
18
|
+
"买入": 8.0,
|
|
19
|
+
"增持": 5.0,
|
|
20
|
+
"持有": 1.5,
|
|
21
|
+
"中性": 0.0,
|
|
22
|
+
"观望": -4.0,
|
|
23
|
+
"减持": -8.0,
|
|
24
|
+
"卖出": -12.0,
|
|
25
|
+
"回避": -12.0,
|
|
26
|
+
}
|
|
27
|
+
_TREND_SCORE_MAP = {
|
|
28
|
+
"看多": 4.0,
|
|
29
|
+
"震荡": 0.0,
|
|
30
|
+
"中性": 0.0,
|
|
31
|
+
"看空": -6.0,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def analyze_picks_with_dsa(
|
|
36
|
+
picks: list[Pick],
|
|
37
|
+
*,
|
|
38
|
+
run_id: str,
|
|
39
|
+
api_url: str,
|
|
40
|
+
report_type: str = "detailed",
|
|
41
|
+
max_picks: int = 3,
|
|
42
|
+
timeout_sec: float = 120.0,
|
|
43
|
+
force_refresh: bool = False,
|
|
44
|
+
notify: bool = False,
|
|
45
|
+
) -> tuple[list[Pick], list[str]]:
|
|
46
|
+
"""Run DSA deep analysis for the top picks and attach results in place."""
|
|
47
|
+
if not api_url:
|
|
48
|
+
raise ValueError("DSA_API_URL is required when deep_analysis=True")
|
|
49
|
+
if max_picks <= 0:
|
|
50
|
+
return picks, []
|
|
51
|
+
|
|
52
|
+
analyze_count = min(max_picks, len(picks))
|
|
53
|
+
degradation: list[str] = []
|
|
54
|
+
endpoint = build_dsa_analyze_url(api_url)
|
|
55
|
+
|
|
56
|
+
for idx, pick in enumerate(picks):
|
|
57
|
+
if idx >= analyze_count:
|
|
58
|
+
pick.deep_analysis_status = "skipped"
|
|
59
|
+
continue
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
result = call_dsa_analysis(
|
|
63
|
+
endpoint,
|
|
64
|
+
stock_code=pick.code,
|
|
65
|
+
stock_name=pick.name,
|
|
66
|
+
report_type=report_type,
|
|
67
|
+
query_id=f"{run_id}-{pick.rank}-{pick.code}",
|
|
68
|
+
timeout_sec=timeout_sec,
|
|
69
|
+
force_refresh=force_refresh,
|
|
70
|
+
notify=notify,
|
|
71
|
+
)
|
|
72
|
+
pick.deep_analysis_status = "completed"
|
|
73
|
+
pick.deep_analysis_query_id = str(result.get("query_id", ""))
|
|
74
|
+
pick.deep_analysis_result = result
|
|
75
|
+
pick.deep_analysis_summary = extract_deep_analysis_summary(result)
|
|
76
|
+
_attach_deep_analysis_fields(pick, result)
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
logger.warning("DSA deep analysis failed for %s: %s", pick.code, exc)
|
|
79
|
+
pick.deep_analysis_status = "failed"
|
|
80
|
+
pick.deep_analysis_error = str(exc)
|
|
81
|
+
degradation.append(f"DSA deep analysis failed for {pick.code}: {exc}")
|
|
82
|
+
|
|
83
|
+
return picks, degradation
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def build_dsa_analyze_url(api_url: str) -> str:
|
|
87
|
+
"""Accept a base URL or a full endpoint URL."""
|
|
88
|
+
stripped = api_url.rstrip("/")
|
|
89
|
+
parsed = urlparse(stripped)
|
|
90
|
+
if parsed.path and parsed.path not in ("", "/"):
|
|
91
|
+
return stripped
|
|
92
|
+
return f"{stripped}{_DEFAULT_ANALYZE_PATH}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_dsa_readiness(api_url: str, *, timeout_sec: float = 5.0) -> dict:
|
|
96
|
+
"""Best-effort DSA endpoint readiness probe for CLI/runtime diagnostics."""
|
|
97
|
+
if not api_url:
|
|
98
|
+
return {
|
|
99
|
+
"available": False,
|
|
100
|
+
"status": "missing_url",
|
|
101
|
+
"endpoint": "",
|
|
102
|
+
"http_status": None,
|
|
103
|
+
"error": "DSA_API_URL is not configured",
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
endpoint = build_dsa_analyze_url(api_url)
|
|
107
|
+
try:
|
|
108
|
+
response = requests.get(endpoint, timeout=timeout_sec)
|
|
109
|
+
except requests.RequestException as exc:
|
|
110
|
+
return {
|
|
111
|
+
"available": False,
|
|
112
|
+
"status": "unreachable",
|
|
113
|
+
"endpoint": endpoint,
|
|
114
|
+
"http_status": None,
|
|
115
|
+
"error": str(exc),
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
status_code = int(getattr(response, "status_code", 0) or 0)
|
|
119
|
+
if status_code in {200, 204, 405, 422}:
|
|
120
|
+
status = "route_present"
|
|
121
|
+
available = True
|
|
122
|
+
elif status_code in {401, 403}:
|
|
123
|
+
status = "unauthorized"
|
|
124
|
+
available = False
|
|
125
|
+
elif status_code == 404:
|
|
126
|
+
status = "route_missing"
|
|
127
|
+
available = False
|
|
128
|
+
else:
|
|
129
|
+
status = "unexpected_status"
|
|
130
|
+
available = False
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
"available": available,
|
|
134
|
+
"status": status,
|
|
135
|
+
"endpoint": endpoint,
|
|
136
|
+
"http_status": status_code,
|
|
137
|
+
"error": "" if available else _safe_str(getattr(response, "text", ""))[:280],
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def call_dsa_analysis(
|
|
142
|
+
endpoint: str,
|
|
143
|
+
*,
|
|
144
|
+
stock_code: str,
|
|
145
|
+
stock_name: str = "",
|
|
146
|
+
report_type: str = "detailed",
|
|
147
|
+
query_id: str = "",
|
|
148
|
+
timeout_sec: float = 120.0,
|
|
149
|
+
force_refresh: bool = False,
|
|
150
|
+
notify: bool = False,
|
|
151
|
+
) -> dict:
|
|
152
|
+
"""Call the DSA sync analysis endpoint and return parsed JSON."""
|
|
153
|
+
payload = {
|
|
154
|
+
"stock_code": stock_code,
|
|
155
|
+
"report_type": report_type,
|
|
156
|
+
"force_refresh": force_refresh,
|
|
157
|
+
"async_mode": False,
|
|
158
|
+
"stock_name": stock_name or None,
|
|
159
|
+
"original_query": stock_code,
|
|
160
|
+
"selection_source": "import",
|
|
161
|
+
"notify": notify,
|
|
162
|
+
}
|
|
163
|
+
if query_id:
|
|
164
|
+
# The current DSA public API does not require query_id,
|
|
165
|
+
# but we keep it in the payload for forward compatibility.
|
|
166
|
+
payload["query_id"] = query_id
|
|
167
|
+
|
|
168
|
+
response = requests.post(endpoint, json=payload, timeout=timeout_sec)
|
|
169
|
+
response.raise_for_status()
|
|
170
|
+
try:
|
|
171
|
+
body = response.json()
|
|
172
|
+
except ValueError:
|
|
173
|
+
return {"raw_text": response.text}
|
|
174
|
+
if not isinstance(body, dict):
|
|
175
|
+
return {"raw_result": body}
|
|
176
|
+
return body
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def extract_deep_analysis_summary(result: dict) -> str:
|
|
180
|
+
"""Best-effort extraction of a short summary from a DSA response."""
|
|
181
|
+
if not isinstance(result, dict):
|
|
182
|
+
return ""
|
|
183
|
+
|
|
184
|
+
for key in ("summary", "analysis_summary", "conclusion", "message"):
|
|
185
|
+
value = result.get(key)
|
|
186
|
+
if isinstance(value, str) and value.strip():
|
|
187
|
+
return value.strip()
|
|
188
|
+
|
|
189
|
+
report = result.get("report")
|
|
190
|
+
if isinstance(report, dict):
|
|
191
|
+
summary = report.get("summary")
|
|
192
|
+
if isinstance(summary, str) and summary.strip():
|
|
193
|
+
return summary.strip()
|
|
194
|
+
if isinstance(summary, dict):
|
|
195
|
+
for key in (
|
|
196
|
+
"analysis_summary",
|
|
197
|
+
"summary",
|
|
198
|
+
"conclusion",
|
|
199
|
+
"recommendation",
|
|
200
|
+
"operation_advice",
|
|
201
|
+
"signal_level",
|
|
202
|
+
):
|
|
203
|
+
value = summary.get(key)
|
|
204
|
+
if isinstance(value, str) and value.strip():
|
|
205
|
+
return value.strip()
|
|
206
|
+
rendered = json.dumps(summary, ensure_ascii=False)
|
|
207
|
+
return rendered[:280]
|
|
208
|
+
|
|
209
|
+
rendered = json.dumps(result, ensure_ascii=False)
|
|
210
|
+
return rendered[:280]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def apply_dsa_overlay(picks: list[Pick]) -> list[Pick]:
|
|
214
|
+
"""Use DSA structured output as the final low-frequency risk/alpha overlay."""
|
|
215
|
+
rescored: list[tuple[int, Pick]] = []
|
|
216
|
+
for idx, pick in enumerate(picks):
|
|
217
|
+
base_score = float(pick.final_score)
|
|
218
|
+
if pick.deep_analysis_status == "completed":
|
|
219
|
+
base_score += _compute_dsa_overlay_score(pick)
|
|
220
|
+
pick.final_score = round(base_score, 4)
|
|
221
|
+
rescored.append((idx, pick))
|
|
222
|
+
|
|
223
|
+
rescored.sort(key=lambda item: (-item[1].final_score, item[0]))
|
|
224
|
+
reranked = [pick for _, pick in rescored]
|
|
225
|
+
for i, pick in enumerate(reranked, start=1):
|
|
226
|
+
pick.rank = i
|
|
227
|
+
return reranked
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _attach_deep_analysis_fields(pick: Pick, result: dict) -> None:
|
|
231
|
+
summary = _extract_report_summary(result)
|
|
232
|
+
trend = _extract_trend_result(result)
|
|
233
|
+
|
|
234
|
+
pick.deep_analysis_signal_score = _safe_int(trend.get("signal_score"))
|
|
235
|
+
pick.deep_analysis_sentiment_score = _safe_int(summary.get("sentiment_score"))
|
|
236
|
+
pick.deep_analysis_operation_advice = _safe_str(summary.get("operation_advice"))
|
|
237
|
+
pick.deep_analysis_trend_prediction = _safe_str(summary.get("trend_prediction"))
|
|
238
|
+
pick.deep_analysis_risk_flags = _extract_risk_flags(trend)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _compute_dsa_overlay_score(pick: Pick) -> float:
|
|
242
|
+
score = 0.0
|
|
243
|
+
|
|
244
|
+
if pick.deep_analysis_signal_score is not None:
|
|
245
|
+
score += (pick.deep_analysis_signal_score - 50) * 0.20
|
|
246
|
+
if pick.deep_analysis_sentiment_score is not None:
|
|
247
|
+
score += (pick.deep_analysis_sentiment_score - 50) * 0.12
|
|
248
|
+
|
|
249
|
+
advice = pick.deep_analysis_operation_advice.strip()
|
|
250
|
+
score += _ADVICE_SCORE_MAP.get(advice, 0.0)
|
|
251
|
+
|
|
252
|
+
trend = pick.deep_analysis_trend_prediction.strip()
|
|
253
|
+
score += _TREND_SCORE_MAP.get(trend, 0.0)
|
|
254
|
+
|
|
255
|
+
if pick.deep_analysis_risk_flags:
|
|
256
|
+
score -= min(len(pick.deep_analysis_risk_flags) * 2.0, 6.0)
|
|
257
|
+
|
|
258
|
+
return score
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _extract_report_summary(result: dict) -> dict:
|
|
262
|
+
report = result.get("report")
|
|
263
|
+
if not isinstance(report, dict):
|
|
264
|
+
return {}
|
|
265
|
+
summary = report.get("summary")
|
|
266
|
+
return summary if isinstance(summary, dict) else {}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _extract_trend_result(result: dict) -> dict:
|
|
270
|
+
report = result.get("report")
|
|
271
|
+
if not isinstance(report, dict):
|
|
272
|
+
return {}
|
|
273
|
+
details = report.get("details")
|
|
274
|
+
if not isinstance(details, dict):
|
|
275
|
+
return {}
|
|
276
|
+
context_snapshot = details.get("context_snapshot")
|
|
277
|
+
if not isinstance(context_snapshot, dict):
|
|
278
|
+
return {}
|
|
279
|
+
trend = context_snapshot.get("trend_result")
|
|
280
|
+
return trend if isinstance(trend, dict) else {}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _extract_risk_flags(trend_result: dict) -> list[str]:
|
|
284
|
+
risks = trend_result.get("risk_factors")
|
|
285
|
+
if not isinstance(risks, list):
|
|
286
|
+
return []
|
|
287
|
+
return [str(item).strip() for item in risks if str(item).strip()]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _safe_int(value) -> int | None:
|
|
291
|
+
try:
|
|
292
|
+
if value is None or value == "":
|
|
293
|
+
return None
|
|
294
|
+
return int(value)
|
|
295
|
+
except (TypeError, ValueError):
|
|
296
|
+
return None
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _safe_str(value) -> str:
|
|
300
|
+
if value is None:
|
|
301
|
+
return ""
|
|
302
|
+
return str(value).strip()
|
alphasift/dsa_adapter.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Stable DSA integration adapter.
|
|
3
|
+
|
|
4
|
+
DSA should depend on this module instead of AlphaSift internal pipeline,
|
|
5
|
+
strategy, or model details. Keep this contract backward-compatible.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import asdict, is_dataclass
|
|
11
|
+
from typing import Any, Dict, List
|
|
12
|
+
|
|
13
|
+
from alphasift import __version__
|
|
14
|
+
from alphasift.pipeline import screen as run_screen
|
|
15
|
+
from alphasift.strategy import list_strategies as load_strategies
|
|
16
|
+
|
|
17
|
+
CONTRACT_VERSION = "1"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_contract_version() -> str:
|
|
21
|
+
"""Return the stable adapter contract version."""
|
|
22
|
+
return CONTRACT_VERSION
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_status(context: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
|
26
|
+
"""Return non-sensitive adapter status for DSA health checks."""
|
|
27
|
+
try:
|
|
28
|
+
strategies = list_strategies(context=context)
|
|
29
|
+
strategy_count = len(strategies)
|
|
30
|
+
available = True
|
|
31
|
+
error = ""
|
|
32
|
+
except Exception as exc: # pragma: no cover - defensive integration boundary
|
|
33
|
+
strategy_count = 0
|
|
34
|
+
available = False
|
|
35
|
+
error = str(exc)
|
|
36
|
+
|
|
37
|
+
payload: Dict[str, Any] = {
|
|
38
|
+
"available": available,
|
|
39
|
+
"version": __version__,
|
|
40
|
+
"contract_version": CONTRACT_VERSION,
|
|
41
|
+
"strategy_count": strategy_count,
|
|
42
|
+
}
|
|
43
|
+
if error:
|
|
44
|
+
payload["error"] = error
|
|
45
|
+
return payload
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def list_strategies(context: Dict[str, Any] | None = None) -> List[Dict[str, Any]]:
|
|
49
|
+
"""List enabled AlphaSift strategies using a DSA-stable shape."""
|
|
50
|
+
return [
|
|
51
|
+
{
|
|
52
|
+
"id": item.name,
|
|
53
|
+
"name": item.display_name,
|
|
54
|
+
"description": item.description,
|
|
55
|
+
"version": item.version,
|
|
56
|
+
"category": item.category,
|
|
57
|
+
"tags": list(item.tags),
|
|
58
|
+
"market_scope": list(item.market_scope),
|
|
59
|
+
}
|
|
60
|
+
for item in load_strategies()
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def screen(
|
|
65
|
+
strategy: str,
|
|
66
|
+
*,
|
|
67
|
+
market: str = "cn",
|
|
68
|
+
max_results: int = 20,
|
|
69
|
+
use_llm: bool = True,
|
|
70
|
+
context: Dict[str, Any] | None = None,
|
|
71
|
+
) -> Dict[str, Any]:
|
|
72
|
+
"""Run one screening request and return a stable DSA response."""
|
|
73
|
+
result = run_screen(
|
|
74
|
+
strategy,
|
|
75
|
+
market=market,
|
|
76
|
+
max_output=max_results,
|
|
77
|
+
use_llm=use_llm,
|
|
78
|
+
context=context,
|
|
79
|
+
)
|
|
80
|
+
picks = [_normalize_pick(item, index + 1) for index, item in enumerate(result.picks)]
|
|
81
|
+
return {
|
|
82
|
+
"source": "alphasift",
|
|
83
|
+
"contract_version": CONTRACT_VERSION,
|
|
84
|
+
"run_id": result.run_id,
|
|
85
|
+
"strategy": result.strategy,
|
|
86
|
+
"strategy_version": result.strategy_version,
|
|
87
|
+
"strategy_category": result.strategy_category,
|
|
88
|
+
"market": result.market,
|
|
89
|
+
"snapshot_count": result.snapshot_count,
|
|
90
|
+
"after_filter_count": result.after_filter_count,
|
|
91
|
+
"llm_ranked": result.llm_ranked,
|
|
92
|
+
"llm_market_view": result.llm_market_view,
|
|
93
|
+
"llm_selection_logic": result.llm_selection_logic,
|
|
94
|
+
"llm_portfolio_risk": result.llm_portfolio_risk,
|
|
95
|
+
"llm_coverage": result.llm_coverage,
|
|
96
|
+
"llm_parse_errors": list(result.llm_parse_errors),
|
|
97
|
+
"candidate_count": len(picks),
|
|
98
|
+
"candidates": picks,
|
|
99
|
+
"warnings": list(result.degradation),
|
|
100
|
+
"source_errors": list(result.source_errors),
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _normalize_pick(raw: Any, fallback_rank: int) -> Dict[str, Any]:
|
|
105
|
+
item = _to_plain(raw)
|
|
106
|
+
if not isinstance(item, dict):
|
|
107
|
+
item = {"code": str(item)}
|
|
108
|
+
score = item.get("final_score")
|
|
109
|
+
if score is None:
|
|
110
|
+
score = item.get("screen_score")
|
|
111
|
+
reason = item.get("llm_thesis") or item.get("ranking_reason") or item.get("risk_summary") or _build_reason(item)
|
|
112
|
+
return {
|
|
113
|
+
"rank": item.get("rank") or fallback_rank,
|
|
114
|
+
"code": item.get("code") or item.get("symbol") or item.get("stock_code") or "",
|
|
115
|
+
"name": item.get("name") or item.get("stock_name") or "",
|
|
116
|
+
"score": score,
|
|
117
|
+
"screen_score": item.get("screen_score"),
|
|
118
|
+
"reason": reason,
|
|
119
|
+
"risk_level": item.get("risk_level") or "",
|
|
120
|
+
"risk_flags": list(item.get("risk_flags") or []),
|
|
121
|
+
"llm_score": item.get("llm_score"),
|
|
122
|
+
"llm_confidence": item.get("llm_confidence"),
|
|
123
|
+
"llm_sector": item.get("llm_sector") or "",
|
|
124
|
+
"llm_theme": item.get("llm_theme") or "",
|
|
125
|
+
"llm_tags": list(item.get("llm_tags") or []),
|
|
126
|
+
"llm_thesis": item.get("llm_thesis") or "",
|
|
127
|
+
"llm_catalysts": list(item.get("llm_catalysts") or []),
|
|
128
|
+
"llm_risks": list(item.get("llm_risks") or []),
|
|
129
|
+
"llm_watch_items": list(item.get("llm_watch_items") or []),
|
|
130
|
+
"llm_invalidators": list(item.get("llm_invalidators") or []),
|
|
131
|
+
"llm_style_fit": item.get("llm_style_fit") or "",
|
|
132
|
+
"price": item.get("price"),
|
|
133
|
+
"change_pct": item.get("change_pct"),
|
|
134
|
+
"amount": item.get("amount"),
|
|
135
|
+
"industry": item.get("industry") or "",
|
|
136
|
+
"factor_scores": dict(item.get("factor_scores") or {}),
|
|
137
|
+
"dsa_context": dict(item.get("dsa_context") or {}),
|
|
138
|
+
"dsa_news": list(item.get("dsa_news") or []),
|
|
139
|
+
"dsa_analysis_summary": item.get("dsa_analysis_summary") or "",
|
|
140
|
+
"post_analysis_summaries": dict(item.get("post_analysis_summaries") or {}),
|
|
141
|
+
"post_analysis_tags": list(item.get("post_analysis_tags") or []),
|
|
142
|
+
"raw": item,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _build_reason(item: Dict[str, Any]) -> str:
|
|
147
|
+
summaries = item.get("post_analysis_summaries") or {}
|
|
148
|
+
if isinstance(summaries, dict):
|
|
149
|
+
summary = next((str(value) for value in summaries.values() if value), "")
|
|
150
|
+
if summary:
|
|
151
|
+
return summary
|
|
152
|
+
|
|
153
|
+
parts: List[str] = []
|
|
154
|
+
factors = item.get("factor_scores") or {}
|
|
155
|
+
if isinstance(factors, dict):
|
|
156
|
+
top_factors = sorted(
|
|
157
|
+
((key, value) for key, value in factors.items() if isinstance(value, (int, float))),
|
|
158
|
+
key=lambda pair: pair[1],
|
|
159
|
+
reverse=True,
|
|
160
|
+
)[:3]
|
|
161
|
+
if top_factors:
|
|
162
|
+
factor_text = ", ".join(f"{key} {value:.1f}" for key, value in top_factors)
|
|
163
|
+
parts.append(f"Top factors: {factor_text}")
|
|
164
|
+
if item.get("industry"):
|
|
165
|
+
parts.append(f"Industry: {item['industry']}")
|
|
166
|
+
if item.get("risk_level"):
|
|
167
|
+
parts.append(f"Risk level: {item['risk_level']}")
|
|
168
|
+
return "; ".join(parts)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _to_plain(value: Any) -> Any:
|
|
172
|
+
if is_dataclass(value):
|
|
173
|
+
return asdict(value)
|
|
174
|
+
if hasattr(value, "model_dump"):
|
|
175
|
+
return value.model_dump()
|
|
176
|
+
if hasattr(value, "dict") and callable(value.dict):
|
|
177
|
+
return value.dict()
|
|
178
|
+
return value
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""DSA provider-context bridge.
|
|
3
|
+
|
|
4
|
+
This module consumes DSA-owned callables passed through ``context["dsa"]``.
|
|
5
|
+
It is intentionally best-effort: AlphaSift can use richer DSA data when
|
|
6
|
+
available, but screening should continue when one provider is slow or broken.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Any, Callable
|
|
13
|
+
|
|
14
|
+
from alphasift.models import Pick
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
DSA_PROVIDER_MAX_CANDIDATES = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def apply_dsa_provider_context(
|
|
22
|
+
picks: list[Pick],
|
|
23
|
+
context: dict[str, Any] | None,
|
|
24
|
+
*,
|
|
25
|
+
max_candidates: int = DSA_PROVIDER_MAX_CANDIDATES,
|
|
26
|
+
) -> list[str]:
|
|
27
|
+
"""Attach DSA context to top candidates before LLM ranking."""
|
|
28
|
+
provider = _extract_provider_context(context)
|
|
29
|
+
if not picks or not provider:
|
|
30
|
+
return []
|
|
31
|
+
|
|
32
|
+
limit = min(len(picks), max(max_candidates, 0))
|
|
33
|
+
if limit <= 0:
|
|
34
|
+
return []
|
|
35
|
+
|
|
36
|
+
enriched_count = 0
|
|
37
|
+
errors: list[str] = []
|
|
38
|
+
for pick in picks[:limit]:
|
|
39
|
+
try:
|
|
40
|
+
payload = _fetch_candidate_context(provider, pick)
|
|
41
|
+
if not payload:
|
|
42
|
+
continue
|
|
43
|
+
normalized = _normalize_candidate_payload(payload, pick)
|
|
44
|
+
if not normalized:
|
|
45
|
+
continue
|
|
46
|
+
pick.dsa_context = normalized["context"]
|
|
47
|
+
pick.dsa_news = normalized["news"]
|
|
48
|
+
pick.dsa_analysis_summary = normalized["summary"]
|
|
49
|
+
if _is_enriched_context(pick.dsa_context, pick.dsa_news):
|
|
50
|
+
enriched_count += 1
|
|
51
|
+
except Exception as exc: # noqa: BLE001 - external DSA providers are optional.
|
|
52
|
+
message = f"{pick.code}: {exc}"
|
|
53
|
+
errors.append(message)
|
|
54
|
+
pick.dsa_context = {
|
|
55
|
+
"enriched": False,
|
|
56
|
+
"warnings": [message],
|
|
57
|
+
}
|
|
58
|
+
logger.warning("DSA provider context failed for %s: %s", pick.code, exc)
|
|
59
|
+
|
|
60
|
+
notes = [f"DSA provider context applied {enriched_count} of {limit} candidates"]
|
|
61
|
+
if errors:
|
|
62
|
+
sample = " | ".join(errors[:5])
|
|
63
|
+
suffix = f" | +{len(errors) - 5} more" if len(errors) > 5 else ""
|
|
64
|
+
notes.append(f"DSA provider context row errors: {sample}{suffix}")
|
|
65
|
+
return notes
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _extract_provider_context(context: dict[str, Any] | None) -> dict[str, Any]:
|
|
69
|
+
if not isinstance(context, dict):
|
|
70
|
+
return {}
|
|
71
|
+
provider = context.get("dsa")
|
|
72
|
+
return provider if isinstance(provider, dict) else {}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _fetch_candidate_context(provider: dict[str, Any], pick: Pick) -> dict[str, Any]:
|
|
76
|
+
candidate_getter = provider.get("get_candidate_context")
|
|
77
|
+
if callable(candidate_getter):
|
|
78
|
+
payload = _call_candidate_getter(candidate_getter, pick)
|
|
79
|
+
return payload if isinstance(payload, dict) else {}
|
|
80
|
+
|
|
81
|
+
quote = _call_optional_provider(provider.get("get_realtime_quote"), pick.code)
|
|
82
|
+
fundamentals = _call_optional_provider(provider.get("get_fundamental_context"), pick.code)
|
|
83
|
+
news = _call_news_provider(provider.get("search_stock_news"), pick)
|
|
84
|
+
return {
|
|
85
|
+
"enriched": bool(quote or fundamentals or _news_results(news)),
|
|
86
|
+
"quote": quote,
|
|
87
|
+
"fundamentals": fundamentals,
|
|
88
|
+
"news": news,
|
|
89
|
+
"warnings": [],
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _call_candidate_getter(getter: Callable[..., Any], pick: Pick) -> Any:
|
|
94
|
+
try:
|
|
95
|
+
return getter(pick.code, pick.name)
|
|
96
|
+
except TypeError:
|
|
97
|
+
return getter(pick.code)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _call_optional_provider(provider: Any, stock_code: str) -> dict[str, Any]:
|
|
101
|
+
if not callable(provider):
|
|
102
|
+
return {}
|
|
103
|
+
payload = provider(stock_code)
|
|
104
|
+
return payload if isinstance(payload, dict) else {}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _call_news_provider(provider: Any, pick: Pick) -> dict[str, Any]:
|
|
108
|
+
if not callable(provider):
|
|
109
|
+
return {"success": False, "results": []}
|
|
110
|
+
try:
|
|
111
|
+
payload = provider(pick.code, pick.name, max_results=3)
|
|
112
|
+
except TypeError:
|
|
113
|
+
try:
|
|
114
|
+
payload = provider(pick.code, pick.name)
|
|
115
|
+
except TypeError:
|
|
116
|
+
payload = provider(pick.code)
|
|
117
|
+
return payload if isinstance(payload, dict) else {"success": False, "results": []}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _normalize_candidate_payload(payload: dict[str, Any], pick: Pick) -> dict[str, Any]:
|
|
121
|
+
full_payload = payload
|
|
122
|
+
context = payload.get("dsa_context") if isinstance(payload.get("dsa_context"), dict) else payload
|
|
123
|
+
if not isinstance(context, dict):
|
|
124
|
+
return {}
|
|
125
|
+
|
|
126
|
+
news = payload.get("dsa_news")
|
|
127
|
+
if not isinstance(news, list):
|
|
128
|
+
news = _news_results(context.get("news"))
|
|
129
|
+
news = [item for item in news if isinstance(item, dict)]
|
|
130
|
+
|
|
131
|
+
summary = str(payload.get("dsa_analysis_summary") or "").strip()
|
|
132
|
+
if not summary:
|
|
133
|
+
summary = _build_dsa_summary(pick, context, news)
|
|
134
|
+
|
|
135
|
+
normalized_context = dict(context)
|
|
136
|
+
normalized_context.setdefault("enriched", _is_enriched_context(normalized_context, news))
|
|
137
|
+
if full_payload is not context and "dsa_context" in full_payload:
|
|
138
|
+
normalized_context.setdefault("source_payload", "dsa_candidate_context")
|
|
139
|
+
return {
|
|
140
|
+
"context": normalized_context,
|
|
141
|
+
"news": news,
|
|
142
|
+
"summary": summary,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _is_enriched_context(context: dict[str, Any], news: list[dict[str, Any]]) -> bool:
|
|
147
|
+
return bool(
|
|
148
|
+
context.get("enriched")
|
|
149
|
+
or context.get("quote")
|
|
150
|
+
or context.get("fundamentals")
|
|
151
|
+
or news
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _news_results(news_payload: Any) -> list[dict[str, Any]]:
|
|
156
|
+
if isinstance(news_payload, dict) and isinstance(news_payload.get("results"), list):
|
|
157
|
+
return [item for item in news_payload["results"] if isinstance(item, dict)]
|
|
158
|
+
if isinstance(news_payload, list):
|
|
159
|
+
return [item for item in news_payload if isinstance(item, dict)]
|
|
160
|
+
return []
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _build_dsa_summary(pick: Pick, context: dict[str, Any], news: list[dict[str, Any]]) -> str:
|
|
164
|
+
parts: list[str] = []
|
|
165
|
+
quote = context.get("quote") if isinstance(context.get("quote"), dict) else {}
|
|
166
|
+
price = quote.get("price") if quote else pick.price
|
|
167
|
+
change_pct = quote.get("change_pct") if quote else pick.change_pct
|
|
168
|
+
if price not in (None, ""):
|
|
169
|
+
text = f"DSA行情: 现价 {price}"
|
|
170
|
+
if change_pct not in (None, ""):
|
|
171
|
+
text += f", 涨跌幅 {change_pct}%"
|
|
172
|
+
parts.append(text)
|
|
173
|
+
|
|
174
|
+
fundamentals = context.get("fundamentals")
|
|
175
|
+
coverage = fundamentals.get("coverage") if isinstance(fundamentals, dict) else {}
|
|
176
|
+
if isinstance(coverage, dict):
|
|
177
|
+
available = [
|
|
178
|
+
str(key)
|
|
179
|
+
for key, value in coverage.items()
|
|
180
|
+
if str(value).lower() in {"available", "partial"}
|
|
181
|
+
]
|
|
182
|
+
if available:
|
|
183
|
+
parts.append(f"DSA基本面覆盖: {', '.join(available[:4])}")
|
|
184
|
+
|
|
185
|
+
titles = [
|
|
186
|
+
str(item.get("title") or "").strip()
|
|
187
|
+
for item in news
|
|
188
|
+
if isinstance(item.get("title"), str) and item.get("title")
|
|
189
|
+
]
|
|
190
|
+
if titles:
|
|
191
|
+
parts.append(f"DSA新闻: {'; '.join(titles[:2])}")
|
|
192
|
+
return "; ".join(parts)
|