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/market_news.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Multi-source market-wide and candidate catalyst news fetching for daily reports."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
8
|
+
from datetime import datetime, timedelta
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import requests
|
|
16
|
+
|
|
17
|
+
_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
|
18
|
+
_NOISE_PATTERNS = (
|
|
19
|
+
"互动平台",
|
|
20
|
+
"融资融券余额",
|
|
21
|
+
"股吧",
|
|
22
|
+
"龙虎榜营业部",
|
|
23
|
+
"资金流向",
|
|
24
|
+
"代表团",
|
|
25
|
+
"民航组织",
|
|
26
|
+
"实时行情, 股票股价",
|
|
27
|
+
)
|
|
28
|
+
_CATEGORY_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|
29
|
+
("宏观政策", ("央行", "证监会", "上交所", "深交所", "北交所", "沪深交易所", "中国结算", "发改委", "财政", "国务院", "降准", "降息", "LPR", "政策", "PMI", "GDP", "CPI", "关税")),
|
|
30
|
+
("海外市场", ("美联储", "美股", "纳斯达克", "道指", "标普", "欧股", "港股", "恒生", "日元", "美元", "油价", "黄金")),
|
|
31
|
+
("板块产业", ("板块", "产业链", "算力", "AI", "人工智能", "芯片", "半导体", "新能源", "光伏", "锂电", "医药", "创新药", "银行", "券商", "低空", "机器人", "军工")),
|
|
32
|
+
("公司动态", ("回购", "增持", "减持", "业绩", "预告", "分红", "并购", "重组", "中标", "涨停", "跌停")),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _norm_title_key(text: str) -> str:
|
|
37
|
+
return re.sub(r"[\W_]+", "", str(text or "")).lower()[:48]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _classify_news_category(text: str) -> str:
|
|
41
|
+
for label, keywords in _CATEGORY_RULES:
|
|
42
|
+
if any(kw in text for kw in keywords):
|
|
43
|
+
return label
|
|
44
|
+
return "市场要闻"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _format_pub_time(raw: object) -> str:
|
|
48
|
+
val = str(raw or "").strip()
|
|
49
|
+
if not val:
|
|
50
|
+
return ""
|
|
51
|
+
if val.isdigit():
|
|
52
|
+
try:
|
|
53
|
+
ts = int(val)
|
|
54
|
+
if ts > 1_000_000_000_000:
|
|
55
|
+
ts //= 1000
|
|
56
|
+
return datetime.fromtimestamp(ts).strftime("%m-%d %H:%M")
|
|
57
|
+
except (OSError, ValueError, OverflowError):
|
|
58
|
+
return ""
|
|
59
|
+
m = re.search(r"(\d{2}-\d{2})\s+(\d{2}:\d{2})", val)
|
|
60
|
+
if m:
|
|
61
|
+
return f"{m.group(1)} {m.group(2)}"
|
|
62
|
+
m2 = re.search(r"(\d{4}-\d{2}-\d{2})", val)
|
|
63
|
+
return m2.group(1) if m2 else val[:16]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _clean_line(text: object, *, max_len: int = 120) -> str:
|
|
67
|
+
s = " ".join(re.sub(r"<[^>]+>", " ", str(text or "")).split())
|
|
68
|
+
if len(s) > max_len:
|
|
69
|
+
return s[: max_len - 1].rstrip() + "…"
|
|
70
|
+
return s
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _redact_text(text: str, secrets: Sequence[str] = ()) -> str:
|
|
74
|
+
out = str(text or "")
|
|
75
|
+
for s in secrets:
|
|
76
|
+
if s:
|
|
77
|
+
out = out.replace(s, "***")
|
|
78
|
+
out = re.sub(r"(?i)(api[_-]?key|token|tvly-|key)[=:\s]+[^\s&,'\"]+", r"\1=***", out)
|
|
79
|
+
return out[:180]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _fetch_eastmoney_fast_news(*, limit: int = 8, timeout_sec: float = 5.0) -> list[dict[str, Any]]:
|
|
83
|
+
url = "https://np-weblist.eastmoney.com/comm/web/getFastNewsList"
|
|
84
|
+
collected: list[dict[str, Any]] = []
|
|
85
|
+
# Column 103 focuses on A-share listed companies / market moves; 102 covers broader macro/market headlines.
|
|
86
|
+
for col in ("103", "102"):
|
|
87
|
+
resp = requests.get(
|
|
88
|
+
url,
|
|
89
|
+
params={
|
|
90
|
+
"client": "web",
|
|
91
|
+
"biz": "web_724",
|
|
92
|
+
"fastColumn": col,
|
|
93
|
+
"sortEnd": "",
|
|
94
|
+
"pageSize": max(limit, 10),
|
|
95
|
+
"req_trace": str(int(datetime.now().timestamp() * 1000)),
|
|
96
|
+
},
|
|
97
|
+
headers=_HEADERS,
|
|
98
|
+
timeout=timeout_sec,
|
|
99
|
+
)
|
|
100
|
+
resp.raise_for_status()
|
|
101
|
+
payload = resp.json()
|
|
102
|
+
rows = ((payload.get("data") or {}).get("fastNewsList") or []) if isinstance(payload, dict) else []
|
|
103
|
+
for item in rows:
|
|
104
|
+
if not isinstance(item, dict):
|
|
105
|
+
continue
|
|
106
|
+
title = _clean_line(item.get("title") or item.get("summary") or "", max_len=110)
|
|
107
|
+
if not title or len(title) < 6:
|
|
108
|
+
continue
|
|
109
|
+
summary = _clean_line(item.get("summary") or "", max_len=140)
|
|
110
|
+
collected.append({
|
|
111
|
+
"title": title,
|
|
112
|
+
"summary": summary if summary and summary != title else "",
|
|
113
|
+
"published_at": _format_pub_time(item.get("showTime")),
|
|
114
|
+
"source": "东方财富7x24",
|
|
115
|
+
"category": _classify_news_category(f"{title} {summary}"),
|
|
116
|
+
})
|
|
117
|
+
if len(collected) >= limit * 2:
|
|
118
|
+
break
|
|
119
|
+
return collected
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _fetch_ths_fast_news(*, limit: int = 8, timeout_sec: float = 5.0) -> list[dict[str, Any]]:
|
|
123
|
+
resp = requests.get(
|
|
124
|
+
"https://news.10jqka.com.cn/tapp/news/push/stock",
|
|
125
|
+
params={"page": 1, "tag": "", "track": "website", "pagesize": max(limit, 12)},
|
|
126
|
+
headers=_HEADERS,
|
|
127
|
+
timeout=timeout_sec,
|
|
128
|
+
)
|
|
129
|
+
resp.raise_for_status()
|
|
130
|
+
payload = resp.json()
|
|
131
|
+
rows = ((payload.get("data") or {}).get("list") or []) if isinstance(payload, dict) else []
|
|
132
|
+
out: list[dict[str, Any]] = []
|
|
133
|
+
for item in rows:
|
|
134
|
+
if not isinstance(item, dict):
|
|
135
|
+
continue
|
|
136
|
+
title = _clean_line(item.get("title") or item.get("digest") or "", max_len=110)
|
|
137
|
+
if not title or len(title) < 6:
|
|
138
|
+
continue
|
|
139
|
+
summary = _clean_line(item.get("digest") or "", max_len=140)
|
|
140
|
+
out.append({
|
|
141
|
+
"title": title,
|
|
142
|
+
"summary": summary if summary and summary != title else "",
|
|
143
|
+
"published_at": _format_pub_time(item.get("rtime") or item.get("ctime")),
|
|
144
|
+
"source": "同花顺快讯",
|
|
145
|
+
"category": _classify_news_category(f"{title} {summary}"),
|
|
146
|
+
})
|
|
147
|
+
return out
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _fetch_sina_fast_news(*, limit: int = 8, timeout_sec: float = 5.0) -> list[dict[str, Any]]:
|
|
151
|
+
resp = requests.get(
|
|
152
|
+
"https://zhibo.sina.com.cn/api/zhibo/feed",
|
|
153
|
+
params={"page": 1, "page_size": max(limit, 12), "zhibo_id": 152, "tag_id": 0, "dire": "f", "dpc": 1, "type": 1},
|
|
154
|
+
headers=_HEADERS,
|
|
155
|
+
timeout=timeout_sec,
|
|
156
|
+
)
|
|
157
|
+
resp.raise_for_status()
|
|
158
|
+
payload = resp.json()
|
|
159
|
+
rows = (
|
|
160
|
+
((((payload.get("result") or {}).get("data") or {}).get("feed") or {}).get("list") or [])
|
|
161
|
+
if isinstance(payload, dict)
|
|
162
|
+
else []
|
|
163
|
+
)
|
|
164
|
+
out: list[dict[str, Any]] = []
|
|
165
|
+
for item in rows:
|
|
166
|
+
if not isinstance(item, dict):
|
|
167
|
+
continue
|
|
168
|
+
raw_text = _clean_line(item.get("rich_text") or "", max_len=160)
|
|
169
|
+
if not raw_text or len(raw_text) < 8:
|
|
170
|
+
continue
|
|
171
|
+
m = re.match(r"^【([^】]{4,70})】\s*(.*)$", raw_text)
|
|
172
|
+
if m:
|
|
173
|
+
title = m.group(1).strip()
|
|
174
|
+
summary = m.group(2).strip()[:120]
|
|
175
|
+
else:
|
|
176
|
+
title = raw_text[:100]
|
|
177
|
+
summary = ""
|
|
178
|
+
out.append({
|
|
179
|
+
"title": title,
|
|
180
|
+
"summary": summary,
|
|
181
|
+
"published_at": _format_pub_time(item.get("create_time")),
|
|
182
|
+
"source": "新浪财经7x24",
|
|
183
|
+
"category": _classify_news_category(raw_text),
|
|
184
|
+
})
|
|
185
|
+
return out
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _resolve_search_keys(
|
|
189
|
+
explicit: Sequence[str] | None,
|
|
190
|
+
*env_names: str,
|
|
191
|
+
) -> list[str]:
|
|
192
|
+
if explicit is not None:
|
|
193
|
+
return [str(k).strip() for k in explicit if str(k).strip()]
|
|
194
|
+
out: list[str] = []
|
|
195
|
+
for env_name in env_names:
|
|
196
|
+
raw = os.getenv(env_name, "").strip()
|
|
197
|
+
if raw and raw.lower() not in {"0", "false", "none", "off"}:
|
|
198
|
+
for item in raw.split(","):
|
|
199
|
+
k = item.strip()
|
|
200
|
+
if k and k not in out:
|
|
201
|
+
out.append(k)
|
|
202
|
+
return out
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def search_stock_news_via_web(
|
|
206
|
+
query: str,
|
|
207
|
+
*,
|
|
208
|
+
limit: int = 3,
|
|
209
|
+
tavily_keys: Sequence[str] | None = None,
|
|
210
|
+
serpapi_keys: Sequence[str] | None = None,
|
|
211
|
+
timeout_sec: float = 6.0,
|
|
212
|
+
) -> list[dict[str, str]]:
|
|
213
|
+
"""Search stock or market news via optional Tavily / SerpAPI keys without exposing credentials."""
|
|
214
|
+
t_keys = _resolve_search_keys(tavily_keys, "TAVILY_API_KEYS", "TAVILY_API_KEY")
|
|
215
|
+
s_keys = _resolve_search_keys(serpapi_keys, "SERPAPI_API_KEYS", "SERPAPI_API_KEY")
|
|
216
|
+
max_res = max(1, min(int(limit), 8))
|
|
217
|
+
|
|
218
|
+
for key in t_keys:
|
|
219
|
+
try:
|
|
220
|
+
resp = requests.post(
|
|
221
|
+
"https://api.tavily.com/search",
|
|
222
|
+
json={
|
|
223
|
+
"api_key": key,
|
|
224
|
+
"query": query,
|
|
225
|
+
"search_depth": "basic",
|
|
226
|
+
"topic": "news",
|
|
227
|
+
"max_results": max_res,
|
|
228
|
+
"days": 7,
|
|
229
|
+
},
|
|
230
|
+
headers={"Content-Type": "application/json"},
|
|
231
|
+
timeout=timeout_sec,
|
|
232
|
+
)
|
|
233
|
+
if resp.status_code in {401, 403, 429, 432}:
|
|
234
|
+
continue
|
|
235
|
+
resp.raise_for_status()
|
|
236
|
+
data = resp.json()
|
|
237
|
+
results = data.get("results") or [] if isinstance(data, dict) else []
|
|
238
|
+
items: list[dict[str, str]] = []
|
|
239
|
+
for r in results[:max_res]:
|
|
240
|
+
if not isinstance(r, dict):
|
|
241
|
+
continue
|
|
242
|
+
title = _clean_line(r.get("title") or "", max_len=110)
|
|
243
|
+
if not title:
|
|
244
|
+
continue
|
|
245
|
+
items.append({
|
|
246
|
+
"title": title,
|
|
247
|
+
"summary": _clean_line(r.get("content") or "", max_len=120),
|
|
248
|
+
"published_at": _format_pub_time(r.get("published_date")),
|
|
249
|
+
"source": "Tavily",
|
|
250
|
+
"category": _classify_news_category(title),
|
|
251
|
+
})
|
|
252
|
+
if items:
|
|
253
|
+
return items
|
|
254
|
+
except Exception: # noqa: BLE001
|
|
255
|
+
continue
|
|
256
|
+
|
|
257
|
+
for key in s_keys:
|
|
258
|
+
try:
|
|
259
|
+
resp = requests.get(
|
|
260
|
+
"https://serpapi.com/search.json",
|
|
261
|
+
params={"q": query, "api_key": key, "num": max_res, "tbm": "nws", "hl": "zh-cn"},
|
|
262
|
+
timeout=timeout_sec,
|
|
263
|
+
)
|
|
264
|
+
if resp.status_code in {401, 403, 429}:
|
|
265
|
+
continue
|
|
266
|
+
resp.raise_for_status()
|
|
267
|
+
data = resp.json()
|
|
268
|
+
results = (data.get("news_results") or data.get("organic_results") or []) if isinstance(data, dict) else []
|
|
269
|
+
items = []
|
|
270
|
+
for r in results[:max_res]:
|
|
271
|
+
if not isinstance(r, dict):
|
|
272
|
+
continue
|
|
273
|
+
title = _clean_line(r.get("title") or "", max_len=110)
|
|
274
|
+
if not title:
|
|
275
|
+
continue
|
|
276
|
+
items.append({
|
|
277
|
+
"title": title,
|
|
278
|
+
"summary": _clean_line(r.get("snippet") or "", max_len=120),
|
|
279
|
+
"published_at": _format_pub_time(r.get("date")),
|
|
280
|
+
"source": str(r.get("source") or "SerpAPI")[:24],
|
|
281
|
+
"category": _classify_news_category(title),
|
|
282
|
+
})
|
|
283
|
+
if items:
|
|
284
|
+
return items
|
|
285
|
+
except Exception: # noqa: BLE001
|
|
286
|
+
continue
|
|
287
|
+
|
|
288
|
+
return []
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _select_and_dedupe_news(raw_items: list[dict[str, Any]], *, limit: int) -> list[dict[str, Any]]:
|
|
292
|
+
deduped: list[dict[str, Any]] = []
|
|
293
|
+
seen_keys: set[str] = set()
|
|
294
|
+
# First pass excludes low-signal platform Q&A / boilerplate; second pass backfills if needed.
|
|
295
|
+
for allow_noise in (False, True):
|
|
296
|
+
for item in raw_items:
|
|
297
|
+
title = str(item.get("title") or "").strip()
|
|
298
|
+
if not title:
|
|
299
|
+
continue
|
|
300
|
+
if not allow_noise and any(p in title for p in _NOISE_PATTERNS):
|
|
301
|
+
continue
|
|
302
|
+
key = _norm_title_key(title)
|
|
303
|
+
if not key or key in seen_keys:
|
|
304
|
+
continue
|
|
305
|
+
seen_keys.add(key)
|
|
306
|
+
deduped.append(item)
|
|
307
|
+
if len(deduped) >= limit:
|
|
308
|
+
return deduped
|
|
309
|
+
return deduped
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _read_news_cache(cache_file: Path | None, ttl_hours: int) -> dict[str, Any] | None:
|
|
313
|
+
if cache_file is None or not cache_file.is_file() or ttl_hours <= 0:
|
|
314
|
+
return None
|
|
315
|
+
try:
|
|
316
|
+
data = json.loads(cache_file.read_text(encoding="utf-8"))
|
|
317
|
+
cached_at = datetime.fromisoformat(str(data.get("cached_at") or ""))
|
|
318
|
+
if datetime.now() - cached_at > timedelta(hours=ttl_hours):
|
|
319
|
+
return None
|
|
320
|
+
return data if isinstance(data.get("items"), list) else None
|
|
321
|
+
except Exception: # noqa: BLE001
|
|
322
|
+
return None
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _write_news_cache(cache_file: Path | None, payload: dict[str, Any]) -> None:
|
|
326
|
+
if cache_file is None:
|
|
327
|
+
return
|
|
328
|
+
try:
|
|
329
|
+
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
|
330
|
+
cache_file.write_text(
|
|
331
|
+
json.dumps({"cached_at": datetime.now().isoformat(), **payload}, ensure_ascii=False, indent=2),
|
|
332
|
+
encoding="utf-8",
|
|
333
|
+
)
|
|
334
|
+
except OSError:
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def fetch_cn_market_news(
|
|
339
|
+
*,
|
|
340
|
+
limit: int = 6,
|
|
341
|
+
trade_date: str | None = None,
|
|
342
|
+
cache_dir: Path | None = None,
|
|
343
|
+
cache_ttl_hours: int = 2,
|
|
344
|
+
tavily_keys: Sequence[str] | None = None,
|
|
345
|
+
serpapi_keys: Sequence[str] | None = None,
|
|
346
|
+
timeout_sec: float = 5.0,
|
|
347
|
+
) -> tuple[list[dict[str, Any]], list[str], list[str]]:
|
|
348
|
+
"""Fetch recent CN market / policy / sector headlines with multi-source fallback."""
|
|
349
|
+
target_limit = max(1, int(limit))
|
|
350
|
+
date_tag = (trade_date or datetime.now().strftime("%Y-%m-%d")).strip()
|
|
351
|
+
cache_file = Path(cache_dir) / f"market_news_cn_{date_tag}.json" if cache_dir else None
|
|
352
|
+
cached = _read_news_cache(cache_file, cache_ttl_hours)
|
|
353
|
+
if cached is not None:
|
|
354
|
+
return list(cached["items"])[:target_limit], list(cached.get("sources") or []), []
|
|
355
|
+
|
|
356
|
+
raw_items: list[dict[str, Any]] = []
|
|
357
|
+
sources: list[str] = []
|
|
358
|
+
errors: list[str] = []
|
|
359
|
+
secrets = [
|
|
360
|
+
*_resolve_search_keys(tavily_keys, "TAVILY_API_KEYS", "TAVILY_API_KEY"),
|
|
361
|
+
*_resolve_search_keys(serpapi_keys, "SERPAPI_API_KEYS", "SERPAPI_API_KEY"),
|
|
362
|
+
]
|
|
363
|
+
|
|
364
|
+
providers = (
|
|
365
|
+
("东方财富7x24", _fetch_eastmoney_fast_news),
|
|
366
|
+
("同花顺快讯", _fetch_ths_fast_news),
|
|
367
|
+
("新浪财经7x24", _fetch_sina_fast_news),
|
|
368
|
+
)
|
|
369
|
+
# Query EastMoney + Tonghuashun in parallel, then assemble in deterministic priority order
|
|
370
|
+
# (EastMoney CN company/market news first, then Tonghuashun market headlines).
|
|
371
|
+
rows_by_label: dict[str, list[dict[str, Any]]] = {}
|
|
372
|
+
with ThreadPoolExecutor(max_workers=2) as pool:
|
|
373
|
+
futs = {
|
|
374
|
+
pool.submit(fn, limit=max(target_limit, 8), timeout_sec=timeout_sec): label
|
|
375
|
+
for label, fn in providers[:2]
|
|
376
|
+
}
|
|
377
|
+
for fut in as_completed(futs):
|
|
378
|
+
label = futs[fut]
|
|
379
|
+
try:
|
|
380
|
+
rows = fut.result()
|
|
381
|
+
if rows:
|
|
382
|
+
rows_by_label[label] = rows
|
|
383
|
+
except Exception as exc: # noqa: BLE001
|
|
384
|
+
errors.append(f"{label}: {_redact_text(str(exc), secrets)}")
|
|
385
|
+
for label, _ in providers[:2]:
|
|
386
|
+
if label in rows_by_label:
|
|
387
|
+
raw_items.extend(rows_by_label[label])
|
|
388
|
+
sources.append(label)
|
|
389
|
+
|
|
390
|
+
items = _select_and_dedupe_news(raw_items, limit=target_limit)
|
|
391
|
+
if len(items) < min(3, target_limit):
|
|
392
|
+
try:
|
|
393
|
+
sina_rows = _fetch_sina_fast_news(limit=max(target_limit, 8), timeout_sec=timeout_sec)
|
|
394
|
+
if sina_rows:
|
|
395
|
+
raw_items.extend(sina_rows)
|
|
396
|
+
sources.append("新浪财经7x24")
|
|
397
|
+
items = _select_and_dedupe_news(raw_items, limit=target_limit)
|
|
398
|
+
except Exception as exc: # noqa: BLE001
|
|
399
|
+
errors.append(f"新浪财经7x24: {_redact_text(str(exc), secrets)}")
|
|
400
|
+
|
|
401
|
+
if len(items) < min(3, target_limit):
|
|
402
|
+
query = f"A股 {date_tag} 收盘 板块 要闻 政策" if trade_date else "A股 今日 收盘 板块 要闻 政策"
|
|
403
|
+
web_rows = search_stock_news_via_web(
|
|
404
|
+
query,
|
|
405
|
+
limit=target_limit,
|
|
406
|
+
tavily_keys=tavily_keys,
|
|
407
|
+
serpapi_keys=serpapi_keys,
|
|
408
|
+
timeout_sec=timeout_sec + 1.0,
|
|
409
|
+
)
|
|
410
|
+
if web_rows:
|
|
411
|
+
raw_items.extend(web_rows)
|
|
412
|
+
sources.extend(sorted({r["source"] for r in web_rows if r.get("source")}))
|
|
413
|
+
items = _select_and_dedupe_news(raw_items, limit=target_limit)
|
|
414
|
+
|
|
415
|
+
deduped_sources = list(dict.fromkeys(sources))
|
|
416
|
+
if items:
|
|
417
|
+
_write_news_cache(cache_file, {"items": items, "sources": deduped_sources})
|
|
418
|
+
return items, deduped_sources, (errors if not items else [])
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def fetch_region_market_news(
|
|
422
|
+
markets: Sequence[str],
|
|
423
|
+
*,
|
|
424
|
+
limit: int = 4,
|
|
425
|
+
tavily_keys: Sequence[str] | None = None,
|
|
426
|
+
serpapi_keys: Sequence[str] | None = None,
|
|
427
|
+
timeout_sec: float = 6.0,
|
|
428
|
+
) -> tuple[list[dict[str, Any]], list[str]]:
|
|
429
|
+
"""Best-effort news fetch for US/Asia/Global market digests when web search keys exist."""
|
|
430
|
+
mkt_set = {str(m).strip().lower() for m in markets if str(m).strip()}
|
|
431
|
+
if not mkt_set:
|
|
432
|
+
return [], []
|
|
433
|
+
if "us" in mkt_set and len(mkt_set) == 1:
|
|
434
|
+
query = "US stock market S&P 500 Nasdaq closing highlights today"
|
|
435
|
+
elif "hk" in mkt_set:
|
|
436
|
+
query = "港股 恒生指数 亚太股市 收盘 要闻"
|
|
437
|
+
else:
|
|
438
|
+
query = "Global equity markets Asia US stocks closing news today"
|
|
439
|
+
rows = search_stock_news_via_web(
|
|
440
|
+
query,
|
|
441
|
+
limit=limit,
|
|
442
|
+
tavily_keys=tavily_keys,
|
|
443
|
+
serpapi_keys=serpapi_keys,
|
|
444
|
+
timeout_sec=timeout_sec,
|
|
445
|
+
)
|
|
446
|
+
return rows, sorted({r["source"] for r in rows if r.get("source")})
|