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/llm_client.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""OpenAI-compatible chat completion and ordered endpoint resolution."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from http import HTTPStatus
|
|
8
|
+
|
|
9
|
+
from urllib.parse import quote, urlsplit
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_DASHSCOPE = ("https://dashscope.aliyuncs.com/compatible-mode/v1", ("DASHSCOPE_API_KEY", "QWEN_API_KEY"))
|
|
16
|
+
_GATEWAYS = {
|
|
17
|
+
"openai": ("https://api.openai.com/v1", ("OPENAI_API_KEY",)),
|
|
18
|
+
"deepseek": ("https://api.deepseek.com", ("DEEPSEEK_API_KEY",)),
|
|
19
|
+
"gemini": ("https://generativelanguage.googleapis.com/v1beta/openai", ("GEMINI_API_KEY",)),
|
|
20
|
+
"anthropic": ("https://api.anthropic.com/v1", ("ANTHROPIC_API_KEY",)),
|
|
21
|
+
"ollama": ("http://localhost:11434/v1", ()),
|
|
22
|
+
"openrouter": ("https://openrouter.ai/api/v1", ("OPENROUTER_API_KEY",)),
|
|
23
|
+
"dashscope": _DASHSCOPE,
|
|
24
|
+
"qwen": _DASHSCOPE,
|
|
25
|
+
"zhipu": ("https://open.bigmodel.cn/api/paas/v4", ("ZHIPU_API_KEY", "ZAI_API_KEY")),
|
|
26
|
+
"moonshot": ("https://api.moonshot.cn/v1", ("MOONSHOT_API_KEY",)),
|
|
27
|
+
"aihubmix": ("https://aihubmix.com/v1", ("AIHUBMIX_KEY", "AIHUBMIX_API_KEY")),
|
|
28
|
+
}
|
|
29
|
+
_BASE_URL_ENV = {
|
|
30
|
+
"openai": "OPENAI_BASE_URL",
|
|
31
|
+
"ollama": "OLLAMA_API_BASE",
|
|
32
|
+
"aihubmix": "AIHUBMIX_BASE_URL",
|
|
33
|
+
}
|
|
34
|
+
_CHANNEL_PROTOCOLS = _GATEWAYS.keys() - {"anthropic"}
|
|
35
|
+
_NATIVE_PROVIDER_HOSTS: dict[str, str] = {
|
|
36
|
+
(urlsplit(info[0]).hostname or "").lower(): ("dashscope" if prov == "qwen" else prov)
|
|
37
|
+
for prov, info in _GATEWAYS.items()
|
|
38
|
+
if prov not in {"openai", "openrouter", "aihubmix"} and urlsplit(info[0]).hostname
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _is_foreign_gateway_url(url: str, provider: str) -> bool:
|
|
43
|
+
"""Return True when ``url`` is a different vendor's native gateway hostname."""
|
|
44
|
+
host = (urlsplit(str(url or "").strip()).hostname or "").lower()
|
|
45
|
+
owner = _NATIVE_PROVIDER_HOSTS.get(host) if host else None
|
|
46
|
+
if not owner:
|
|
47
|
+
return False
|
|
48
|
+
norm_prov = "dashscope" if provider == "qwen" else provider
|
|
49
|
+
return owner != norm_prov
|
|
50
|
+
_SECRET_LIKE = re.compile(
|
|
51
|
+
r"(?i)(?:bearer\s+\S+"
|
|
52
|
+
r"|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"
|
|
53
|
+
r"|[0-9a-f]{12,}\.[A-Za-z0-9_-]{10,}"
|
|
54
|
+
r"|\b(?:sk|pk|rk|key)-[\w-]{8,}"
|
|
55
|
+
r"|\bAIza[\w-]{16,}"
|
|
56
|
+
r"|\b(?:access_token|token|key|secret|password|api_key)\s*[=:]\s*['\"]?[^\s&,'\"\}\]]+['\"]?"
|
|
57
|
+
r"|\b[\w-]{32,}\b)"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class LLMClientError(RuntimeError):
|
|
62
|
+
"""An LLM failure with a safe message and an HTTP status when available."""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
message: str,
|
|
67
|
+
*,
|
|
68
|
+
status_code: int | None = None,
|
|
69
|
+
timed_out: bool = False,
|
|
70
|
+
json_mode_rejected: bool = False,
|
|
71
|
+
truncated: bool = False,
|
|
72
|
+
partial_content: str = "",
|
|
73
|
+
max_tokens: int | None = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
super().__init__(message)
|
|
76
|
+
self.status_code = status_code
|
|
77
|
+
self.timed_out = timed_out
|
|
78
|
+
self.json_mode_rejected = json_mode_rejected
|
|
79
|
+
# The completion ran out of output budget: ``partial_content`` holds any
|
|
80
|
+
# text emitted before the cut, ``max_tokens`` the budget actually sent.
|
|
81
|
+
self.truncated = truncated
|
|
82
|
+
self.partial_content = partial_content
|
|
83
|
+
self.max_tokens = max_tokens
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
DEFAULT_LLM_MAX_TOKENS = 8192
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class LLMAttempt:
|
|
91
|
+
base_url: str = field(repr=False)
|
|
92
|
+
model: str
|
|
93
|
+
api_key: str = field(repr=False)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def normalize_model(model: str, protocol: str = "openai") -> str:
|
|
97
|
+
model = model.strip()
|
|
98
|
+
if protocol == "openrouter" and not model.startswith("openrouter/"):
|
|
99
|
+
return f"openrouter/{model}"
|
|
100
|
+
if "/" in model:
|
|
101
|
+
return model
|
|
102
|
+
return f"{protocol}/{model}" if protocol in _GATEWAYS else f"openai/{model}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def split_model(model: str) -> tuple[str, str]:
|
|
106
|
+
prefix, slash, name = model.partition("/")
|
|
107
|
+
if slash and prefix in _GATEWAYS:
|
|
108
|
+
return ("dashscope" if prefix == "qwen" else prefix), name
|
|
109
|
+
return "openai", model
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def gateway_api_keys(provider: str) -> list[str]:
|
|
113
|
+
if provider == "gemini":
|
|
114
|
+
value = os.getenv("GEMINI_API_KEYS", "").strip()
|
|
115
|
+
if value.lower() not in {"", "0", "false", "none", "off"}:
|
|
116
|
+
keys = [key.strip() for key in value.split(",") if key.strip()]
|
|
117
|
+
if keys:
|
|
118
|
+
return keys
|
|
119
|
+
for name in _GATEWAYS[provider][1]:
|
|
120
|
+
if key := os.getenv(name, "").strip():
|
|
121
|
+
return [key]
|
|
122
|
+
return []
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def gateway_base_url(provider: str, override: str = "") -> str:
|
|
126
|
+
env_name = _BASE_URL_ENV.get(provider)
|
|
127
|
+
configured_url = os.getenv(env_name, "").strip() if env_name else ""
|
|
128
|
+
url = (override.strip() or configured_url or _GATEWAYS[provider][0]).rstrip("/")
|
|
129
|
+
if provider == "ollama" and not url.endswith("/v1"):
|
|
130
|
+
url += "/v1"
|
|
131
|
+
return url
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def configuration_error(channels: list[dict[str, object]], config_path: str) -> str:
|
|
135
|
+
if config_path:
|
|
136
|
+
return (
|
|
137
|
+
"LITELLM_CONFIG (Router YAML) is unsupported. Unset LITELLM_CONFIG and migrate each "
|
|
138
|
+
"route to LLM_CHANNELS=primary,backup with LLM_PRIMARY_PROTOCOL=openai, "
|
|
139
|
+
"LLM_PRIMARY_BASE_URL=<OpenAI-compatible base URL>, LLM_PRIMARY_API_KEY=<key> "
|
|
140
|
+
"(or LLM_PRIMARY_API_KEYS=<key1,key2>), and LLM_PRIMARY_MODELS=<model>. "
|
|
141
|
+
"Repeat with LLM_BACKUP_* for the next route."
|
|
142
|
+
)
|
|
143
|
+
if any(str(channel.get("protocol", "openai")) not in _CHANNEL_PROTOCOLS for channel in channels):
|
|
144
|
+
return (
|
|
145
|
+
"Unsupported LLM channel protocol. Set LLM_<NAME>_PROTOCOL=openai and "
|
|
146
|
+
"LLM_<NAME>_BASE_URL to an OpenAI-compatible endpoint. For Claude, use "
|
|
147
|
+
"https://api.anthropic.com/v1."
|
|
148
|
+
)
|
|
149
|
+
return ""
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def build_attempts(
|
|
153
|
+
model: str,
|
|
154
|
+
*,
|
|
155
|
+
api_key: str,
|
|
156
|
+
base_url: str,
|
|
157
|
+
channels: list[dict[str, object]],
|
|
158
|
+
fallback_models: list[str],
|
|
159
|
+
) -> list[LLMAttempt]:
|
|
160
|
+
"""Try the primary model, remaining channel models, then direct fallbacks."""
|
|
161
|
+
primary_provider, primary_name = split_model(model)
|
|
162
|
+
primary_keys = gateway_api_keys(primary_provider)
|
|
163
|
+
if api_key and (
|
|
164
|
+
primary_provider != "gemini" or primary_keys[:1] != [api_key] or os.getenv("LLM_API_KEY", "").strip()
|
|
165
|
+
):
|
|
166
|
+
primary_keys = [api_key]
|
|
167
|
+
|
|
168
|
+
def direct_attempts(candidate: str) -> list[LLMAttempt]:
|
|
169
|
+
provider, name = split_model(candidate)
|
|
170
|
+
same_provider = provider == primary_provider
|
|
171
|
+
url = gateway_base_url(provider, base_url if same_provider else "")
|
|
172
|
+
# Never forward an OpenAI fallback model (e.g. gpt-4o) to OPENAI_BASE_URL when
|
|
173
|
+
# OPENAI_BASE_URL points at a non-OpenAI native gateway (e.g. api.deepseek.com).
|
|
174
|
+
if not same_provider and provider == "openai" and _is_foreign_gateway_url(url, provider):
|
|
175
|
+
return []
|
|
176
|
+
keys = primary_keys if same_provider else gateway_api_keys(provider)
|
|
177
|
+
if not keys and (provider == "ollama" or (same_provider and base_url)):
|
|
178
|
+
keys = [""]
|
|
179
|
+
return [LLMAttempt(url, name, key) for key in keys if name]
|
|
180
|
+
|
|
181
|
+
primary_channels: list[LLMAttempt] = []
|
|
182
|
+
remaining_channels: list[LLMAttempt] = []
|
|
183
|
+
for channel in channels:
|
|
184
|
+
protocol = str(channel.get("protocol", "openai"))
|
|
185
|
+
models = channel.get("models")
|
|
186
|
+
channel_keys = channel.get("api_keys")
|
|
187
|
+
channel_url = str(channel.get("base_url") or "")
|
|
188
|
+
for value in models if isinstance(models, list) else []:
|
|
189
|
+
provider, name = split_model(normalize_model(str(value), protocol))
|
|
190
|
+
same_provider = provider == primary_provider
|
|
191
|
+
default_origin = _GATEWAYS.get(provider, ("", ()))[0].rstrip("/")
|
|
192
|
+
url = gateway_base_url(provider, channel_url or (base_url if same_provider else ""))
|
|
193
|
+
explicit_keys = [str(k or "") for k in channel_keys] if isinstance(channel_keys, list) else []
|
|
194
|
+
keys: list[str]
|
|
195
|
+
if explicit_keys:
|
|
196
|
+
keys = explicit_keys
|
|
197
|
+
elif not channel_url or url.rstrip("/") == default_origin or provider == "ollama":
|
|
198
|
+
keys = (primary_keys if same_provider else gateway_api_keys(provider)) or [""]
|
|
199
|
+
else:
|
|
200
|
+
# Custom third-party channel URL without explicit channel keys must NOT
|
|
201
|
+
# receive unrelated provider gateway keys by ambient inheritance.
|
|
202
|
+
keys = [""]
|
|
203
|
+
target = primary_channels if name == primary_name else remaining_channels
|
|
204
|
+
target.extend(LLMAttempt(url, name, key) for key in keys if name)
|
|
205
|
+
|
|
206
|
+
attempts = [*primary_channels, *direct_attempts(model), *remaining_channels]
|
|
207
|
+
for fallback in fallback_models:
|
|
208
|
+
attempts.extend(direct_attempts(fallback.strip()))
|
|
209
|
+
return list(dict.fromkeys(attempts))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _validated_endpoint(base_url: str) -> str:
|
|
213
|
+
cleaned = str(base_url or "").strip()
|
|
214
|
+
parsed = urlsplit(cleaned)
|
|
215
|
+
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
|
|
216
|
+
raise LLMClientError("Invalid LLM endpoint URL")
|
|
217
|
+
if parsed.username or parsed.password:
|
|
218
|
+
raise LLMClientError("Invalid LLM endpoint URL: embedded credentials disallowed")
|
|
219
|
+
if parsed.query or parsed.fragment or "?" in cleaned or "#" in cleaned:
|
|
220
|
+
raise LLMClientError("Invalid LLM endpoint URL: query and fragment disallowed")
|
|
221
|
+
return cleaned.rstrip("/")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def supports_reasoning_effort(attempt: LLMAttempt) -> bool:
|
|
225
|
+
"""Return True when endpoint/model expects or supports OpenAI ``reasoning_effort``."""
|
|
226
|
+
url_l = str(attempt.base_url or "").lower()
|
|
227
|
+
model_l = str(attempt.model or "").lower()
|
|
228
|
+
if "generativelanguage.googleapis.com" in url_l and ("gemini-2.5" in model_l or "gemini-3" in model_l):
|
|
229
|
+
return True
|
|
230
|
+
return model_l.startswith(("o1", "o3", "o4", "gpt-5"))
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def complete(
|
|
234
|
+
attempt: LLMAttempt,
|
|
235
|
+
*,
|
|
236
|
+
messages: list[dict[str, str]],
|
|
237
|
+
temperature: float,
|
|
238
|
+
max_tokens: int | None = None,
|
|
239
|
+
response_format: dict[str, str] | None = None,
|
|
240
|
+
reasoning_effort: str | None = None,
|
|
241
|
+
timeout: float = 60.0,
|
|
242
|
+
silent: bool = True,
|
|
243
|
+
) -> str:
|
|
244
|
+
"""Make one request and return the first assistant message's text."""
|
|
245
|
+
endpoint_base = _validated_endpoint(attempt.base_url)
|
|
246
|
+
payload: dict[str, object] = {"model": attempt.model, "messages": messages, "temperature": temperature}
|
|
247
|
+
eff_tokens: int | None = None
|
|
248
|
+
if max_tokens is not None and int(max_tokens) > 0:
|
|
249
|
+
eff_tokens = int(max_tokens)
|
|
250
|
+
payload["max_tokens"] = eff_tokens
|
|
251
|
+
if reasoning_effort and supports_reasoning_effort(attempt):
|
|
252
|
+
payload["reasoning_effort"] = str(reasoning_effort)
|
|
253
|
+
if response_format is not None:
|
|
254
|
+
payload["response_format"] = response_format
|
|
255
|
+
headers = {"Authorization": f"Bearer {attempt.api_key}"} if attempt.api_key else {}
|
|
256
|
+
try:
|
|
257
|
+
response = requests.post(
|
|
258
|
+
f"{endpoint_base}/chat/completions",
|
|
259
|
+
headers=headers,
|
|
260
|
+
json=payload,
|
|
261
|
+
timeout=timeout,
|
|
262
|
+
allow_redirects=False,
|
|
263
|
+
)
|
|
264
|
+
except requests.RequestException as exc:
|
|
265
|
+
# Requests can wrap a body read timeout in ConnectionError or ChunkedEncodingError.
|
|
266
|
+
if isinstance(exc, requests.Timeout) or "timed out" in str(exc).lower():
|
|
267
|
+
raise LLMClientError("LLM request timed out", timed_out=True) from None
|
|
268
|
+
raise LLMClientError("LLM HTTP request failed") from None
|
|
269
|
+
|
|
270
|
+
status = response.status_code
|
|
271
|
+
if not silent:
|
|
272
|
+
logger.debug("LLM HTTP status %d", status)
|
|
273
|
+
if not 200 <= status < 300:
|
|
274
|
+
raise _response_error(response, check_json_mode=response_format is not None, api_key=attempt.api_key)
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
choice = response.json()["choices"][0]
|
|
278
|
+
message = choice["message"]
|
|
279
|
+
if not isinstance(message, dict) or ("content" not in message and "reasoning_content" not in message):
|
|
280
|
+
raise KeyError("content")
|
|
281
|
+
content = message.get("content")
|
|
282
|
+
except (ValueError, KeyError, IndexError, TypeError):
|
|
283
|
+
raise LLMClientError("Invalid LLM chat completion response", status_code=status) from None
|
|
284
|
+
if content is None or isinstance(content, str):
|
|
285
|
+
text = content or ""
|
|
286
|
+
finish_reason = str(choice.get("finish_reason") or "").strip().lower()
|
|
287
|
+
reasoning = message.get("reasoning_content") if isinstance(message, dict) else None
|
|
288
|
+
# A reasoning model can spend the whole budget before answering (empty
|
|
289
|
+
# content) or be cut off mid-answer; both look like an ordinary bad
|
|
290
|
+
# response unless finish_reason is checked.
|
|
291
|
+
if finish_reason == "length" or (
|
|
292
|
+
not text.strip() and isinstance(reasoning, str) and reasoning.strip()
|
|
293
|
+
):
|
|
294
|
+
raise LLMClientError(
|
|
295
|
+
f"LLM completion truncated (finish_reason={finish_reason or 'unknown'}, "
|
|
296
|
+
f"max_tokens={eff_tokens if eff_tokens is not None else 'unset'})",
|
|
297
|
+
status_code=status,
|
|
298
|
+
truncated=True,
|
|
299
|
+
partial_content=text if text.strip() else "",
|
|
300
|
+
max_tokens=eff_tokens,
|
|
301
|
+
)
|
|
302
|
+
if not isinstance(content, str):
|
|
303
|
+
raise LLMClientError("Invalid LLM assistant text", status_code=status)
|
|
304
|
+
if not content.strip():
|
|
305
|
+
raise LLMClientError("Empty LLM chat completion content", status_code=status)
|
|
306
|
+
return content
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _provider_reason(response: requests.Response, api_key: str) -> str:
|
|
310
|
+
"""Return the provider's short error message with the key redacted, or ''."""
|
|
311
|
+
try:
|
|
312
|
+
body = response.json()
|
|
313
|
+
except ValueError:
|
|
314
|
+
return ""
|
|
315
|
+
if isinstance(body, list) and body:
|
|
316
|
+
body = body[0]
|
|
317
|
+
error = body.get("error", body) if isinstance(body, dict) else None
|
|
318
|
+
reason = error.get("message") if isinstance(error, dict) else error
|
|
319
|
+
if not isinstance(reason, str):
|
|
320
|
+
return ""
|
|
321
|
+
reason = " ".join(reason.split())
|
|
322
|
+
if api_key:
|
|
323
|
+
reason = reason.replace(api_key, "***")
|
|
324
|
+
encoded = quote(api_key, safe="")
|
|
325
|
+
if encoded:
|
|
326
|
+
reason = reason.replace(encoded, "***")
|
|
327
|
+
# A relay can echo a credential other than ours, so also mask anything key-shaped.
|
|
328
|
+
return _SECRET_LIKE.sub("***", reason)[:180]
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _response_error(response: requests.Response, *, check_json_mode: bool, api_key: str = "") -> LLMClientError:
|
|
332
|
+
status = response.status_code
|
|
333
|
+
timed_out = status in (408, 504)
|
|
334
|
+
# Error bodies can echo credentials and prompts: classify on the raw text, but only
|
|
335
|
+
# surface the provider's short message field, truncated and with the key redacted.
|
|
336
|
+
detail = response.text.lower() if check_json_mode and status in (400, 415, 422) else ""
|
|
337
|
+
rejected = (
|
|
338
|
+
("response_format" in detail or "json_object" in detail or "json mode" in detail)
|
|
339
|
+
and any(tok in detail for tok in ("unsupported", "not support", "invalid", "unrecognized", "unknown", "disabled", "disallowed"))
|
|
340
|
+
)
|
|
341
|
+
try:
|
|
342
|
+
message = f"LLM HTTP {status} {HTTPStatus(status).phrase}"
|
|
343
|
+
except ValueError:
|
|
344
|
+
message = f"LLM HTTP {status}"
|
|
345
|
+
if rejected:
|
|
346
|
+
message += " (response_format rejected)"
|
|
347
|
+
elif reason := _provider_reason(response, api_key):
|
|
348
|
+
message += f": {reason}"
|
|
349
|
+
return LLMClientError(message, status_code=status, timed_out=timed_out, json_mode_rejected=rejected)
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Multi-market (US / HK / JP / KR / TW / IN / global) daily screening digest builder."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
from zoneinfo import ZoneInfo
|
|
11
|
+
|
|
12
|
+
from alphasift.config import Config
|
|
13
|
+
from alphasift.daily_brief import resolve_strategy_display_names
|
|
14
|
+
from alphasift.daily_report import IM_CARD_MAX_CHARS, _format_strategy_entry, ensure_im_card_length
|
|
15
|
+
from alphasift.market_news import fetch_region_market_news
|
|
16
|
+
from alphasift.markets import get_market, latest_settled_close
|
|
17
|
+
from alphasift.models import ScreenResult
|
|
18
|
+
from alphasift.source_guard import call_with_timeout
|
|
19
|
+
from alphasift.store import load_screen_result
|
|
20
|
+
from alphasift.timeutil import parse_timestamp
|
|
21
|
+
|
|
22
|
+
MARKET_CN_NAMES: dict[str, str] = {
|
|
23
|
+
"cn": "A股",
|
|
24
|
+
"us": "美股",
|
|
25
|
+
"hk": "港股",
|
|
26
|
+
"jp": "日股",
|
|
27
|
+
"kr": "韩股",
|
|
28
|
+
"tw": "台股",
|
|
29
|
+
"in": "印股",
|
|
30
|
+
}
|
|
31
|
+
_MARKET_NEWS_TIMEOUT_SEC = 8.0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _market_session_date(created_at: str, market: str) -> str:
|
|
35
|
+
parsed = parse_timestamp(created_at)
|
|
36
|
+
if parsed is None:
|
|
37
|
+
return str(created_at or "")[:10]
|
|
38
|
+
settled = latest_settled_close(market, parsed)
|
|
39
|
+
if settled is not None:
|
|
40
|
+
return settled[0].isoformat()
|
|
41
|
+
mkt_info = get_market(market)
|
|
42
|
+
return parsed.astimezone(ZoneInfo(mkt_info.timezone)).date().isoformat()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_multi_market_runs(
|
|
46
|
+
config: Config,
|
|
47
|
+
*,
|
|
48
|
+
markets: Sequence[str],
|
|
49
|
+
runs_dir: Path | None = None,
|
|
50
|
+
trade_date: str | None = None,
|
|
51
|
+
) -> dict[str, list[ScreenResult]]:
|
|
52
|
+
"""Load latest (or trade_date-matched) saved runs grouped by market."""
|
|
53
|
+
req_markets = [str(m).strip().lower() for m in markets if str(m).strip()]
|
|
54
|
+
req_set = set(req_markets)
|
|
55
|
+
if not req_set:
|
|
56
|
+
return {}
|
|
57
|
+
|
|
58
|
+
target_runs_dir = Path(runs_dir).expanduser() if runs_dir is not None else (config.data_dir / "runs")
|
|
59
|
+
grouped: dict[str, list[tuple[str, ScreenResult]]] = {m: [] for m in req_markets}
|
|
60
|
+
if not target_runs_dir.is_dir():
|
|
61
|
+
return {m: [] for m in req_markets}
|
|
62
|
+
|
|
63
|
+
for path in sorted(target_runs_dir.glob("*.json")):
|
|
64
|
+
try:
|
|
65
|
+
sr = load_screen_result(path, data_dir=config.data_dir)
|
|
66
|
+
except Exception: # noqa: BLE001
|
|
67
|
+
continue
|
|
68
|
+
mkt = (sr.market or "cn").strip().lower()
|
|
69
|
+
if mkt not in req_set:
|
|
70
|
+
continue
|
|
71
|
+
sess_date = _market_session_date(sr.created_at or "", mkt)
|
|
72
|
+
if trade_date and sess_date != trade_date:
|
|
73
|
+
continue
|
|
74
|
+
grouped.setdefault(mkt, []).append((sess_date, sr))
|
|
75
|
+
|
|
76
|
+
out: dict[str, list[ScreenResult]] = {}
|
|
77
|
+
for mkt in req_markets:
|
|
78
|
+
candidates = grouped.get(mkt) or []
|
|
79
|
+
if not candidates:
|
|
80
|
+
out[mkt] = []
|
|
81
|
+
continue
|
|
82
|
+
target_sess = trade_date or max(sd for sd, _ in candidates if sd) or ""
|
|
83
|
+
# Deduplicate by (strategy, track) keeping latest created_at for target session date
|
|
84
|
+
by_key: dict[tuple[str, str], ScreenResult] = {}
|
|
85
|
+
for sd, sr in candidates:
|
|
86
|
+
if target_sess and sd != target_sess:
|
|
87
|
+
continue
|
|
88
|
+
tr = sr.track or ("ai" if sr.llm_ranked else "rules")
|
|
89
|
+
key = (str(sr.strategy), tr)
|
|
90
|
+
prev = by_key.get(key)
|
|
91
|
+
if prev is None or str(sr.created_at or "") >= str(prev.created_at or ""):
|
|
92
|
+
by_key[key] = sr
|
|
93
|
+
runs = sorted(
|
|
94
|
+
by_key.values(),
|
|
95
|
+
key=lambda r: (str(r.strategy), 0 if (r.track or "rules") == "rules" else 1),
|
|
96
|
+
)
|
|
97
|
+
out[mkt] = runs
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _top_picks_for_market(
|
|
102
|
+
strategy_entries: list[dict[str, Any]],
|
|
103
|
+
*,
|
|
104
|
+
display_names: dict[str, str],
|
|
105
|
+
) -> list[dict[str, Any]]:
|
|
106
|
+
by_code: dict[str, dict[str, Any]] = {}
|
|
107
|
+
for st in strategy_entries:
|
|
108
|
+
sname = str(st.get("strategy") or "")
|
|
109
|
+
for pk in st.get("picks") or []:
|
|
110
|
+
code = str(pk.get("code") or "").strip()
|
|
111
|
+
if not code:
|
|
112
|
+
continue
|
|
113
|
+
item = by_code.setdefault(
|
|
114
|
+
code,
|
|
115
|
+
{
|
|
116
|
+
"code": code,
|
|
117
|
+
"name": str(pk.get("name") or "").strip(),
|
|
118
|
+
"industry": str(pk.get("industry") or "").strip(),
|
|
119
|
+
"strategies": [],
|
|
120
|
+
"scores": [],
|
|
121
|
+
"price": pk.get("price"),
|
|
122
|
+
"pe_ratio": pk.get("pe_ratio"),
|
|
123
|
+
"pb_ratio": pk.get("pb_ratio"),
|
|
124
|
+
"change_pct": pk.get("change_pct"),
|
|
125
|
+
"ranking_reason": str(pk.get("ranking_reason") or "").strip(),
|
|
126
|
+
},
|
|
127
|
+
)
|
|
128
|
+
if sname and sname not in item["strategies"]:
|
|
129
|
+
item["strategies"].append(sname)
|
|
130
|
+
if pk.get("final_score") is not None:
|
|
131
|
+
item["scores"].append(float(pk["final_score"]))
|
|
132
|
+
for fld in ("price", "pe_ratio", "pb_ratio", "change_pct"):
|
|
133
|
+
if item[fld] is None and pk.get(fld) is not None:
|
|
134
|
+
item[fld] = pk.get(fld)
|
|
135
|
+
if not item["ranking_reason"] and pk.get("ranking_reason"):
|
|
136
|
+
item["ranking_reason"] = str(pk.get("ranking_reason") or "").strip()
|
|
137
|
+
|
|
138
|
+
rows: list[dict[str, Any]] = []
|
|
139
|
+
for item in by_code.values():
|
|
140
|
+
avg_score = round(sum(item["scores"]) / len(item["scores"]), 2) if item["scores"] else 0.0
|
|
141
|
+
rows.append({
|
|
142
|
+
"code": item["code"],
|
|
143
|
+
"name": item["name"],
|
|
144
|
+
"industry": item["industry"],
|
|
145
|
+
"strategy_count": len(item["strategies"]),
|
|
146
|
+
"strategies": item["strategies"],
|
|
147
|
+
"strategy_display_names": [display_names.get(s, s) for s in item["strategies"]],
|
|
148
|
+
"avg_final_score": avg_score,
|
|
149
|
+
"price": item["price"],
|
|
150
|
+
"pe_ratio": item["pe_ratio"],
|
|
151
|
+
"pb_ratio": item["pb_ratio"],
|
|
152
|
+
"change_pct": item["change_pct"],
|
|
153
|
+
"ranking_reason": item["ranking_reason"],
|
|
154
|
+
})
|
|
155
|
+
rows.sort(key=lambda x: (-x["strategy_count"], -x["avg_final_score"], x["code"]))
|
|
156
|
+
return rows[:6]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def render_market_digest_im_card(
|
|
160
|
+
digest: dict[str, Any],
|
|
161
|
+
*,
|
|
162
|
+
max_chars: int = IM_CARD_MAX_CHARS,
|
|
163
|
+
) -> str:
|
|
164
|
+
sections = digest.get("market_sections") or []
|
|
165
|
+
mkt_labels = "·".join(s.get("market_name") or str(s.get("market") or "").upper() for s in sections)
|
|
166
|
+
lines = [f"**AlphaSift 全球市场盘后精选 ({digest.get('trade_date', '-')})|{mkt_labels or '多市场'}**"]
|
|
167
|
+
if sections:
|
|
168
|
+
for sec in sections[:6]:
|
|
169
|
+
m_name = sec.get("market_name") or str(sec.get("market") or "").upper()
|
|
170
|
+
st_cnt = int(sec.get("strategy_count") or 0)
|
|
171
|
+
top = sec.get("top_picks") or []
|
|
172
|
+
if top:
|
|
173
|
+
top_txt = "、".join(
|
|
174
|
+
f"{p.get('code')} {str(p.get('name') or '')[:8]}({p.get('avg_final_score'):.1f}分)"
|
|
175
|
+
for p in top[:3]
|
|
176
|
+
)
|
|
177
|
+
lines.append(f"- **{m_name}**({st_cnt} 组策略 · {sec.get('trade_date', '-')}):{top_txt}")
|
|
178
|
+
else:
|
|
179
|
+
lines.append(f"- **{m_name}**:今日无新增候选")
|
|
180
|
+
else:
|
|
181
|
+
lines.append("**概览**:所选市场暂无已保存的策略运行记录")
|
|
182
|
+
|
|
183
|
+
mnews = ((digest.get("market_news") or {}).get("items") or []) if isinstance(digest.get("market_news"), dict) else []
|
|
184
|
+
if mnews:
|
|
185
|
+
lines.append(f"**市场快讯**:{str(mnews[0].get('title') or '')[:55]}")
|
|
186
|
+
|
|
187
|
+
detail_url = str(digest.get("detail_url") or "").strip()
|
|
188
|
+
if detail_url:
|
|
189
|
+
lines.append(f"🔗 在线交互看板与历史战绩:{detail_url}")
|
|
190
|
+
lines.append("注:量化形态观测与回测基准,非投资建议。")
|
|
191
|
+
return ensure_im_card_length("\n".join(lines), max_chars=max_chars)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def build_markets_digest(
|
|
195
|
+
runs_by_market: dict[str, list[ScreenResult]],
|
|
196
|
+
*,
|
|
197
|
+
markets: Sequence[str],
|
|
198
|
+
trade_date: str | None = None,
|
|
199
|
+
detail_url: str = "",
|
|
200
|
+
include_news: bool = False,
|
|
201
|
+
config: Config | None = None,
|
|
202
|
+
track_summary: dict[str, Any] | None = None,
|
|
203
|
+
regional_news_collector: Callable[..., tuple[list[dict[str, Any]], list[str]]] | None = None,
|
|
204
|
+
) -> dict[str, Any]:
|
|
205
|
+
"""Build a multi-market post-close screening digest (object='MarketDigest')."""
|
|
206
|
+
req_markets = [str(m).strip().lower() for m in markets if str(m).strip()]
|
|
207
|
+
summary_names = (
|
|
208
|
+
track_summary.get("strategy_names")
|
|
209
|
+
if isinstance(track_summary, dict) and isinstance(track_summary.get("strategy_names"), dict)
|
|
210
|
+
else None
|
|
211
|
+
)
|
|
212
|
+
display_names = resolve_strategy_display_names(
|
|
213
|
+
config.strategies_dir if config is not None else None,
|
|
214
|
+
overrides=summary_names,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
sections: list[dict[str, Any]] = []
|
|
218
|
+
session_dates: list[str] = []
|
|
219
|
+
degradation: list[str] = []
|
|
220
|
+
|
|
221
|
+
for mkt in req_markets:
|
|
222
|
+
runs = runs_by_market.get(mkt) or []
|
|
223
|
+
mkt_meta = get_market(mkt)
|
|
224
|
+
sess_dates = [
|
|
225
|
+
_market_session_date(r.created_at or "", mkt)
|
|
226
|
+
for r in runs
|
|
227
|
+
if getattr(r, "created_at", "")
|
|
228
|
+
]
|
|
229
|
+
mkt_date = trade_date or (max(sess_dates) if sess_dates else "-")
|
|
230
|
+
if mkt_date and mkt_date != "-":
|
|
231
|
+
session_dates.append(mkt_date)
|
|
232
|
+
strat_entries = [_format_strategy_entry(r, display_names=display_names) for r in runs]
|
|
233
|
+
top_picks = _top_picks_for_market(strat_entries, display_names=display_names)
|
|
234
|
+
if not runs:
|
|
235
|
+
degradation.append(f"No saved runs found for market={mkt}")
|
|
236
|
+
sections.append({
|
|
237
|
+
"market": mkt,
|
|
238
|
+
"market_name": MARKET_CN_NAMES.get(mkt, mkt_meta.name),
|
|
239
|
+
"benchmark": mkt_meta.benchmark_name,
|
|
240
|
+
"trade_date": mkt_date,
|
|
241
|
+
"strategy_count": len(strat_entries),
|
|
242
|
+
"strategies": strat_entries,
|
|
243
|
+
"top_picks": top_picks,
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
resolved_date = trade_date or (max(session_dates) if session_dates else datetime.now(timezone.utc).date().isoformat())
|
|
247
|
+
|
|
248
|
+
market_news_section: dict[str, Any] = {"items": [], "sources": [], "errors": []}
|
|
249
|
+
if include_news:
|
|
250
|
+
try:
|
|
251
|
+
if regional_news_collector is not None:
|
|
252
|
+
n_items, n_sources = regional_news_collector(req_markets, limit=4)
|
|
253
|
+
else:
|
|
254
|
+
n_items, n_sources = call_with_timeout(
|
|
255
|
+
fetch_region_market_news,
|
|
256
|
+
req_markets,
|
|
257
|
+
limit=4,
|
|
258
|
+
tavily_keys=config.tavily_api_keys if config is not None else None,
|
|
259
|
+
serpapi_keys=config.serpapi_api_keys if config is not None else None,
|
|
260
|
+
timeout_sec=_MARKET_NEWS_TIMEOUT_SEC,
|
|
261
|
+
label="regional market news",
|
|
262
|
+
)
|
|
263
|
+
market_news_section["items"] = list(n_items or [])
|
|
264
|
+
market_news_section["sources"] = list(n_sources or [])
|
|
265
|
+
except Exception as exc: # noqa: BLE001
|
|
266
|
+
market_news_section["errors"].append(f"regional news skipped: {exc}")
|
|
267
|
+
|
|
268
|
+
digest: dict[str, Any] = {
|
|
269
|
+
"schema_version": 1,
|
|
270
|
+
"object": "MarketDigest",
|
|
271
|
+
"trade_date": resolved_date,
|
|
272
|
+
"market": "+".join(req_markets) or "global",
|
|
273
|
+
"markets": req_markets,
|
|
274
|
+
"detail_url": str(detail_url or "").strip(),
|
|
275
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
276
|
+
"strategy_display_names": display_names,
|
|
277
|
+
"market_sections": sections,
|
|
278
|
+
"market_news": market_news_section,
|
|
279
|
+
"degradation": degradation,
|
|
280
|
+
}
|
|
281
|
+
card = render_market_digest_im_card(digest)
|
|
282
|
+
digest["im_card_markdown"] = card
|
|
283
|
+
digest["im_card_chars"] = len(card)
|
|
284
|
+
return digest
|