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/hotspot.py
ADDED
|
@@ -0,0 +1,1713 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Topic-first hotspot discovery and detail helpers."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import asdict, dataclass, field
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
from alphasift.industry import (
|
|
17
|
+
_board_heat_score,
|
|
18
|
+
_safe_float,
|
|
19
|
+
_safe_text,
|
|
20
|
+
load_board_heat_trends,
|
|
21
|
+
)
|
|
22
|
+
from alphasift.normalize import normalize_code as _normalize_code # strict: free-text paths
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
HOTSPOT_STAGES = (
|
|
26
|
+
"初次异动",
|
|
27
|
+
"确认扩散",
|
|
28
|
+
"加速主升",
|
|
29
|
+
"分歧放量",
|
|
30
|
+
"降温退潮",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class HotspotSummary:
|
|
36
|
+
topic: str
|
|
37
|
+
name: str = ""
|
|
38
|
+
source: str = ""
|
|
39
|
+
rank: int | None = None
|
|
40
|
+
change_pct: float | None = None
|
|
41
|
+
heat_score: float = 50.0
|
|
42
|
+
trend_score: float | None = None
|
|
43
|
+
persistence_score: float | None = None
|
|
44
|
+
cooling_score: float | None = None
|
|
45
|
+
observations: int = 0
|
|
46
|
+
state: str = ""
|
|
47
|
+
stage: str = "初次异动"
|
|
48
|
+
sample_stock_count: int = 0
|
|
49
|
+
leaders: list[str] = field(default_factory=list)
|
|
50
|
+
leader_stocks: list["HotspotStock"] = field(default_factory=list)
|
|
51
|
+
quality_status: str = "partial"
|
|
52
|
+
missing_fields: list[str] = field(default_factory=list)
|
|
53
|
+
canonical_topic: str = ""
|
|
54
|
+
aliases: list[str] = field(default_factory=list)
|
|
55
|
+
resolver_candidates: list[dict[str, Any]] = field(default_factory=list)
|
|
56
|
+
provider_used: str = ""
|
|
57
|
+
fallback_used: bool = False
|
|
58
|
+
source_errors: list[str] = field(default_factory=list)
|
|
59
|
+
stale: bool = False
|
|
60
|
+
stale_age_hours: float | None = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class HotspotStock:
|
|
65
|
+
code: str
|
|
66
|
+
name: str = ""
|
|
67
|
+
change_pct: float | None = None
|
|
68
|
+
amount: float | None = None
|
|
69
|
+
turnover_rate: float | None = None
|
|
70
|
+
volume_ratio: float | None = None
|
|
71
|
+
net_inflow: float | None = None
|
|
72
|
+
is_limit_up: bool = False
|
|
73
|
+
active_days: int = 0
|
|
74
|
+
evidence_count: int = 0
|
|
75
|
+
role: str = ""
|
|
76
|
+
hot_stock_score: float = 0.0
|
|
77
|
+
source: str = ""
|
|
78
|
+
source_confidence: float | None = None
|
|
79
|
+
fallback_used: bool = False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class HotspotTopicResolution:
|
|
84
|
+
query: str
|
|
85
|
+
canonical_topic: str = ""
|
|
86
|
+
candidates: list[dict[str, Any]] = field(default_factory=list)
|
|
87
|
+
aliases: list[str] = field(default_factory=list)
|
|
88
|
+
confidence: float = 0.0
|
|
89
|
+
unresolved: bool = True
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class TimelineEvent:
|
|
94
|
+
date: str
|
|
95
|
+
source: str
|
|
96
|
+
title: str
|
|
97
|
+
event_type: str = "news"
|
|
98
|
+
impact_score: float = 0.0
|
|
99
|
+
related_codes: list[str] = field(default_factory=list)
|
|
100
|
+
description: str = ""
|
|
101
|
+
url: str = ""
|
|
102
|
+
published_at: str = ""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class HotspotRouteItem:
|
|
107
|
+
date: str
|
|
108
|
+
title: str
|
|
109
|
+
description: str = ""
|
|
110
|
+
source: str = ""
|
|
111
|
+
event_type: str = "summary"
|
|
112
|
+
impact_score: float = 0.0
|
|
113
|
+
related_codes: list[str] = field(default_factory=list)
|
|
114
|
+
url: str = ""
|
|
115
|
+
published_at: str = ""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class HotspotDetail:
|
|
120
|
+
summary: HotspotSummary
|
|
121
|
+
stocks: list[HotspotStock] = field(default_factory=list)
|
|
122
|
+
timeline: list[TimelineEvent] = field(default_factory=list)
|
|
123
|
+
route: list[HotspotRouteItem] = field(default_factory=list)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class HotspotResults(list[HotspotSummary]):
|
|
127
|
+
"""List-compatible hotspot result with degradation metadata."""
|
|
128
|
+
|
|
129
|
+
def __init__(
|
|
130
|
+
self,
|
|
131
|
+
items: list[HotspotSummary] | None = None,
|
|
132
|
+
*,
|
|
133
|
+
provider_used: str = "",
|
|
134
|
+
fallback_used: bool = False,
|
|
135
|
+
source_errors: list[str] | None = None,
|
|
136
|
+
stale: bool = False,
|
|
137
|
+
stale_age_hours: float | None = None,
|
|
138
|
+
) -> None:
|
|
139
|
+
super().__init__(items or [])
|
|
140
|
+
self.provider_used = provider_used
|
|
141
|
+
self.fallback_used = fallback_used
|
|
142
|
+
self.source_errors = _dedupe_errors(source_errors or [])
|
|
143
|
+
self.stale = stale
|
|
144
|
+
self.stale_age_hours = stale_age_hours
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def compute_hotspot_heat_score(change_pct: float | None, rank: float | None) -> float:
|
|
148
|
+
"""Compute board heat using the industry cache semantics."""
|
|
149
|
+
return _board_heat_score(change_pct=change_pct, rank=rank)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def classify_hotspot_stage(
|
|
153
|
+
*,
|
|
154
|
+
state: str = "",
|
|
155
|
+
trend_score: float | None = None,
|
|
156
|
+
cooling_score: float | None = None,
|
|
157
|
+
persistence_score: float | None = None,
|
|
158
|
+
latest_score: float | None = None,
|
|
159
|
+
observations: int | None = None,
|
|
160
|
+
) -> str:
|
|
161
|
+
"""Classify a hotspot into a coarse lifecycle stage."""
|
|
162
|
+
state_text = _safe_text(state).lower()
|
|
163
|
+
trend = _safe_float(trend_score) or 0.0
|
|
164
|
+
cooling = _safe_float(cooling_score) or 0.0
|
|
165
|
+
persistence = _safe_float(persistence_score) or 0.0
|
|
166
|
+
latest = _safe_float(latest_score) or 0.0
|
|
167
|
+
obs = int(_safe_float(observations) or 0)
|
|
168
|
+
|
|
169
|
+
if state_text in {"weakening", "cooling"} and (latest < 60 or trend <= -5):
|
|
170
|
+
return "降温退潮"
|
|
171
|
+
if cooling >= 8 and (latest < 60 or trend <= -5):
|
|
172
|
+
return "降温退潮"
|
|
173
|
+
if cooling >= 5:
|
|
174
|
+
return "分歧放量"
|
|
175
|
+
if latest >= 75 and trend >= 8 and persistence >= 50:
|
|
176
|
+
return "加速主升"
|
|
177
|
+
if state_text == "persistent_hot" or persistence >= 66.6667:
|
|
178
|
+
return "确认扩散"
|
|
179
|
+
if trend >= 5 and obs >= 2:
|
|
180
|
+
return "确认扩散"
|
|
181
|
+
return "初次异动"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def resolve_hotspot_topic(
|
|
185
|
+
topic: str,
|
|
186
|
+
*,
|
|
187
|
+
provider: str | object | None = None,
|
|
188
|
+
hotspots: list[HotspotSummary | dict[str, Any]] | None = None,
|
|
189
|
+
fallback_cache_path: str | Path | None = None,
|
|
190
|
+
max_boards: int = 500,
|
|
191
|
+
source_errors: list[str] | None = None,
|
|
192
|
+
) -> HotspotTopicResolution:
|
|
193
|
+
"""Resolve a user topic to deterministic canonical hotspot candidates."""
|
|
194
|
+
topic_text = _safe_text(topic)
|
|
195
|
+
candidates: list[dict[str, Any]] = []
|
|
196
|
+
if hotspots:
|
|
197
|
+
candidates.extend(_topic_candidates_from_hotspots(hotspots, source="cache"))
|
|
198
|
+
|
|
199
|
+
if fallback_cache_path:
|
|
200
|
+
try:
|
|
201
|
+
candidates.extend(_topic_candidates_from_hotspots(load_hotspots_json(fallback_cache_path), source="cache"))
|
|
202
|
+
except FileNotFoundError:
|
|
203
|
+
pass
|
|
204
|
+
except Exception as exc: # noqa: BLE001 - resolver should degrade to provider/query candidates.
|
|
205
|
+
if source_errors is not None:
|
|
206
|
+
source_errors.append(f"last_good_cache: {exc}")
|
|
207
|
+
|
|
208
|
+
if provider is not None:
|
|
209
|
+
provider_errors = source_errors if source_errors is not None else []
|
|
210
|
+
for label, provider_obj in _resolve_provider_chain(provider, provider_errors):
|
|
211
|
+
if provider_obj is None:
|
|
212
|
+
continue
|
|
213
|
+
rows = _load_board_summaries(
|
|
214
|
+
provider_obj,
|
|
215
|
+
max_boards=max_boards,
|
|
216
|
+
source_errors=provider_errors,
|
|
217
|
+
provider_label=label,
|
|
218
|
+
)
|
|
219
|
+
candidates.extend(_topic_candidates_from_board_rows(rows, provider_label=label))
|
|
220
|
+
|
|
221
|
+
return _resolve_topic_from_candidates(topic_text, candidates)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def score_hotspot_stock(row: dict[str, Any] | pd.Series) -> float:
|
|
225
|
+
"""Score a constituent stock for hotspot leadership strength."""
|
|
226
|
+
change = _safe_float(_row_value(row, ["change_pct", "涨跌幅", "涨幅"])) or 0.0
|
|
227
|
+
amount = _safe_float(_row_value(row, ["amount", "成交额", "成交金额"])) or 0.0
|
|
228
|
+
turnover = _safe_float(_row_value(row, ["turnover_rate", "换手率"])) or 0.0
|
|
229
|
+
volume_ratio = _safe_float(_row_value(row, ["volume_ratio", "量比"])) or 0.0
|
|
230
|
+
net_inflow = _safe_float(_row_value(row, ["net_inflow", "主力净流入", "主力净流入-净额"])) or 0.0
|
|
231
|
+
is_limit_up = _safe_bool(_row_value(row, ["is_limit_up", "涨停", "是否涨停"]))
|
|
232
|
+
active_days = int(_safe_float(_row_value(row, ["active_days", "连续活跃", "活跃天数"])) or 0)
|
|
233
|
+
evidence_count = int(_safe_float(_row_value(row, ["evidence_count", "证据数", "线索数"])) or 0)
|
|
234
|
+
|
|
235
|
+
amount_score = 0.0
|
|
236
|
+
if amount > 0:
|
|
237
|
+
amount_score = _clamp((math.log10(amount) - 6.0) / 4.0 * 18.0, 0.0, 18.0)
|
|
238
|
+
|
|
239
|
+
inflow_score = 0.0
|
|
240
|
+
if net_inflow > 0:
|
|
241
|
+
inflow_score = _clamp((math.log10(net_inflow) - 5.0) / 4.0 * 12.0, 0.0, 12.0)
|
|
242
|
+
elif net_inflow < 0:
|
|
243
|
+
inflow_score = -_clamp((math.log10(abs(net_inflow)) - 5.0) / 4.0 * 8.0, 0.0, 8.0)
|
|
244
|
+
|
|
245
|
+
score = 35.0
|
|
246
|
+
score += _clamp(change * 2.7, -18.0, 32.0)
|
|
247
|
+
score += amount_score
|
|
248
|
+
score += _clamp(turnover * 1.1, 0.0, 14.0)
|
|
249
|
+
score += _clamp(volume_ratio * 3.0, 0.0, 12.0)
|
|
250
|
+
score += inflow_score
|
|
251
|
+
score += 8.0 if is_limit_up else 0.0
|
|
252
|
+
score += _clamp(active_days * 2.5, 0.0, 8.0)
|
|
253
|
+
score += _clamp(evidence_count * 2.0, 0.0, 8.0)
|
|
254
|
+
return round(_clamp(score, 0.0, 100.0), 4)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def assign_stock_roles(scored_rows: list[dict[str, Any] | HotspotStock]) -> list[HotspotStock]:
|
|
258
|
+
"""Sort scored constituents and assign hotspot roles."""
|
|
259
|
+
stocks = [_coerce_hotspot_stock(item) for item in scored_rows]
|
|
260
|
+
stocks = sorted(
|
|
261
|
+
stocks,
|
|
262
|
+
key=lambda item: (
|
|
263
|
+
item.hot_stock_score,
|
|
264
|
+
item.change_pct if item.change_pct is not None else -999.0,
|
|
265
|
+
item.amount if item.amount is not None else -1.0,
|
|
266
|
+
item.code,
|
|
267
|
+
),
|
|
268
|
+
reverse=True,
|
|
269
|
+
)
|
|
270
|
+
if not stocks:
|
|
271
|
+
return []
|
|
272
|
+
|
|
273
|
+
top_score = stocks[0].hot_stock_score
|
|
274
|
+
for idx, stock in enumerate(stocks):
|
|
275
|
+
change = stock.change_pct or 0.0
|
|
276
|
+
if idx == 0 and stock.hot_stock_score >= 70:
|
|
277
|
+
role = "核心龙头"
|
|
278
|
+
elif idx <= 2 and stock.hot_stock_score >= max(68.0, top_score - 8.0) and change >= 5.0:
|
|
279
|
+
role = "核心龙头"
|
|
280
|
+
elif stock.hot_stock_score >= 62.0 and change >= 3.0:
|
|
281
|
+
role = "助攻"
|
|
282
|
+
elif stock.hot_stock_score >= 48.0 and change >= 0:
|
|
283
|
+
role = "补涨"
|
|
284
|
+
elif stock.hot_stock_score >= 38.0:
|
|
285
|
+
role = "后排"
|
|
286
|
+
else:
|
|
287
|
+
role = "掉队"
|
|
288
|
+
stock.role = role
|
|
289
|
+
return stocks
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def discover_hotspots(
|
|
293
|
+
*,
|
|
294
|
+
provider: str | object = "akshare",
|
|
295
|
+
max_boards: int = 80,
|
|
296
|
+
history_path: str | Path | None = None,
|
|
297
|
+
fallback_cache_path: str | Path | None = None,
|
|
298
|
+
top: int = 20,
|
|
299
|
+
) -> HotspotResults:
|
|
300
|
+
"""Discover ranked concept/industry hotspots from a provider."""
|
|
301
|
+
source_errors: list[str] = []
|
|
302
|
+
provider_chain = _resolve_provider_chain(provider, source_errors)
|
|
303
|
+
provider_used = ""
|
|
304
|
+
rows: list[dict[str, Any]] = []
|
|
305
|
+
|
|
306
|
+
for label, provider_obj in provider_chain:
|
|
307
|
+
provider_used = label or provider_used
|
|
308
|
+
if provider_obj is None:
|
|
309
|
+
continue
|
|
310
|
+
error_count = len(source_errors)
|
|
311
|
+
rows = _load_board_summaries(
|
|
312
|
+
provider_obj,
|
|
313
|
+
max_boards=max_boards,
|
|
314
|
+
source_errors=source_errors,
|
|
315
|
+
provider_label=label,
|
|
316
|
+
)
|
|
317
|
+
if rows:
|
|
318
|
+
provider_used = label
|
|
319
|
+
break
|
|
320
|
+
if len(source_errors) == error_count:
|
|
321
|
+
source_errors.append(f"{label}: returned no hotspot rows")
|
|
322
|
+
|
|
323
|
+
if not rows:
|
|
324
|
+
if fallback_cache_path and not source_errors and provider_used == "none":
|
|
325
|
+
source_errors.append("none: no live provider requested")
|
|
326
|
+
fallback = _load_fallback_hotspots(
|
|
327
|
+
fallback_cache_path,
|
|
328
|
+
source_errors=source_errors,
|
|
329
|
+
top=top,
|
|
330
|
+
)
|
|
331
|
+
if fallback is not None:
|
|
332
|
+
return fallback
|
|
333
|
+
return HotspotResults(
|
|
334
|
+
[],
|
|
335
|
+
provider_used=provider_used,
|
|
336
|
+
fallback_used=False,
|
|
337
|
+
source_errors=source_errors,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
trends = _load_history_trends(history_path)
|
|
341
|
+
summaries: list[HotspotSummary] = []
|
|
342
|
+
for row in rows:
|
|
343
|
+
topic = row["topic"]
|
|
344
|
+
trend = trends.get(topic, {})
|
|
345
|
+
latest_score = _safe_float(trend.get("board_heat_latest_score"))
|
|
346
|
+
trend_score = _safe_float(trend.get("board_heat_trend_score"))
|
|
347
|
+
persistence_score = _safe_float(trend.get("board_heat_persistence_score"))
|
|
348
|
+
cooling_score = _safe_float(trend.get("board_heat_cooling_score"))
|
|
349
|
+
observations = int(_safe_float(trend.get("board_heat_observations")) or 0)
|
|
350
|
+
state = _safe_text(trend.get("board_heat_state"))
|
|
351
|
+
heat_score = latest_score if latest_score is not None else float(row["heat_score"])
|
|
352
|
+
stage = classify_hotspot_stage(
|
|
353
|
+
state=state,
|
|
354
|
+
trend_score=trend_score,
|
|
355
|
+
cooling_score=cooling_score,
|
|
356
|
+
persistence_score=persistence_score,
|
|
357
|
+
latest_score=heat_score,
|
|
358
|
+
observations=observations,
|
|
359
|
+
)
|
|
360
|
+
summaries.append(HotspotSummary(
|
|
361
|
+
topic=topic,
|
|
362
|
+
name=topic,
|
|
363
|
+
source=row.get("source", ""),
|
|
364
|
+
rank=row.get("rank"),
|
|
365
|
+
change_pct=row.get("change_pct"),
|
|
366
|
+
heat_score=round(heat_score, 4),
|
|
367
|
+
trend_score=trend_score,
|
|
368
|
+
persistence_score=persistence_score,
|
|
369
|
+
cooling_score=cooling_score,
|
|
370
|
+
observations=observations,
|
|
371
|
+
state=state,
|
|
372
|
+
stage=stage,
|
|
373
|
+
canonical_topic=topic,
|
|
374
|
+
aliases=[topic],
|
|
375
|
+
))
|
|
376
|
+
|
|
377
|
+
ranked = sorted(summaries, key=_hotspot_sort_key, reverse=True)[:max(int(top), 0)]
|
|
378
|
+
for summary in ranked:
|
|
379
|
+
provider_obj = next((obj for label, obj in provider_chain if label == provider_used), None)
|
|
380
|
+
stocks = _load_scored_constituents(
|
|
381
|
+
provider_obj,
|
|
382
|
+
summary.topic,
|
|
383
|
+
source=summary.source,
|
|
384
|
+
source_errors=source_errors,
|
|
385
|
+
provider_label=provider_used,
|
|
386
|
+
) if provider_obj is not None else []
|
|
387
|
+
summary.sample_stock_count = len(stocks)
|
|
388
|
+
_set_summary_leaders(summary, stocks)
|
|
389
|
+
if not stocks:
|
|
390
|
+
fallback_summary = _find_fallback_hotspot(summary.topic, fallback_cache_path, source_errors=source_errors)
|
|
391
|
+
fallback_stocks = _leader_fallback_stocks(
|
|
392
|
+
fallback_summary,
|
|
393
|
+
stale_age_hours=_cache_stale_age_hours(fallback_cache_path),
|
|
394
|
+
)
|
|
395
|
+
if fallback_stocks:
|
|
396
|
+
summary.sample_stock_count = len(fallback_stocks)
|
|
397
|
+
summary.fallback_used = True
|
|
398
|
+
_set_summary_leaders(summary, fallback_stocks)
|
|
399
|
+
_add_missing_fields(summary, ["live_stocks"])
|
|
400
|
+
else:
|
|
401
|
+
_add_missing_fields(summary, ["stocks", "leader_stocks"])
|
|
402
|
+
return _with_result_metadata(
|
|
403
|
+
ranked,
|
|
404
|
+
provider_used=provider_used,
|
|
405
|
+
fallback_used=False,
|
|
406
|
+
source_errors=source_errors,
|
|
407
|
+
stale=False,
|
|
408
|
+
stale_age_hours=None,
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def get_hotspot_detail(
|
|
413
|
+
topic: str,
|
|
414
|
+
*,
|
|
415
|
+
provider: str | object = "akshare",
|
|
416
|
+
top_stocks: int = 10,
|
|
417
|
+
timeline_path: str | Path | None = None,
|
|
418
|
+
history_path: str | Path | None = None,
|
|
419
|
+
fallback_cache_path: str | Path | None = None,
|
|
420
|
+
) -> HotspotDetail:
|
|
421
|
+
"""Return one hotspot detail view with constituent stock roles and timeline."""
|
|
422
|
+
topic_text = _safe_text(topic)
|
|
423
|
+
source_errors: list[str] = []
|
|
424
|
+
provider_chain = _resolve_provider_chain(provider, source_errors)
|
|
425
|
+
provider_used = ""
|
|
426
|
+
fallback_hotspots = _load_hotspot_cache_for_fallback(fallback_cache_path, source_errors=source_errors)
|
|
427
|
+
cache_resolution = _resolve_topic_from_candidates(
|
|
428
|
+
topic_text,
|
|
429
|
+
_topic_candidates_from_hotspots(fallback_hotspots, source="cache"),
|
|
430
|
+
)
|
|
431
|
+
fallback_summary = _fallback_summary_for_resolution(topic_text, fallback_hotspots, cache_resolution)
|
|
432
|
+
best_resolution = cache_resolution
|
|
433
|
+
summary = HotspotSummary(
|
|
434
|
+
topic=topic_text,
|
|
435
|
+
name=topic_text,
|
|
436
|
+
source="",
|
|
437
|
+
canonical_topic=cache_resolution.canonical_topic,
|
|
438
|
+
aliases=cache_resolution.aliases,
|
|
439
|
+
resolver_candidates=cache_resolution.candidates,
|
|
440
|
+
)
|
|
441
|
+
stocks: list[HotspotStock] = []
|
|
442
|
+
lookup_topic_used = topic_text
|
|
443
|
+
|
|
444
|
+
if topic_text:
|
|
445
|
+
for label, provider_obj in provider_chain:
|
|
446
|
+
provider_used = label or provider_used
|
|
447
|
+
if provider_obj is None:
|
|
448
|
+
continue
|
|
449
|
+
board_rows = _load_board_summaries(
|
|
450
|
+
provider_obj,
|
|
451
|
+
max_boards=500,
|
|
452
|
+
source_errors=source_errors,
|
|
453
|
+
provider_label=label,
|
|
454
|
+
)
|
|
455
|
+
provider_resolution = _resolve_topic_from_candidates(
|
|
456
|
+
topic_text,
|
|
457
|
+
[
|
|
458
|
+
*_topic_candidates_from_board_rows(board_rows, provider_label=label),
|
|
459
|
+
*_topic_candidates_from_hotspots(fallback_hotspots, source="cache"),
|
|
460
|
+
],
|
|
461
|
+
)
|
|
462
|
+
if provider_resolution.candidates:
|
|
463
|
+
best_resolution = provider_resolution
|
|
464
|
+
lookup_topic = provider_resolution.canonical_topic or cache_resolution.canonical_topic or topic_text
|
|
465
|
+
lookup_topic_used = lookup_topic
|
|
466
|
+
row = _find_board_summary_in_rows(board_rows, lookup_topic)
|
|
467
|
+
if row:
|
|
468
|
+
row_heat = _safe_float(row.get("heat_score"))
|
|
469
|
+
summary = HotspotSummary(
|
|
470
|
+
topic=topic_text,
|
|
471
|
+
name=lookup_topic,
|
|
472
|
+
source=row.get("source", ""),
|
|
473
|
+
rank=row.get("rank"),
|
|
474
|
+
change_pct=row.get("change_pct"),
|
|
475
|
+
heat_score=row_heat if row_heat is not None else 50.0,
|
|
476
|
+
canonical_topic=lookup_topic,
|
|
477
|
+
aliases=provider_resolution.aliases,
|
|
478
|
+
resolver_candidates=provider_resolution.candidates,
|
|
479
|
+
)
|
|
480
|
+
source = summary.source or "concept"
|
|
481
|
+
stocks = _load_scored_constituents(
|
|
482
|
+
provider_obj,
|
|
483
|
+
lookup_topic,
|
|
484
|
+
source=source,
|
|
485
|
+
source_errors=source_errors,
|
|
486
|
+
provider_label=label,
|
|
487
|
+
)
|
|
488
|
+
if stocks and not summary.source:
|
|
489
|
+
summary.source = source
|
|
490
|
+
if not stocks and source != "industry":
|
|
491
|
+
stocks = _load_scored_constituents(
|
|
492
|
+
provider_obj,
|
|
493
|
+
lookup_topic,
|
|
494
|
+
source="industry",
|
|
495
|
+
source_errors=source_errors,
|
|
496
|
+
provider_label=label,
|
|
497
|
+
)
|
|
498
|
+
if stocks:
|
|
499
|
+
summary.source = "industry"
|
|
500
|
+
if row or stocks:
|
|
501
|
+
provider_used = label
|
|
502
|
+
break
|
|
503
|
+
|
|
504
|
+
if not stocks and not summary.source and fallback_summary is not None:
|
|
505
|
+
cached_summary = _copy_hotspot_summary(fallback_summary)
|
|
506
|
+
if cached_summary.topic != topic_text:
|
|
507
|
+
cached_summary.name = cached_summary.topic
|
|
508
|
+
cached_summary.topic = topic_text
|
|
509
|
+
summary = cached_summary
|
|
510
|
+
summary.canonical_topic = cache_resolution.canonical_topic or fallback_summary.canonical_topic or fallback_summary.topic
|
|
511
|
+
summary.aliases = cache_resolution.aliases or summary.aliases
|
|
512
|
+
summary.resolver_candidates = cache_resolution.candidates
|
|
513
|
+
stale_age = _cache_stale_age_hours(fallback_cache_path)
|
|
514
|
+
_apply_summary_metadata(
|
|
515
|
+
summary,
|
|
516
|
+
provider_used="last_good_cache",
|
|
517
|
+
fallback_used=True,
|
|
518
|
+
source_errors=source_errors or ["none: no live detail rows"],
|
|
519
|
+
stale=True,
|
|
520
|
+
stale_age_hours=stale_age,
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
if best_resolution.candidates:
|
|
524
|
+
summary.canonical_topic = best_resolution.canonical_topic or summary.canonical_topic
|
|
525
|
+
summary.aliases = best_resolution.aliases
|
|
526
|
+
summary.resolver_candidates = best_resolution.candidates
|
|
527
|
+
if not summary.canonical_topic and topic_text:
|
|
528
|
+
summary.canonical_topic = topic_text if not best_resolution.unresolved else ""
|
|
529
|
+
if stocks and not summary.canonical_topic:
|
|
530
|
+
summary.canonical_topic = lookup_topic_used or topic_text
|
|
531
|
+
|
|
532
|
+
if not stocks:
|
|
533
|
+
stale_age = _cache_stale_age_hours(fallback_cache_path)
|
|
534
|
+
leader_source = fallback_summary if fallback_summary is not None else summary
|
|
535
|
+
stocks = _leader_fallback_stocks(leader_source, stale_age_hours=stale_age)
|
|
536
|
+
if stocks:
|
|
537
|
+
summary.fallback_used = True
|
|
538
|
+
summary.stale = summary.stale or fallback_summary is not None
|
|
539
|
+
summary.stale_age_hours = stale_age if fallback_summary is not None else summary.stale_age_hours
|
|
540
|
+
_add_missing_fields(summary, ["live_stocks"])
|
|
541
|
+
else:
|
|
542
|
+
_add_missing_fields(summary, ["stocks", "leader_stocks"])
|
|
543
|
+
|
|
544
|
+
trends = _load_history_trends(history_path)
|
|
545
|
+
trend = (
|
|
546
|
+
trends.get(summary.canonical_topic or "")
|
|
547
|
+
or trends.get(topic_text, {})
|
|
548
|
+
or trends.get(summary.name, {})
|
|
549
|
+
)
|
|
550
|
+
latest_score = _safe_float(trend.get("board_heat_latest_score"))
|
|
551
|
+
summary.heat_score = round(latest_score if latest_score is not None else summary.heat_score, 4)
|
|
552
|
+
summary.trend_score = _safe_float(trend.get("board_heat_trend_score"))
|
|
553
|
+
summary.persistence_score = _safe_float(trend.get("board_heat_persistence_score"))
|
|
554
|
+
summary.cooling_score = _safe_float(trend.get("board_heat_cooling_score"))
|
|
555
|
+
summary.observations = int(_safe_float(trend.get("board_heat_observations")) or 0)
|
|
556
|
+
summary.state = _safe_text(trend.get("board_heat_state"))
|
|
557
|
+
summary.stage = classify_hotspot_stage(
|
|
558
|
+
state=summary.state,
|
|
559
|
+
trend_score=summary.trend_score,
|
|
560
|
+
cooling_score=summary.cooling_score,
|
|
561
|
+
persistence_score=summary.persistence_score,
|
|
562
|
+
latest_score=summary.heat_score,
|
|
563
|
+
observations=summary.observations,
|
|
564
|
+
)
|
|
565
|
+
if not summary.fallback_used or stocks:
|
|
566
|
+
summary.sample_stock_count = len(stocks)
|
|
567
|
+
_set_summary_leaders(summary, stocks)
|
|
568
|
+
if not summary.provider_used:
|
|
569
|
+
_apply_summary_metadata(
|
|
570
|
+
summary,
|
|
571
|
+
provider_used=provider_used,
|
|
572
|
+
fallback_used=summary.fallback_used,
|
|
573
|
+
source_errors=source_errors,
|
|
574
|
+
stale=summary.stale,
|
|
575
|
+
stale_age_hours=summary.stale_age_hours,
|
|
576
|
+
)
|
|
577
|
+
_finalize_summary_quality(summary, stock_count=len(stocks))
|
|
578
|
+
|
|
579
|
+
timeline: list[TimelineEvent] = []
|
|
580
|
+
if timeline_path:
|
|
581
|
+
try:
|
|
582
|
+
timeline = load_hotspot_timeline(timeline_path, topic=summary.canonical_topic or topic_text)
|
|
583
|
+
if summary.canonical_topic and summary.canonical_topic != topic_text:
|
|
584
|
+
timeline.extend(load_hotspot_timeline(timeline_path, topic=topic_text))
|
|
585
|
+
timeline = _dedupe_timeline(timeline)
|
|
586
|
+
except Exception as exc: # noqa: BLE001 - timeline is evidence, not a hard dependency.
|
|
587
|
+
summary.source_errors = _dedupe_errors([*summary.source_errors, f"timeline: {exc}"])
|
|
588
|
+
_add_missing_fields(summary, ["timeline"])
|
|
589
|
+
_finalize_summary_quality(summary, stock_count=len(stocks))
|
|
590
|
+
capped_stocks = stocks[:max(int(top_stocks), 0)]
|
|
591
|
+
route = build_hotspot_route(summary, timeline, capped_stocks)
|
|
592
|
+
return HotspotDetail(summary=summary, stocks=capped_stocks, timeline=timeline, route=route)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def build_hotspot_route(
|
|
596
|
+
summary: HotspotSummary,
|
|
597
|
+
timeline: list[TimelineEvent] | None = None,
|
|
598
|
+
stocks: list[HotspotStock] | None = None,
|
|
599
|
+
*,
|
|
600
|
+
max_items: int = 5,
|
|
601
|
+
max_description_chars: int = 180,
|
|
602
|
+
) -> list[HotspotRouteItem]:
|
|
603
|
+
"""Build compact, display-ready route events without dropping raw timeline data."""
|
|
604
|
+
events = timeline or []
|
|
605
|
+
if events:
|
|
606
|
+
return _build_route_from_timeline(
|
|
607
|
+
events,
|
|
608
|
+
max_items=max_items,
|
|
609
|
+
max_description_chars=max_description_chars,
|
|
610
|
+
)
|
|
611
|
+
return [_build_summary_route_item(summary, stocks or [], max_description_chars=max_description_chars)]
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def load_hotspot_history(path_like: str | Path) -> list[dict[str, Any]]:
|
|
615
|
+
"""Load hotspot history JSONL records, skipping malformed lines."""
|
|
616
|
+
path = Path(path_like)
|
|
617
|
+
if not path.is_file():
|
|
618
|
+
raise FileNotFoundError(f"Hotspot history file not found: {path}")
|
|
619
|
+
rows: list[dict[str, Any]] = []
|
|
620
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
621
|
+
line = line.strip()
|
|
622
|
+
if not line:
|
|
623
|
+
continue
|
|
624
|
+
try:
|
|
625
|
+
item = json.loads(line)
|
|
626
|
+
except json.JSONDecodeError:
|
|
627
|
+
continue
|
|
628
|
+
if not isinstance(item, dict):
|
|
629
|
+
continue
|
|
630
|
+
topic = _safe_text(item.get("topic") or item.get("board"))
|
|
631
|
+
heat = _safe_float(_row_value(item, ["heat_score", "max_board_heat_score"]))
|
|
632
|
+
generated_at = _safe_text(item.get("generated_at"))
|
|
633
|
+
if not topic or heat is None or heat < 0 or heat > 100:
|
|
634
|
+
continue
|
|
635
|
+
item["topic"] = topic
|
|
636
|
+
item["board"] = _safe_text(item.get("board")) or topic
|
|
637
|
+
item["heat_score"] = heat
|
|
638
|
+
item["max_board_heat_score"] = heat
|
|
639
|
+
item["generated_at"] = generated_at
|
|
640
|
+
rows.append(item)
|
|
641
|
+
return sorted(rows, key=lambda item: (str(item.get("generated_at", "")), str(item.get("topic", ""))))
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def append_hotspot_history(
|
|
645
|
+
path_like: str | Path,
|
|
646
|
+
hotspots: list[HotspotSummary | dict[str, Any]],
|
|
647
|
+
*,
|
|
648
|
+
generated_at: str,
|
|
649
|
+
) -> Path:
|
|
650
|
+
"""Append hotspot summaries to a trend-compatible JSONL history file."""
|
|
651
|
+
path = Path(path_like)
|
|
652
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
653
|
+
with path.open("a", encoding="utf-8") as handle:
|
|
654
|
+
for hotspot in hotspots:
|
|
655
|
+
item = asdict(hotspot) if isinstance(hotspot, HotspotSummary) else dict(hotspot)
|
|
656
|
+
topic = _safe_text(item.get("topic") or item.get("name"))
|
|
657
|
+
heat = _safe_float(item.get("heat_score"))
|
|
658
|
+
if not topic or heat is None:
|
|
659
|
+
continue
|
|
660
|
+
record = {
|
|
661
|
+
"generated_at": generated_at,
|
|
662
|
+
"topic": topic,
|
|
663
|
+
"board": topic,
|
|
664
|
+
"source": _safe_text(item.get("source")),
|
|
665
|
+
"rank": item.get("rank"),
|
|
666
|
+
"change_pct": item.get("change_pct"),
|
|
667
|
+
"heat_score": heat,
|
|
668
|
+
"max_board_heat_score": heat,
|
|
669
|
+
"sample_stock_count": int(_safe_float(item.get("sample_stock_count")) or 0),
|
|
670
|
+
"leaders": item.get("leaders") if isinstance(item.get("leaders"), list) else [],
|
|
671
|
+
}
|
|
672
|
+
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
673
|
+
return path
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def load_hotspot_timeline(path_like: str | Path, topic: str | None = None) -> list[TimelineEvent]:
|
|
677
|
+
"""Load timeline JSONL records, sorted by date, skipping malformed rows."""
|
|
678
|
+
path = Path(path_like)
|
|
679
|
+
if not path.is_file():
|
|
680
|
+
raise FileNotFoundError(f"Hotspot timeline file not found: {path}")
|
|
681
|
+
topic_text = _safe_text(topic)
|
|
682
|
+
events: list[TimelineEvent] = []
|
|
683
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
684
|
+
line = line.strip()
|
|
685
|
+
if not line:
|
|
686
|
+
continue
|
|
687
|
+
try:
|
|
688
|
+
item = json.loads(line)
|
|
689
|
+
except json.JSONDecodeError:
|
|
690
|
+
continue
|
|
691
|
+
if not isinstance(item, dict):
|
|
692
|
+
continue
|
|
693
|
+
if topic_text and not _timeline_matches_topic(item, topic_text):
|
|
694
|
+
continue
|
|
695
|
+
date = _safe_text(item.get("date") or item.get("generated_at") or item.get("time"))
|
|
696
|
+
source = _safe_text(item.get("source"))
|
|
697
|
+
title = _safe_text(item.get("title"))
|
|
698
|
+
if not date or not source or not title:
|
|
699
|
+
continue
|
|
700
|
+
events.append(TimelineEvent(
|
|
701
|
+
date=date,
|
|
702
|
+
source=source,
|
|
703
|
+
title=title,
|
|
704
|
+
event_type=_safe_text(item.get("event_type")) or "news",
|
|
705
|
+
impact_score=round(_safe_float(item.get("impact_score")) or 0.0, 4),
|
|
706
|
+
related_codes=_normalize_related_codes(item.get("related_codes")),
|
|
707
|
+
description=_safe_text(item.get("description") or item.get("summary") or item.get("content")),
|
|
708
|
+
url=_safe_text(item.get("url") or item.get("link")),
|
|
709
|
+
published_at=_safe_text(item.get("published_at") or item.get("publish_time") or item.get("time")),
|
|
710
|
+
))
|
|
711
|
+
return sorted(events, key=lambda item: (item.date, item.source, item.title))
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def load_hotspots_json(path_like: str | Path) -> list[HotspotSummary]:
|
|
715
|
+
"""Load a last-good hotspot cache, skipping malformed rows."""
|
|
716
|
+
path = Path(path_like)
|
|
717
|
+
if not path.is_file():
|
|
718
|
+
raise FileNotFoundError(f"Hotspot cache file not found: {path}")
|
|
719
|
+
try:
|
|
720
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
721
|
+
except json.JSONDecodeError:
|
|
722
|
+
return []
|
|
723
|
+
|
|
724
|
+
if isinstance(payload, dict) and any(key in payload for key in ("topic", "board", "hotspot")):
|
|
725
|
+
raw_rows = [payload]
|
|
726
|
+
elif isinstance(payload, dict):
|
|
727
|
+
raw_rows = (
|
|
728
|
+
payload.get("hotspots")
|
|
729
|
+
or payload.get("rows")
|
|
730
|
+
or payload.get("items")
|
|
731
|
+
or payload.get("data")
|
|
732
|
+
or []
|
|
733
|
+
)
|
|
734
|
+
if not raw_rows and all(isinstance(value, dict) for value in payload.values()):
|
|
735
|
+
raw_rows = list(payload.values())
|
|
736
|
+
else:
|
|
737
|
+
raw_rows = payload
|
|
738
|
+
if not isinstance(raw_rows, list):
|
|
739
|
+
return []
|
|
740
|
+
|
|
741
|
+
rows: list[HotspotSummary] = []
|
|
742
|
+
for item in raw_rows:
|
|
743
|
+
summary = _coerce_hotspot_summary(item)
|
|
744
|
+
if summary is not None:
|
|
745
|
+
rows.append(summary)
|
|
746
|
+
return rows
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def save_hotspots_json(path_like: str | Path, hotspots: list[HotspotSummary]) -> Path:
|
|
750
|
+
path = Path(path_like)
|
|
751
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
752
|
+
generated_at = datetime.now(timezone.utc).isoformat()
|
|
753
|
+
rows = [asdict(item) for item in hotspots]
|
|
754
|
+
payload = {
|
|
755
|
+
"schema_version": 2,
|
|
756
|
+
"generated_at": generated_at,
|
|
757
|
+
"metadata": {
|
|
758
|
+
"schema_version": 2,
|
|
759
|
+
"asset_type": "hotspot_cache",
|
|
760
|
+
"generated_at": generated_at,
|
|
761
|
+
"row_count": len(rows),
|
|
762
|
+
"last_good": True,
|
|
763
|
+
"quality_counts": _quality_counts(hotspots),
|
|
764
|
+
},
|
|
765
|
+
"hotspots": rows,
|
|
766
|
+
}
|
|
767
|
+
tmp_path = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
768
|
+
try:
|
|
769
|
+
tmp_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
770
|
+
os.replace(tmp_path, path)
|
|
771
|
+
finally:
|
|
772
|
+
if tmp_path.exists():
|
|
773
|
+
tmp_path.unlink()
|
|
774
|
+
return path
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def hotspot_detail_to_dict(detail: HotspotDetail) -> dict[str, Any]:
|
|
778
|
+
return {
|
|
779
|
+
"summary": asdict(detail.summary),
|
|
780
|
+
"stocks": [asdict(item) for item in detail.stocks],
|
|
781
|
+
"timeline": [asdict(item) for item in detail.timeline],
|
|
782
|
+
"route": [asdict(item) for item in detail.route],
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def _resolve_provider(provider: str | object) -> object | None:
|
|
787
|
+
source_errors: list[str] = []
|
|
788
|
+
for _, provider_obj in _resolve_provider_chain(provider, source_errors):
|
|
789
|
+
if provider_obj is not None:
|
|
790
|
+
return provider_obj
|
|
791
|
+
return None
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _resolve_provider_chain(
|
|
795
|
+
provider: str | object,
|
|
796
|
+
source_errors: list[str],
|
|
797
|
+
) -> list[tuple[str, object | None]]:
|
|
798
|
+
if not isinstance(provider, str):
|
|
799
|
+
return [(_provider_label(provider), provider)]
|
|
800
|
+
|
|
801
|
+
names = [part.strip().lower() for part in provider.split(",") if part.strip()]
|
|
802
|
+
if not names:
|
|
803
|
+
names = ["none"]
|
|
804
|
+
|
|
805
|
+
resolved: list[tuple[str, object | None]] = []
|
|
806
|
+
for name in names:
|
|
807
|
+
if name in {"none", "off", "false"}:
|
|
808
|
+
resolved.append(("none", None))
|
|
809
|
+
continue
|
|
810
|
+
if name == "akshare":
|
|
811
|
+
try:
|
|
812
|
+
import akshare as ak
|
|
813
|
+
except Exception as exc: # noqa: BLE001 - provider import is optional.
|
|
814
|
+
source_errors.append(f"akshare: {exc}")
|
|
815
|
+
continue
|
|
816
|
+
resolved.append(("akshare", ak))
|
|
817
|
+
continue
|
|
818
|
+
source_errors.append(f"unknown provider '{name}'")
|
|
819
|
+
return resolved
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def _load_board_summaries(
|
|
823
|
+
provider: object,
|
|
824
|
+
*,
|
|
825
|
+
max_boards: int,
|
|
826
|
+
source_errors: list[str] | None = None,
|
|
827
|
+
provider_label: str = "",
|
|
828
|
+
) -> list[dict[str, Any]]:
|
|
829
|
+
rows: list[dict[str, Any]] = []
|
|
830
|
+
specs = [
|
|
831
|
+
("concept", "stock_board_concept_name_em"),
|
|
832
|
+
("industry", "stock_board_industry_name_em"),
|
|
833
|
+
]
|
|
834
|
+
limit = max(int(max_boards), 1)
|
|
835
|
+
for source, method_name in specs:
|
|
836
|
+
frame = _call_provider_frame(
|
|
837
|
+
provider,
|
|
838
|
+
method_name,
|
|
839
|
+
source_errors=source_errors,
|
|
840
|
+
provider_label=provider_label,
|
|
841
|
+
)
|
|
842
|
+
if frame is None:
|
|
843
|
+
frame = _mapping_provider_frame(provider, f"{source}_boards")
|
|
844
|
+
if frame is None:
|
|
845
|
+
continue
|
|
846
|
+
rows.extend(_normalize_board_rows(frame, source=source)[:limit])
|
|
847
|
+
deduped: dict[str, dict[str, Any]] = {}
|
|
848
|
+
for row in rows:
|
|
849
|
+
topic = row["topic"]
|
|
850
|
+
existing = deduped.get(topic)
|
|
851
|
+
if existing is None or _board_row_rank_key(row) > _board_row_rank_key(existing):
|
|
852
|
+
deduped[topic] = row
|
|
853
|
+
return sorted(deduped.values(), key=_board_row_rank_key, reverse=True)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _normalize_board_rows(frame: pd.DataFrame, *, source: str) -> list[dict[str, Any]]:
|
|
857
|
+
if frame is None or frame.empty:
|
|
858
|
+
return []
|
|
859
|
+
rows: list[dict[str, Any]] = []
|
|
860
|
+
for idx, row in frame.iterrows():
|
|
861
|
+
topic = _safe_text(_row_value(row, [
|
|
862
|
+
"topic",
|
|
863
|
+
"board",
|
|
864
|
+
"板块名称",
|
|
865
|
+
"概念名称",
|
|
866
|
+
"行业名称",
|
|
867
|
+
"名称",
|
|
868
|
+
"name",
|
|
869
|
+
]))
|
|
870
|
+
if not topic:
|
|
871
|
+
continue
|
|
872
|
+
rank = _safe_float(_row_value(row, ["rank", "排名", "序号"]))
|
|
873
|
+
if rank is None:
|
|
874
|
+
rank = float(idx + 1)
|
|
875
|
+
change_pct = _safe_float(_row_value(row, ["change_pct", "涨跌幅", "涨幅"]))
|
|
876
|
+
heat_score = compute_hotspot_heat_score(change_pct, rank)
|
|
877
|
+
rows.append({
|
|
878
|
+
"topic": topic,
|
|
879
|
+
"source": source,
|
|
880
|
+
"rank": int(rank) if rank is not None else None,
|
|
881
|
+
"change_pct": change_pct,
|
|
882
|
+
"heat_score": heat_score,
|
|
883
|
+
})
|
|
884
|
+
return rows
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _find_board_summary(
|
|
888
|
+
provider: object,
|
|
889
|
+
topic: str,
|
|
890
|
+
*,
|
|
891
|
+
source_errors: list[str] | None = None,
|
|
892
|
+
provider_label: str = "",
|
|
893
|
+
) -> dict[str, Any] | None:
|
|
894
|
+
for row in _load_board_summaries(
|
|
895
|
+
provider,
|
|
896
|
+
max_boards=500,
|
|
897
|
+
source_errors=source_errors,
|
|
898
|
+
provider_label=provider_label,
|
|
899
|
+
):
|
|
900
|
+
if row["topic"] == topic:
|
|
901
|
+
return row
|
|
902
|
+
return None
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def _find_board_summary_in_rows(rows: list[dict[str, Any]], topic: str) -> dict[str, Any] | None:
|
|
906
|
+
topic_key = _normalize_topic_key(topic)
|
|
907
|
+
for row in rows:
|
|
908
|
+
if _normalize_topic_key(row.get("topic")) == topic_key:
|
|
909
|
+
return row
|
|
910
|
+
return None
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def _load_scored_constituents(
|
|
914
|
+
provider: object,
|
|
915
|
+
topic: str,
|
|
916
|
+
*,
|
|
917
|
+
source: str,
|
|
918
|
+
source_errors: list[str] | None = None,
|
|
919
|
+
provider_label: str = "",
|
|
920
|
+
) -> list[HotspotStock]:
|
|
921
|
+
method_names = []
|
|
922
|
+
if source == "industry":
|
|
923
|
+
method_names.append("stock_board_industry_cons_em")
|
|
924
|
+
else:
|
|
925
|
+
method_names.append("stock_board_concept_cons_em")
|
|
926
|
+
method_names.append("stock_board_industry_cons_em")
|
|
927
|
+
frame = None
|
|
928
|
+
for method_name in method_names:
|
|
929
|
+
frame = _call_provider_frame(
|
|
930
|
+
provider,
|
|
931
|
+
method_name,
|
|
932
|
+
source_errors=source_errors,
|
|
933
|
+
provider_label=provider_label,
|
|
934
|
+
symbol=topic,
|
|
935
|
+
)
|
|
936
|
+
if frame is not None:
|
|
937
|
+
break
|
|
938
|
+
if frame is None:
|
|
939
|
+
frame = _mapping_constituents_frame(provider, topic, source=source)
|
|
940
|
+
if frame is None:
|
|
941
|
+
return []
|
|
942
|
+
rows = [asdict(stock) for stock in _normalize_stock_rows(frame)]
|
|
943
|
+
stocks = assign_stock_roles(rows)
|
|
944
|
+
stock_source = f"{provider_label or 'provider'}.{source}_constituents"
|
|
945
|
+
for stock in stocks:
|
|
946
|
+
stock.source = stock.source or stock_source
|
|
947
|
+
stock.source_confidence = stock.source_confidence if stock.source_confidence is not None else 1.0
|
|
948
|
+
stock.fallback_used = False
|
|
949
|
+
return stocks
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def _normalize_stock_rows(frame: pd.DataFrame) -> list[HotspotStock]:
|
|
953
|
+
if frame is None or frame.empty:
|
|
954
|
+
return []
|
|
955
|
+
stocks: list[HotspotStock] = []
|
|
956
|
+
for _, row in frame.iterrows():
|
|
957
|
+
code = _normalize_code(_row_value(row, ["code", "代码", "证券代码"]))
|
|
958
|
+
if not code:
|
|
959
|
+
continue
|
|
960
|
+
change_pct = _safe_float(_row_value(row, ["change_pct", "涨跌幅", "涨幅"]))
|
|
961
|
+
amount = _safe_float(_row_value(row, ["amount", "成交额", "成交金额"]))
|
|
962
|
+
turnover_rate = _safe_float(_row_value(row, ["turnover_rate", "换手率"]))
|
|
963
|
+
volume_ratio = _safe_float(_row_value(row, ["volume_ratio", "量比"]))
|
|
964
|
+
net_inflow = _safe_float(_row_value(row, ["net_inflow", "主力净流入", "主力净流入-净额"]))
|
|
965
|
+
stock = HotspotStock(
|
|
966
|
+
code=code,
|
|
967
|
+
name=_safe_text(_row_value(row, ["name", "名称", "股票名称"])),
|
|
968
|
+
change_pct=change_pct,
|
|
969
|
+
amount=amount,
|
|
970
|
+
turnover_rate=turnover_rate,
|
|
971
|
+
volume_ratio=volume_ratio,
|
|
972
|
+
net_inflow=net_inflow,
|
|
973
|
+
is_limit_up=_safe_bool(_row_value(row, ["is_limit_up", "涨停", "是否涨停"])) or (change_pct or 0) >= 9.8,
|
|
974
|
+
active_days=int(_safe_float(_row_value(row, ["active_days", "连续活跃", "活跃天数"])) or 0),
|
|
975
|
+
evidence_count=int(_safe_float(_row_value(row, ["evidence_count", "证据数", "线索数"])) or 0),
|
|
976
|
+
)
|
|
977
|
+
stock.hot_stock_score = score_hotspot_stock(asdict(stock))
|
|
978
|
+
stocks.append(stock)
|
|
979
|
+
return stocks
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _coerce_hotspot_stock(item: dict[str, Any] | HotspotStock) -> HotspotStock:
|
|
983
|
+
if isinstance(item, HotspotStock):
|
|
984
|
+
stock = item
|
|
985
|
+
else:
|
|
986
|
+
stock = HotspotStock(
|
|
987
|
+
code=_normalize_code(_row_value(item, ["code", "代码"])),
|
|
988
|
+
name=_safe_text(_row_value(item, ["name", "名称"])),
|
|
989
|
+
change_pct=_safe_float(_row_value(item, ["change_pct", "涨跌幅"])),
|
|
990
|
+
amount=_safe_float(_row_value(item, ["amount", "成交额"])),
|
|
991
|
+
turnover_rate=_safe_float(_row_value(item, ["turnover_rate", "换手率"])),
|
|
992
|
+
volume_ratio=_safe_float(_row_value(item, ["volume_ratio", "量比"])),
|
|
993
|
+
net_inflow=_safe_float(_row_value(item, ["net_inflow", "主力净流入"])),
|
|
994
|
+
is_limit_up=_safe_bool(_row_value(item, ["is_limit_up", "涨停"])),
|
|
995
|
+
active_days=int(_safe_float(_row_value(item, ["active_days", "连续活跃"])) or 0),
|
|
996
|
+
evidence_count=int(_safe_float(_row_value(item, ["evidence_count", "证据数"])) or 0),
|
|
997
|
+
role=_safe_text(item.get("role")),
|
|
998
|
+
hot_stock_score=_safe_float(item.get("hot_stock_score")) or 0.0,
|
|
999
|
+
source=_safe_text(item.get("source")),
|
|
1000
|
+
source_confidence=_safe_float(item.get("source_confidence")),
|
|
1001
|
+
fallback_used=_safe_bool(item.get("fallback_used")),
|
|
1002
|
+
)
|
|
1003
|
+
if stock.hot_stock_score <= 0:
|
|
1004
|
+
stock.hot_stock_score = score_hotspot_stock(asdict(stock))
|
|
1005
|
+
return stock
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _coerce_hotspot_summary(item: object) -> HotspotSummary | None:
|
|
1009
|
+
if isinstance(item, HotspotSummary):
|
|
1010
|
+
return item
|
|
1011
|
+
if not isinstance(item, dict):
|
|
1012
|
+
return None
|
|
1013
|
+
topic = _safe_text(_row_value(item, ["topic", "name", "board", "hotspot"]))
|
|
1014
|
+
if not topic:
|
|
1015
|
+
return None
|
|
1016
|
+
heat_score = _safe_float(_row_value(item, ["heat_score", "max_board_heat_score"]))
|
|
1017
|
+
if heat_score is None:
|
|
1018
|
+
heat_score = 50.0
|
|
1019
|
+
if heat_score < 0 or heat_score > 100:
|
|
1020
|
+
return None
|
|
1021
|
+
rank = _safe_float(item.get("rank"))
|
|
1022
|
+
leaders = item.get("leaders")
|
|
1023
|
+
leader_stocks = item.get("leader_stocks")
|
|
1024
|
+
source_errors = item.get("source_errors")
|
|
1025
|
+
missing_fields = item.get("missing_fields")
|
|
1026
|
+
aliases = item.get("aliases")
|
|
1027
|
+
resolver_candidates = item.get("resolver_candidates")
|
|
1028
|
+
return HotspotSummary(
|
|
1029
|
+
topic=topic,
|
|
1030
|
+
name=_safe_text(item.get("name")) or topic,
|
|
1031
|
+
source=_safe_text(item.get("source")),
|
|
1032
|
+
rank=int(rank) if rank is not None else None,
|
|
1033
|
+
change_pct=_safe_float(item.get("change_pct")),
|
|
1034
|
+
heat_score=round(float(heat_score), 4),
|
|
1035
|
+
trend_score=_safe_float(item.get("trend_score")),
|
|
1036
|
+
persistence_score=_safe_float(item.get("persistence_score")),
|
|
1037
|
+
cooling_score=_safe_float(item.get("cooling_score")),
|
|
1038
|
+
observations=int(_safe_float(item.get("observations")) or 0),
|
|
1039
|
+
state=_safe_text(item.get("state")),
|
|
1040
|
+
stage=_safe_text(item.get("stage")) or "初次异动",
|
|
1041
|
+
sample_stock_count=int(_safe_float(item.get("sample_stock_count")) or 0),
|
|
1042
|
+
leaders=[_safe_text(value) for value in leaders if _safe_text(value)] if isinstance(leaders, list) else [],
|
|
1043
|
+
leader_stocks=[
|
|
1044
|
+
_coerce_hotspot_stock(value)
|
|
1045
|
+
for value in leader_stocks
|
|
1046
|
+
if isinstance(value, (dict, HotspotStock))
|
|
1047
|
+
] if isinstance(leader_stocks, list) else [],
|
|
1048
|
+
quality_status=_safe_text(item.get("quality_status")) or "partial",
|
|
1049
|
+
missing_fields=[
|
|
1050
|
+
_safe_text(value)
|
|
1051
|
+
for value in missing_fields
|
|
1052
|
+
if _safe_text(value)
|
|
1053
|
+
] if isinstance(missing_fields, list) else [],
|
|
1054
|
+
canonical_topic=_safe_text(item.get("canonical_topic")) or topic,
|
|
1055
|
+
aliases=[
|
|
1056
|
+
_safe_text(value)
|
|
1057
|
+
for value in aliases
|
|
1058
|
+
if _safe_text(value)
|
|
1059
|
+
] if isinstance(aliases, list) else [],
|
|
1060
|
+
resolver_candidates=[
|
|
1061
|
+
value
|
|
1062
|
+
for value in resolver_candidates
|
|
1063
|
+
if isinstance(value, dict)
|
|
1064
|
+
] if isinstance(resolver_candidates, list) else [],
|
|
1065
|
+
provider_used=_safe_text(item.get("provider_used")),
|
|
1066
|
+
fallback_used=_safe_bool(item.get("fallback_used")),
|
|
1067
|
+
source_errors=[
|
|
1068
|
+
_safe_text(value)
|
|
1069
|
+
for value in source_errors
|
|
1070
|
+
if _safe_text(value)
|
|
1071
|
+
] if isinstance(source_errors, list) else [],
|
|
1072
|
+
stale=_safe_bool(item.get("stale")),
|
|
1073
|
+
stale_age_hours=_safe_float(item.get("stale_age_hours")),
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _topic_candidates_from_hotspots(
|
|
1078
|
+
hotspots: list[HotspotSummary | dict[str, Any]],
|
|
1079
|
+
*,
|
|
1080
|
+
source: str,
|
|
1081
|
+
) -> list[dict[str, Any]]:
|
|
1082
|
+
candidates: list[dict[str, Any]] = []
|
|
1083
|
+
for item in hotspots:
|
|
1084
|
+
summary = _coerce_hotspot_summary(item)
|
|
1085
|
+
if summary is None:
|
|
1086
|
+
continue
|
|
1087
|
+
aliases = _dedupe_texts([
|
|
1088
|
+
summary.topic,
|
|
1089
|
+
summary.name,
|
|
1090
|
+
summary.canonical_topic,
|
|
1091
|
+
*summary.aliases,
|
|
1092
|
+
])
|
|
1093
|
+
candidates.append({
|
|
1094
|
+
"topic": summary.canonical_topic or summary.topic,
|
|
1095
|
+
"name": summary.name or summary.topic,
|
|
1096
|
+
"source": summary.source,
|
|
1097
|
+
"origin": source,
|
|
1098
|
+
"rank": summary.rank,
|
|
1099
|
+
"heat_score": summary.heat_score,
|
|
1100
|
+
"aliases": aliases,
|
|
1101
|
+
})
|
|
1102
|
+
return candidates
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def _topic_candidates_from_board_rows(
|
|
1106
|
+
rows: list[dict[str, Any]],
|
|
1107
|
+
*,
|
|
1108
|
+
provider_label: str,
|
|
1109
|
+
) -> list[dict[str, Any]]:
|
|
1110
|
+
candidates: list[dict[str, Any]] = []
|
|
1111
|
+
for row in rows:
|
|
1112
|
+
topic = _safe_text(row.get("topic"))
|
|
1113
|
+
if not topic:
|
|
1114
|
+
continue
|
|
1115
|
+
candidates.append({
|
|
1116
|
+
"topic": topic,
|
|
1117
|
+
"name": topic,
|
|
1118
|
+
"source": _safe_text(row.get("source")),
|
|
1119
|
+
"origin": provider_label or "provider",
|
|
1120
|
+
"rank": row.get("rank"),
|
|
1121
|
+
"heat_score": _safe_float(row.get("heat_score")) or 0.0,
|
|
1122
|
+
"aliases": [topic],
|
|
1123
|
+
})
|
|
1124
|
+
return candidates
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
def _resolve_topic_from_candidates(
|
|
1128
|
+
topic: str,
|
|
1129
|
+
candidates: list[dict[str, Any]],
|
|
1130
|
+
) -> HotspotTopicResolution:
|
|
1131
|
+
query = _safe_text(topic)
|
|
1132
|
+
ranked: list[dict[str, Any]] = []
|
|
1133
|
+
seen: set[tuple[str, str]] = set()
|
|
1134
|
+
for candidate in candidates:
|
|
1135
|
+
candidate_topic = _safe_text(candidate.get("topic") or candidate.get("name"))
|
|
1136
|
+
if not candidate_topic:
|
|
1137
|
+
continue
|
|
1138
|
+
aliases = _dedupe_texts([
|
|
1139
|
+
candidate_topic,
|
|
1140
|
+
candidate.get("name"),
|
|
1141
|
+
*candidate.get("aliases", []),
|
|
1142
|
+
])
|
|
1143
|
+
confidence, match_type = _topic_match_score(query, aliases)
|
|
1144
|
+
if confidence < 0.3:
|
|
1145
|
+
continue
|
|
1146
|
+
key = (_normalize_topic_key(candidate_topic), _safe_text(candidate.get("origin")))
|
|
1147
|
+
if key in seen:
|
|
1148
|
+
continue
|
|
1149
|
+
seen.add(key)
|
|
1150
|
+
ranked.append({
|
|
1151
|
+
"topic": candidate_topic,
|
|
1152
|
+
"name": _safe_text(candidate.get("name")) or candidate_topic,
|
|
1153
|
+
"source": _safe_text(candidate.get("source")),
|
|
1154
|
+
"origin": _safe_text(candidate.get("origin")),
|
|
1155
|
+
"rank": candidate.get("rank"),
|
|
1156
|
+
"heat_score": _safe_float(candidate.get("heat_score")) or 0.0,
|
|
1157
|
+
"aliases": aliases,
|
|
1158
|
+
"confidence": round(confidence, 4),
|
|
1159
|
+
"match_type": match_type,
|
|
1160
|
+
})
|
|
1161
|
+
|
|
1162
|
+
ranked.sort(
|
|
1163
|
+
key=lambda item: (
|
|
1164
|
+
_safe_float(item.get("confidence")) or 0.0,
|
|
1165
|
+
_safe_float(item.get("heat_score")) or 0.0,
|
|
1166
|
+
-(_safe_float(item.get("rank")) or 999999.0),
|
|
1167
|
+
item.get("topic", ""),
|
|
1168
|
+
),
|
|
1169
|
+
reverse=True,
|
|
1170
|
+
)
|
|
1171
|
+
top = ranked[0] if ranked else None
|
|
1172
|
+
confidence = _safe_float(top.get("confidence")) if top else 0.0
|
|
1173
|
+
canonical_topic = _safe_text(top.get("topic")) if top and confidence is not None and confidence >= 0.55 else ""
|
|
1174
|
+
aliases = _dedupe_texts([query, *(top.get("aliases", []) if top else [])])
|
|
1175
|
+
return HotspotTopicResolution(
|
|
1176
|
+
query=query,
|
|
1177
|
+
canonical_topic=canonical_topic,
|
|
1178
|
+
candidates=ranked[:5],
|
|
1179
|
+
aliases=aliases,
|
|
1180
|
+
confidence=round(confidence or 0.0, 4),
|
|
1181
|
+
unresolved=not bool(canonical_topic),
|
|
1182
|
+
)
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _topic_match_score(query: str, aliases: list[str]) -> tuple[float, str]:
|
|
1186
|
+
query_key = _normalize_topic_key(query)
|
|
1187
|
+
if not query_key:
|
|
1188
|
+
return 0.0, "empty"
|
|
1189
|
+
best = (0.0, "none")
|
|
1190
|
+
for alias in aliases:
|
|
1191
|
+
alias_key = _normalize_topic_key(alias)
|
|
1192
|
+
if not alias_key:
|
|
1193
|
+
continue
|
|
1194
|
+
if alias_key == query_key:
|
|
1195
|
+
return 1.0, "exact"
|
|
1196
|
+
if len(alias_key) >= 2 and alias_key in query_key:
|
|
1197
|
+
ratio = len(alias_key) / max(len(query_key), 1)
|
|
1198
|
+
best = max(best, (0.82 + min(ratio, 1.0) * 0.08, "alias_contains"), key=lambda item: item[0])
|
|
1199
|
+
continue
|
|
1200
|
+
if len(query_key) >= 2 and query_key in alias_key:
|
|
1201
|
+
ratio = len(query_key) / max(len(alias_key), 1)
|
|
1202
|
+
best = max(best, (0.78 + min(ratio, 1.0) * 0.1, "query_contains"), key=lambda item: item[0])
|
|
1203
|
+
continue
|
|
1204
|
+
query_chars = set(query_key)
|
|
1205
|
+
alias_chars = set(alias_key)
|
|
1206
|
+
overlap = len(query_chars & alias_chars) / max(len(query_chars | alias_chars), 1)
|
|
1207
|
+
if overlap >= 0.45:
|
|
1208
|
+
best = max(best, (0.42 + overlap * 0.28, "char_overlap"), key=lambda item: item[0])
|
|
1209
|
+
return best
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def _normalize_topic_key(value: object) -> str:
|
|
1213
|
+
text = _safe_text(value).lower()
|
|
1214
|
+
text = text.replace("人工智能", "ai")
|
|
1215
|
+
for token in ("概念", "板块", "行业", "产业", "主题", "指数"):
|
|
1216
|
+
text = text.replace(token, "")
|
|
1217
|
+
return "".join(char for char in text if char.isalnum() or "\u4e00" <= char <= "\u9fff")
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def _load_hotspot_cache_for_fallback(
|
|
1221
|
+
fallback_cache_path: str | Path | None,
|
|
1222
|
+
*,
|
|
1223
|
+
source_errors: list[str],
|
|
1224
|
+
) -> list[HotspotSummary]:
|
|
1225
|
+
if not fallback_cache_path:
|
|
1226
|
+
return []
|
|
1227
|
+
try:
|
|
1228
|
+
return load_hotspots_json(fallback_cache_path)
|
|
1229
|
+
except FileNotFoundError:
|
|
1230
|
+
return []
|
|
1231
|
+
except Exception as exc: # noqa: BLE001 - fallback cache must not wipe live detail data.
|
|
1232
|
+
source_errors.append(f"last_good_cache: {exc}")
|
|
1233
|
+
return []
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def _fallback_summary_for_resolution(
|
|
1237
|
+
topic: str,
|
|
1238
|
+
hotspots: list[HotspotSummary],
|
|
1239
|
+
resolution: HotspotTopicResolution,
|
|
1240
|
+
) -> HotspotSummary | None:
|
|
1241
|
+
topic_key = _normalize_topic_key(topic)
|
|
1242
|
+
canonical_key = _normalize_topic_key(resolution.canonical_topic)
|
|
1243
|
+
for hotspot in hotspots:
|
|
1244
|
+
keys = {
|
|
1245
|
+
_normalize_topic_key(hotspot.topic),
|
|
1246
|
+
_normalize_topic_key(hotspot.name),
|
|
1247
|
+
_normalize_topic_key(hotspot.canonical_topic),
|
|
1248
|
+
*(_normalize_topic_key(alias) for alias in hotspot.aliases),
|
|
1249
|
+
}
|
|
1250
|
+
if topic_key in keys or (canonical_key and canonical_key in keys):
|
|
1251
|
+
return hotspot
|
|
1252
|
+
return None
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
def _copy_hotspot_summary(summary: HotspotSummary) -> HotspotSummary:
|
|
1256
|
+
copied = _coerce_hotspot_summary(asdict(summary))
|
|
1257
|
+
return copied if copied is not None else summary
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
def _copy_hotspot_stock(stock: HotspotStock) -> HotspotStock:
|
|
1261
|
+
return _coerce_hotspot_stock(asdict(stock))
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
def _leader_fallback_stocks(
|
|
1265
|
+
summary: HotspotSummary | None,
|
|
1266
|
+
*,
|
|
1267
|
+
stale_age_hours: float | None,
|
|
1268
|
+
) -> list[HotspotStock]:
|
|
1269
|
+
if summary is None:
|
|
1270
|
+
return []
|
|
1271
|
+
stocks: list[HotspotStock] = []
|
|
1272
|
+
for stock in summary.leader_stocks:
|
|
1273
|
+
copied = _copy_hotspot_stock(stock)
|
|
1274
|
+
if not copied.code and not copied.name:
|
|
1275
|
+
continue
|
|
1276
|
+
copied.source = "last_good_cache.leader_stocks"
|
|
1277
|
+
copied.source_confidence = _stale_confidence(0.65, stale_age_hours)
|
|
1278
|
+
copied.fallback_used = True
|
|
1279
|
+
copied.role = copied.role or "核心龙头"
|
|
1280
|
+
stocks.append(copied)
|
|
1281
|
+
if stocks:
|
|
1282
|
+
return stocks
|
|
1283
|
+
|
|
1284
|
+
for idx, leader in enumerate(summary.leaders[:3]):
|
|
1285
|
+
text = _safe_text(leader)
|
|
1286
|
+
if not text:
|
|
1287
|
+
continue
|
|
1288
|
+
stocks.append(HotspotStock(
|
|
1289
|
+
code="",
|
|
1290
|
+
name=text,
|
|
1291
|
+
role="核心龙头" if idx == 0 else "助攻",
|
|
1292
|
+
hot_stock_score=0.0,
|
|
1293
|
+
source="last_good_cache.leaders",
|
|
1294
|
+
source_confidence=_stale_confidence(0.45, stale_age_hours),
|
|
1295
|
+
fallback_used=True,
|
|
1296
|
+
))
|
|
1297
|
+
return stocks
|
|
1298
|
+
|
|
1299
|
+
|
|
1300
|
+
def _set_summary_leaders(summary: HotspotSummary, stocks: list[HotspotStock]) -> None:
|
|
1301
|
+
selected = [stock for stock in stocks if stock.role == "核心龙头"][:3]
|
|
1302
|
+
if not selected:
|
|
1303
|
+
selected = stocks[:3]
|
|
1304
|
+
summary.leader_stocks = [_copy_hotspot_stock(stock) for stock in selected]
|
|
1305
|
+
summary.leaders = [
|
|
1306
|
+
stock.name or stock.code
|
|
1307
|
+
for stock in summary.leader_stocks
|
|
1308
|
+
if stock.name or stock.code
|
|
1309
|
+
]
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
def _add_missing_fields(summary: HotspotSummary, fields: list[str]) -> None:
|
|
1313
|
+
summary.missing_fields = _dedupe_texts([*summary.missing_fields, *fields])
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def _finalize_summary_quality(summary: HotspotSummary, *, stock_count: int | None = None) -> None:
|
|
1317
|
+
if not summary.canonical_topic:
|
|
1318
|
+
_add_missing_fields(summary, ["canonical_topic"])
|
|
1319
|
+
if not summary.source:
|
|
1320
|
+
_add_missing_fields(summary, ["source"])
|
|
1321
|
+
count = summary.sample_stock_count if stock_count is None else stock_count
|
|
1322
|
+
if count <= 0 and not summary.leader_stocks:
|
|
1323
|
+
_add_missing_fields(summary, ["stocks"])
|
|
1324
|
+
summary.missing_fields = _dedupe_texts(summary.missing_fields)
|
|
1325
|
+
if summary.stale:
|
|
1326
|
+
summary.quality_status = "stale"
|
|
1327
|
+
elif "canonical_topic" in summary.missing_fields and not summary.resolver_candidates:
|
|
1328
|
+
summary.quality_status = "failed"
|
|
1329
|
+
elif summary.missing_fields:
|
|
1330
|
+
summary.quality_status = "partial"
|
|
1331
|
+
else:
|
|
1332
|
+
summary.quality_status = "available"
|
|
1333
|
+
|
|
1334
|
+
|
|
1335
|
+
def _quality_counts(hotspots: list[HotspotSummary]) -> dict[str, int]:
|
|
1336
|
+
counts: dict[str, int] = {}
|
|
1337
|
+
for hotspot in hotspots:
|
|
1338
|
+
status = _safe_text(getattr(hotspot, "quality_status", "")) or "partial"
|
|
1339
|
+
counts[status] = counts.get(status, 0) + 1
|
|
1340
|
+
return counts
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def _stale_confidence(base: float, stale_age_hours: float | None) -> float:
|
|
1344
|
+
if stale_age_hours is None:
|
|
1345
|
+
return round(base, 4)
|
|
1346
|
+
if stale_age_hours <= 24:
|
|
1347
|
+
return round(base, 4)
|
|
1348
|
+
return round(max(base * 0.5, base - min(stale_age_hours / 240.0, 0.25)), 4)
|
|
1349
|
+
|
|
1350
|
+
|
|
1351
|
+
def _dedupe_timeline(events: list[TimelineEvent]) -> list[TimelineEvent]:
|
|
1352
|
+
deduped: dict[tuple[str, str, str], TimelineEvent] = {}
|
|
1353
|
+
for event in events:
|
|
1354
|
+
deduped[(event.date, event.source, event.title)] = event
|
|
1355
|
+
return sorted(deduped.values(), key=lambda item: (item.date, item.source, item.title))
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
def _build_route_from_timeline(
|
|
1359
|
+
events: list[TimelineEvent],
|
|
1360
|
+
*,
|
|
1361
|
+
max_items: int,
|
|
1362
|
+
max_description_chars: int,
|
|
1363
|
+
) -> list[HotspotRouteItem]:
|
|
1364
|
+
grouped: dict[str, list[TimelineEvent]] = {}
|
|
1365
|
+
for event in events:
|
|
1366
|
+
date = _event_day(event.date or event.published_at)
|
|
1367
|
+
grouped.setdefault(date, []).append(event)
|
|
1368
|
+
|
|
1369
|
+
route: list[HotspotRouteItem] = []
|
|
1370
|
+
for date in sorted(grouped.keys(), reverse=True)[:max(int(max_items), 1)]:
|
|
1371
|
+
day_events = sorted(
|
|
1372
|
+
grouped[date],
|
|
1373
|
+
key=lambda item: (item.impact_score, item.published_at, item.source, item.title),
|
|
1374
|
+
reverse=True,
|
|
1375
|
+
)
|
|
1376
|
+
lead = day_events[0]
|
|
1377
|
+
texts = []
|
|
1378
|
+
for event in day_events[:3]:
|
|
1379
|
+
text = _safe_text(event.description) or _safe_text(event.title)
|
|
1380
|
+
if text:
|
|
1381
|
+
texts.append(text)
|
|
1382
|
+
description = _compact_text(" ".join(_dedupe_texts(texts)), max_description_chars)
|
|
1383
|
+
route.append(HotspotRouteItem(
|
|
1384
|
+
date=date,
|
|
1385
|
+
title=_route_title(lead),
|
|
1386
|
+
description=description,
|
|
1387
|
+
source=lead.source,
|
|
1388
|
+
event_type=lead.event_type,
|
|
1389
|
+
impact_score=round(max(event.impact_score for event in day_events), 4),
|
|
1390
|
+
related_codes=_dedupe_texts([
|
|
1391
|
+
code
|
|
1392
|
+
for event in day_events
|
|
1393
|
+
for code in event.related_codes
|
|
1394
|
+
]),
|
|
1395
|
+
url=lead.url,
|
|
1396
|
+
published_at=lead.published_at,
|
|
1397
|
+
))
|
|
1398
|
+
return route
|
|
1399
|
+
|
|
1400
|
+
|
|
1401
|
+
def _build_summary_route_item(
|
|
1402
|
+
summary: HotspotSummary,
|
|
1403
|
+
stocks: list[HotspotStock],
|
|
1404
|
+
*,
|
|
1405
|
+
max_description_chars: int,
|
|
1406
|
+
) -> HotspotRouteItem:
|
|
1407
|
+
leaders = summary.leaders or [stock.name for stock in stocks[:3] if stock.name]
|
|
1408
|
+
parts = [
|
|
1409
|
+
f"{summary.topic or summary.name} heat {summary.heat_score:.1f}",
|
|
1410
|
+
f"stage {summary.stage}" if summary.stage else "",
|
|
1411
|
+
"leaders " + ", ".join(leaders[:3]) if leaders else "",
|
|
1412
|
+
]
|
|
1413
|
+
source = summary.provider_used or summary.source or "alphasift_hotspot"
|
|
1414
|
+
return HotspotRouteItem(
|
|
1415
|
+
date=_event_day(datetime.now(timezone.utc).isoformat()),
|
|
1416
|
+
title="Current fermentation",
|
|
1417
|
+
description=_compact_text("; ".join(_dedupe_texts(parts)), max_description_chars),
|
|
1418
|
+
source=source,
|
|
1419
|
+
event_type="summary",
|
|
1420
|
+
impact_score=round(_safe_float(summary.heat_score) or 0.0, 4),
|
|
1421
|
+
related_codes=[stock.code for stock in stocks[:3] if stock.code],
|
|
1422
|
+
)
|
|
1423
|
+
|
|
1424
|
+
|
|
1425
|
+
def _route_title(event: TimelineEvent) -> str:
|
|
1426
|
+
event_type = _safe_text(event.event_type).lower()
|
|
1427
|
+
if event_type in {"announcement", "notice", "order", "policy", "fund_flow"}:
|
|
1428
|
+
return event.title[:60]
|
|
1429
|
+
return "News catalyst"
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
def _event_day(value: str) -> str:
|
|
1433
|
+
text = _safe_text(value)
|
|
1434
|
+
if len(text) >= 10:
|
|
1435
|
+
return text[:10]
|
|
1436
|
+
return text
|
|
1437
|
+
|
|
1438
|
+
|
|
1439
|
+
def _compact_text(value: str, max_chars: int) -> str:
|
|
1440
|
+
text = " ".join(_safe_text(value).split())
|
|
1441
|
+
limit = max(int(max_chars), 20)
|
|
1442
|
+
if len(text) <= limit:
|
|
1443
|
+
return text
|
|
1444
|
+
return text[: max(limit - 3, 0)].rstrip() + "..."
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
def _dedupe_texts(values: list[object]) -> list[str]:
|
|
1448
|
+
items: list[str] = []
|
|
1449
|
+
seen: set[str] = set()
|
|
1450
|
+
for value in values:
|
|
1451
|
+
text = _safe_text(value)
|
|
1452
|
+
if text and text not in seen:
|
|
1453
|
+
seen.add(text)
|
|
1454
|
+
items.append(text)
|
|
1455
|
+
return items
|
|
1456
|
+
|
|
1457
|
+
|
|
1458
|
+
def _load_fallback_hotspots(
|
|
1459
|
+
fallback_cache_path: str | Path | None,
|
|
1460
|
+
*,
|
|
1461
|
+
source_errors: list[str],
|
|
1462
|
+
top: int,
|
|
1463
|
+
) -> HotspotResults | None:
|
|
1464
|
+
if not fallback_cache_path:
|
|
1465
|
+
return None
|
|
1466
|
+
try:
|
|
1467
|
+
hotspots = load_hotspots_json(fallback_cache_path)
|
|
1468
|
+
except FileNotFoundError:
|
|
1469
|
+
return None
|
|
1470
|
+
except Exception as exc: # noqa: BLE001 - malformed fallback cache should not crash live flow.
|
|
1471
|
+
source_errors.append(f"last_good_cache: {exc}")
|
|
1472
|
+
return None
|
|
1473
|
+
if not hotspots:
|
|
1474
|
+
return None
|
|
1475
|
+
stale_age = _cache_stale_age_hours(fallback_cache_path)
|
|
1476
|
+
return _with_result_metadata(
|
|
1477
|
+
hotspots[:max(int(top), 0)],
|
|
1478
|
+
provider_used="last_good_cache",
|
|
1479
|
+
fallback_used=True,
|
|
1480
|
+
source_errors=source_errors or ["none: no live hotspot rows"],
|
|
1481
|
+
stale=True,
|
|
1482
|
+
stale_age_hours=stale_age,
|
|
1483
|
+
)
|
|
1484
|
+
|
|
1485
|
+
|
|
1486
|
+
def _find_fallback_hotspot(
|
|
1487
|
+
topic: str,
|
|
1488
|
+
fallback_cache_path: str | Path | None,
|
|
1489
|
+
*,
|
|
1490
|
+
source_errors: list[str],
|
|
1491
|
+
) -> HotspotSummary | None:
|
|
1492
|
+
if not fallback_cache_path or not topic:
|
|
1493
|
+
return None
|
|
1494
|
+
hotspots = _load_hotspot_cache_for_fallback(fallback_cache_path, source_errors=source_errors)
|
|
1495
|
+
resolution = _resolve_topic_from_candidates(
|
|
1496
|
+
topic,
|
|
1497
|
+
_topic_candidates_from_hotspots(hotspots, source="cache"),
|
|
1498
|
+
)
|
|
1499
|
+
return _fallback_summary_for_resolution(topic, hotspots, resolution)
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
def _with_result_metadata(
|
|
1503
|
+
hotspots: list[HotspotSummary],
|
|
1504
|
+
*,
|
|
1505
|
+
provider_used: str,
|
|
1506
|
+
fallback_used: bool,
|
|
1507
|
+
source_errors: list[str],
|
|
1508
|
+
stale: bool,
|
|
1509
|
+
stale_age_hours: float | None,
|
|
1510
|
+
) -> HotspotResults:
|
|
1511
|
+
errors = _dedupe_errors(source_errors)
|
|
1512
|
+
for hotspot in hotspots:
|
|
1513
|
+
_apply_summary_metadata(
|
|
1514
|
+
hotspot,
|
|
1515
|
+
provider_used=provider_used,
|
|
1516
|
+
fallback_used=fallback_used,
|
|
1517
|
+
source_errors=errors,
|
|
1518
|
+
stale=stale,
|
|
1519
|
+
stale_age_hours=stale_age_hours,
|
|
1520
|
+
)
|
|
1521
|
+
_finalize_summary_quality(hotspot, stock_count=hotspot.sample_stock_count)
|
|
1522
|
+
return HotspotResults(
|
|
1523
|
+
hotspots,
|
|
1524
|
+
provider_used=provider_used,
|
|
1525
|
+
fallback_used=fallback_used,
|
|
1526
|
+
source_errors=errors,
|
|
1527
|
+
stale=stale,
|
|
1528
|
+
stale_age_hours=stale_age_hours,
|
|
1529
|
+
)
|
|
1530
|
+
|
|
1531
|
+
|
|
1532
|
+
def _apply_summary_metadata(
|
|
1533
|
+
summary: HotspotSummary,
|
|
1534
|
+
*,
|
|
1535
|
+
provider_used: str,
|
|
1536
|
+
fallback_used: bool,
|
|
1537
|
+
source_errors: list[str],
|
|
1538
|
+
stale: bool,
|
|
1539
|
+
stale_age_hours: float | None,
|
|
1540
|
+
) -> None:
|
|
1541
|
+
summary.provider_used = provider_used
|
|
1542
|
+
summary.fallback_used = bool(summary.fallback_used or fallback_used)
|
|
1543
|
+
summary.source_errors = _dedupe_errors(source_errors)
|
|
1544
|
+
summary.stale = bool(summary.stale or stale)
|
|
1545
|
+
summary.stale_age_hours = summary.stale_age_hours if summary.stale_age_hours is not None else stale_age_hours
|
|
1546
|
+
|
|
1547
|
+
|
|
1548
|
+
def _cache_stale_age_hours(path_like: str | Path | None) -> float | None:
|
|
1549
|
+
if not path_like:
|
|
1550
|
+
return None
|
|
1551
|
+
path = Path(path_like)
|
|
1552
|
+
if not path.exists():
|
|
1553
|
+
return None
|
|
1554
|
+
modified = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
|
|
1555
|
+
age_hours = (datetime.now(timezone.utc) - modified).total_seconds() / 3600.0
|
|
1556
|
+
return round(max(age_hours, 0.0), 4)
|
|
1557
|
+
|
|
1558
|
+
|
|
1559
|
+
def _record_provider_error(
|
|
1560
|
+
source_errors: list[str] | None,
|
|
1561
|
+
provider_label: str,
|
|
1562
|
+
method_name: str,
|
|
1563
|
+
exc: Exception,
|
|
1564
|
+
) -> None:
|
|
1565
|
+
if source_errors is None:
|
|
1566
|
+
return
|
|
1567
|
+
label = provider_label or "provider"
|
|
1568
|
+
source_errors.append(f"{label}.{method_name}: {exc}")
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
def _provider_label(provider: object) -> str:
|
|
1572
|
+
if isinstance(provider, dict):
|
|
1573
|
+
return "mapping"
|
|
1574
|
+
return provider.__class__.__name__
|
|
1575
|
+
|
|
1576
|
+
|
|
1577
|
+
def _dedupe_errors(source_errors: list[str]) -> list[str]:
|
|
1578
|
+
errors: list[str] = []
|
|
1579
|
+
seen: set[str] = set()
|
|
1580
|
+
for value in source_errors:
|
|
1581
|
+
text = _safe_text(value)
|
|
1582
|
+
if text and text not in seen:
|
|
1583
|
+
seen.add(text)
|
|
1584
|
+
errors.append(text)
|
|
1585
|
+
return errors
|
|
1586
|
+
|
|
1587
|
+
|
|
1588
|
+
def _load_history_trends(history_path: str | Path | None) -> dict[str, dict[str, Any]]:
|
|
1589
|
+
if not history_path:
|
|
1590
|
+
return {}
|
|
1591
|
+
path = Path(history_path)
|
|
1592
|
+
if not path.is_file():
|
|
1593
|
+
return {}
|
|
1594
|
+
return load_board_heat_trends(path)
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
def _hotspot_sort_key(item: HotspotSummary) -> tuple[float, float, float, float, float]:
|
|
1598
|
+
trend = item.trend_score or 0.0
|
|
1599
|
+
persistence = item.persistence_score or 0.0
|
|
1600
|
+
cooling = item.cooling_score or 0.0
|
|
1601
|
+
score = item.heat_score + max(trend, 0.0) * 0.35 + persistence * 0.05 - cooling * 0.6
|
|
1602
|
+
change = item.change_pct if item.change_pct is not None else -999.0
|
|
1603
|
+
rank_bonus = -float(item.rank or 999999)
|
|
1604
|
+
return (score, item.heat_score, change, trend, rank_bonus)
|
|
1605
|
+
|
|
1606
|
+
|
|
1607
|
+
def _board_row_rank_key(item: dict[str, Any]) -> tuple[float, float, float]:
|
|
1608
|
+
heat = _safe_float(item.get("heat_score"))
|
|
1609
|
+
change = _safe_float(item.get("change_pct"))
|
|
1610
|
+
rank = _safe_float(item.get("rank"))
|
|
1611
|
+
rank_bonus = -float(rank if rank is not None else 999999.0)
|
|
1612
|
+
heat_value = heat if heat is not None else 0.0
|
|
1613
|
+
change_value = change if change is not None else -999.0
|
|
1614
|
+
return (heat_value, change_value, rank_bonus)
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def _call_provider_frame(
|
|
1618
|
+
provider: object,
|
|
1619
|
+
method_name: str,
|
|
1620
|
+
*,
|
|
1621
|
+
source_errors: list[str] | None = None,
|
|
1622
|
+
provider_label: str = "",
|
|
1623
|
+
**kwargs: Any,
|
|
1624
|
+
) -> pd.DataFrame | None:
|
|
1625
|
+
method = getattr(provider, method_name, None)
|
|
1626
|
+
if method is None:
|
|
1627
|
+
return None
|
|
1628
|
+
try:
|
|
1629
|
+
frame = method(**kwargs) if kwargs else method()
|
|
1630
|
+
except TypeError:
|
|
1631
|
+
try:
|
|
1632
|
+
frame = method(kwargs.get("symbol")) if kwargs else method()
|
|
1633
|
+
except Exception as exc: # noqa: BLE001 - provider runtime instability is degraded.
|
|
1634
|
+
_record_provider_error(source_errors, provider_label, method_name, exc)
|
|
1635
|
+
return None
|
|
1636
|
+
except Exception as exc: # noqa: BLE001 - provider runtime instability is degraded.
|
|
1637
|
+
_record_provider_error(source_errors, provider_label, method_name, exc)
|
|
1638
|
+
return None
|
|
1639
|
+
return frame if isinstance(frame, pd.DataFrame) else None
|
|
1640
|
+
|
|
1641
|
+
|
|
1642
|
+
def _mapping_provider_frame(provider: object, key: str) -> pd.DataFrame | None:
|
|
1643
|
+
if not isinstance(provider, dict):
|
|
1644
|
+
return None
|
|
1645
|
+
frame = provider.get(key)
|
|
1646
|
+
if isinstance(frame, pd.DataFrame):
|
|
1647
|
+
return frame
|
|
1648
|
+
if isinstance(frame, list):
|
|
1649
|
+
return pd.DataFrame(frame)
|
|
1650
|
+
return None
|
|
1651
|
+
|
|
1652
|
+
|
|
1653
|
+
def _mapping_constituents_frame(provider: object, topic: str, *, source: str) -> pd.DataFrame | None:
|
|
1654
|
+
if not isinstance(provider, dict):
|
|
1655
|
+
return None
|
|
1656
|
+
for key in (f"{source}_constituents", "constituents"):
|
|
1657
|
+
value = provider.get(key)
|
|
1658
|
+
if isinstance(value, dict):
|
|
1659
|
+
frame = value.get(topic)
|
|
1660
|
+
if isinstance(frame, pd.DataFrame):
|
|
1661
|
+
return frame
|
|
1662
|
+
if isinstance(frame, list):
|
|
1663
|
+
return pd.DataFrame(frame)
|
|
1664
|
+
return None
|
|
1665
|
+
|
|
1666
|
+
|
|
1667
|
+
def _timeline_matches_topic(item: dict[str, Any], topic: str) -> bool:
|
|
1668
|
+
values: list[str] = []
|
|
1669
|
+
for key in ("topic", "hotspot", "board"):
|
|
1670
|
+
text = _safe_text(item.get(key))
|
|
1671
|
+
if text:
|
|
1672
|
+
values.append(text)
|
|
1673
|
+
raw_topics = item.get("topics")
|
|
1674
|
+
if isinstance(raw_topics, list):
|
|
1675
|
+
values.extend(_safe_text(value) for value in raw_topics if _safe_text(value))
|
|
1676
|
+
elif _safe_text(raw_topics):
|
|
1677
|
+
values.extend(part.strip() for part in _safe_text(raw_topics).replace(",", ",").split(",") if part.strip())
|
|
1678
|
+
if values:
|
|
1679
|
+
return topic in values
|
|
1680
|
+
return topic in _safe_text(item.get("title"))
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
def _normalize_related_codes(value: object) -> list[str]:
|
|
1684
|
+
if isinstance(value, list):
|
|
1685
|
+
raw_items = value
|
|
1686
|
+
else:
|
|
1687
|
+
raw_items = _safe_text(value).replace(",", ",").replace("、", ",").split(",")
|
|
1688
|
+
codes: list[str] = []
|
|
1689
|
+
seen: set[str] = set()
|
|
1690
|
+
for raw in raw_items:
|
|
1691
|
+
code = _normalize_code(raw)
|
|
1692
|
+
if code and code not in seen:
|
|
1693
|
+
seen.add(code)
|
|
1694
|
+
codes.append(code)
|
|
1695
|
+
return codes
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
def _row_value(row: dict[str, Any] | pd.Series, columns: list[str]) -> Any:
|
|
1699
|
+
for column in columns:
|
|
1700
|
+
if column in row:
|
|
1701
|
+
return row.get(column)
|
|
1702
|
+
return None
|
|
1703
|
+
|
|
1704
|
+
|
|
1705
|
+
def _safe_bool(value: object) -> bool:
|
|
1706
|
+
if isinstance(value, bool):
|
|
1707
|
+
return value
|
|
1708
|
+
text = _safe_text(value).lower()
|
|
1709
|
+
return text in {"1", "true", "yes", "y", "是", "涨停", "limit_up"}
|
|
1710
|
+
|
|
1711
|
+
|
|
1712
|
+
def _clamp(value: float, lower: float, upper: float) -> float:
|
|
1713
|
+
return max(lower, min(upper, value))
|