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/snapshot.py
ADDED
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Market snapshot fetcher.
|
|
3
|
+
|
|
4
|
+
Fetches full-market real-time snapshots for screening.
|
|
5
|
+
This is separate from single-stock realtime quotes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import random
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from datetime import date, datetime, timezone, timedelta
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import pandas as pd
|
|
18
|
+
import requests
|
|
19
|
+
from requests.adapters import HTTPAdapter
|
|
20
|
+
from urllib3.util.retry import Retry
|
|
21
|
+
|
|
22
|
+
from alphasift.markets import MarketSpec, get_market
|
|
23
|
+
from alphasift.snapshot_yahoo import fetch_yahoo_snapshot
|
|
24
|
+
from alphasift.source_guard import call_with_timeout, parse_source_timeout_seconds
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
_SNAPSHOT_CACHE_VERSION = 1
|
|
29
|
+
_DEFAULT_TUSHARE_HTTP_URL = "http://api.waditu.com"
|
|
30
|
+
_EM_REQUEST_MIN_INTERVAL_SECONDS = 1.0
|
|
31
|
+
_EM_REQUEST_JITTER_SECONDS = 0.3
|
|
32
|
+
_SOURCE_HEALTH_FAILURE_THRESHOLD = 3
|
|
33
|
+
_SOURCE_HEALTH_COOLDOWN_SECONDS = 5 * 60
|
|
34
|
+
_SNAPSHOT_CALL_TIMEOUT_SECONDS = 60.0
|
|
35
|
+
_DIRECT_CONNECT_TIMEOUT_SECONDS = 5.0
|
|
36
|
+
_EM_SESSION: requests.Session | None = None
|
|
37
|
+
_EM_LAST_REQUEST_AT = 0.0
|
|
38
|
+
_EM_LOCK = threading.Lock()
|
|
39
|
+
_SOURCE_HEALTH: dict[str, dict[str, object]] = {}
|
|
40
|
+
_SOURCE_HEALTH_LOCK = threading.Lock()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def fetch_cn_snapshot(source: str = "efinance") -> pd.DataFrame:
|
|
44
|
+
"""Fetch A-share full-market snapshot.
|
|
45
|
+
|
|
46
|
+
Returns a DataFrame with columns:
|
|
47
|
+
code, name, price, change_pct, amount, total_mv, circ_mv,
|
|
48
|
+
pe_ratio, pb_ratio, volume_ratio, turnover_rate
|
|
49
|
+
|
|
50
|
+
Raises RuntimeError if the source is unavailable.
|
|
51
|
+
"""
|
|
52
|
+
if source == "sina":
|
|
53
|
+
return _fetch_sina()
|
|
54
|
+
elif source == "efinance":
|
|
55
|
+
return _call_snapshot_wrapper(_fetch_efinance, source=source)
|
|
56
|
+
elif source == "akshare_em":
|
|
57
|
+
return _call_snapshot_wrapper(_fetch_akshare_em, source=source)
|
|
58
|
+
elif source == "em_datacenter":
|
|
59
|
+
return _fetch_em_datacenter()
|
|
60
|
+
elif source == "tushare":
|
|
61
|
+
return _call_snapshot_wrapper(_fetch_tushare, source=source)
|
|
62
|
+
else:
|
|
63
|
+
raise ValueError(f"Unknown snapshot source: {source}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def fetch_snapshot_with_fallback(
|
|
67
|
+
sources: list[str],
|
|
68
|
+
*,
|
|
69
|
+
required_columns: list[str] | None = None,
|
|
70
|
+
fallback_snapshot_path: str | Path | None = None,
|
|
71
|
+
fallback_max_age_hours: float | None = None,
|
|
72
|
+
market: str = "cn",
|
|
73
|
+
source_health_path: str | Path | None = None,
|
|
74
|
+
) -> pd.DataFrame:
|
|
75
|
+
"""Try live sources, optionally falling back to the last-good snapshot.
|
|
76
|
+
|
|
77
|
+
When ``source_health_path`` is set, per-source outcomes are persisted there
|
|
78
|
+
so the next process tries recently healthy sources first. CLI runs are one
|
|
79
|
+
process each, so in-memory health alone never helps them.
|
|
80
|
+
"""
|
|
81
|
+
spec = get_market(market)
|
|
82
|
+
if not spec.cn_rules:
|
|
83
|
+
return _fetch_yahoo_market_snapshot(
|
|
84
|
+
spec,
|
|
85
|
+
required_columns=required_columns or [],
|
|
86
|
+
fallback_snapshot_path=market_snapshot_cache_path(fallback_snapshot_path, spec.id),
|
|
87
|
+
fallback_max_age_hours=fallback_max_age_hours,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
errors = []
|
|
91
|
+
required = required_columns or []
|
|
92
|
+
persisted_health = _load_persisted_source_health(source_health_path)
|
|
93
|
+
touched: set[str] = set()
|
|
94
|
+
sources, order_notes = _order_sources_by_persisted_health(sources, persisted_health)
|
|
95
|
+
for source in sources:
|
|
96
|
+
disabled_reason = _source_disabled_reason(source)
|
|
97
|
+
if disabled_reason:
|
|
98
|
+
errors.append(f"{source}: {disabled_reason}")
|
|
99
|
+
continue
|
|
100
|
+
started = time.monotonic()
|
|
101
|
+
try:
|
|
102
|
+
df = fetch_cn_snapshot(source)
|
|
103
|
+
if not df.empty:
|
|
104
|
+
missing = _missing_required_columns(df, required)
|
|
105
|
+
if missing:
|
|
106
|
+
# A strategy-specific capability gap, not an outage: do not
|
|
107
|
+
# demote the source for strategies that don't need the column.
|
|
108
|
+
errors.append(
|
|
109
|
+
f"{source}: missing required columns {','.join(missing)}"
|
|
110
|
+
)
|
|
111
|
+
continue
|
|
112
|
+
df.attrs.setdefault("snapshot_source", source)
|
|
113
|
+
df.attrs["market"] = spec.id
|
|
114
|
+
df.attrs["source_errors"] = list(errors)
|
|
115
|
+
df.attrs["source_order_notes"] = list(order_notes)
|
|
116
|
+
df.attrs["fallback_used"] = False
|
|
117
|
+
df.attrs["stale"] = False
|
|
118
|
+
df.attrs["stale_age_hours"] = None
|
|
119
|
+
_write_last_good_snapshot(fallback_snapshot_path, df)
|
|
120
|
+
_record_source_success(source, rows=len(df))
|
|
121
|
+
_record_persisted_outcome(persisted_health, source, ok=True, started=started)
|
|
122
|
+
touched.add(source)
|
|
123
|
+
_save_persisted_source_health(source_health_path, persisted_health, touched)
|
|
124
|
+
logger.info("Snapshot fetched from %s: %d rows", source, len(df))
|
|
125
|
+
return df
|
|
126
|
+
errors.append(f"{source}: returned empty data")
|
|
127
|
+
_record_source_failure(source, "returned empty data")
|
|
128
|
+
_record_persisted_outcome(
|
|
129
|
+
persisted_health, source, ok=False, started=started, error="returned empty data",
|
|
130
|
+
)
|
|
131
|
+
touched.add(source)
|
|
132
|
+
except Exception as e:
|
|
133
|
+
errors.append(f"{source}: {e}")
|
|
134
|
+
_record_source_failure(source, e)
|
|
135
|
+
_record_persisted_outcome(persisted_health, source, ok=False, started=started, error=e)
|
|
136
|
+
touched.add(source)
|
|
137
|
+
logger.warning("Snapshot source %s failed: %s", source, e)
|
|
138
|
+
|
|
139
|
+
_save_persisted_source_health(source_health_path, persisted_health, touched)
|
|
140
|
+
|
|
141
|
+
cached = _read_last_good_snapshot(
|
|
142
|
+
fallback_snapshot_path,
|
|
143
|
+
required_columns=required,
|
|
144
|
+
source_errors=errors,
|
|
145
|
+
max_age_hours=fallback_max_age_hours,
|
|
146
|
+
)
|
|
147
|
+
if cached is not None:
|
|
148
|
+
cached.attrs["market"] = spec.id
|
|
149
|
+
return cached
|
|
150
|
+
|
|
151
|
+
raise RuntimeError(f"All snapshot sources failed: {'; '.join(errors)}")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def market_snapshot_cache_path(
|
|
155
|
+
fallback_snapshot_path: str | Path | None,
|
|
156
|
+
market: str,
|
|
157
|
+
) -> Path | None:
|
|
158
|
+
"""Per-market last-good cache; CN keeps the original file name."""
|
|
159
|
+
if fallback_snapshot_path is None:
|
|
160
|
+
return None
|
|
161
|
+
path = Path(fallback_snapshot_path)
|
|
162
|
+
if market == "cn":
|
|
163
|
+
return path
|
|
164
|
+
return path.with_name(f"snapshot.{market}.last_good.json")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _fetch_yahoo_market_snapshot(
|
|
168
|
+
spec: MarketSpec,
|
|
169
|
+
*,
|
|
170
|
+
required_columns: list[str],
|
|
171
|
+
fallback_snapshot_path: Path | None,
|
|
172
|
+
fallback_max_age_hours: float | None,
|
|
173
|
+
) -> pd.DataFrame:
|
|
174
|
+
"""Yahoo screener first; for US also the legacy per-ticker path.
|
|
175
|
+
|
|
176
|
+
``ALPHASIFT_US_TICKERS`` keeps its meaning: an explicit US ticker list
|
|
177
|
+
goes straight to the legacy yfinance adapter.
|
|
178
|
+
"""
|
|
179
|
+
attempts: list[tuple[str, object]] = []
|
|
180
|
+
if spec.id == "us" and os.getenv("ALPHASIFT_US_TICKERS", "").strip():
|
|
181
|
+
attempts.append(("yfinance_tickers", _fetch_us_legacy_snapshot))
|
|
182
|
+
else:
|
|
183
|
+
attempts.append(("yahoo_screener", lambda: fetch_yahoo_snapshot(spec.id)))
|
|
184
|
+
if spec.id == "us":
|
|
185
|
+
attempts.append(("yfinance_tickers", _fetch_us_legacy_snapshot))
|
|
186
|
+
|
|
187
|
+
errors: list[str] = []
|
|
188
|
+
for name, fetch in attempts:
|
|
189
|
+
try:
|
|
190
|
+
df = fetch()
|
|
191
|
+
except Exception as exc: # noqa: BLE001 - fall through to next source / cache
|
|
192
|
+
errors.append(f"{name}: {exc}")
|
|
193
|
+
logger.warning("Snapshot source %s failed for market %s: %s", name, spec.id, exc)
|
|
194
|
+
continue
|
|
195
|
+
if df.empty:
|
|
196
|
+
errors.append(f"{name}: returned empty data")
|
|
197
|
+
continue
|
|
198
|
+
missing = _missing_required_columns(df, required_columns)
|
|
199
|
+
if missing:
|
|
200
|
+
errors.append(f"{name}: missing required columns {','.join(missing)}")
|
|
201
|
+
continue
|
|
202
|
+
df.attrs.setdefault("snapshot_source", name)
|
|
203
|
+
df.attrs["market"] = spec.id
|
|
204
|
+
df.attrs["currency"] = spec.currency
|
|
205
|
+
df.attrs["source_errors"] = [*errors, *df.attrs.get("source_errors", [])]
|
|
206
|
+
df.attrs["fallback_used"] = False
|
|
207
|
+
df.attrs["stale"] = False
|
|
208
|
+
df.attrs["stale_age_hours"] = None
|
|
209
|
+
if df.attrs.get("partial"):
|
|
210
|
+
# Some sectors failed: use the live rows, but keep the complete
|
|
211
|
+
# last-good cache instead of replacing it with a partial universe.
|
|
212
|
+
logger.warning("Snapshot for market %s is partial; last-good cache kept", spec.id)
|
|
213
|
+
else:
|
|
214
|
+
_write_last_good_snapshot(fallback_snapshot_path, df)
|
|
215
|
+
return df
|
|
216
|
+
|
|
217
|
+
cached = _read_last_good_snapshot(
|
|
218
|
+
fallback_snapshot_path,
|
|
219
|
+
required_columns=required_columns,
|
|
220
|
+
source_errors=errors,
|
|
221
|
+
max_age_hours=fallback_max_age_hours,
|
|
222
|
+
)
|
|
223
|
+
if cached is not None:
|
|
224
|
+
cached.attrs["market"] = spec.id
|
|
225
|
+
cached.attrs["currency"] = spec.currency
|
|
226
|
+
return cached
|
|
227
|
+
raise RuntimeError(f"All snapshot sources failed for market {spec.id}: {'; '.join(errors)}")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _fetch_us_legacy_snapshot() -> pd.DataFrame:
|
|
231
|
+
from alphasift.snapshot_us import fetch_us_snapshot
|
|
232
|
+
|
|
233
|
+
# An explicit ALPHASIFT_US_TICKERS list wins; "auto" would try the S&P 500
|
|
234
|
+
# scrape first and ignore it whenever Wikipedia is reachable.
|
|
235
|
+
universe = "env" if os.getenv("ALPHASIFT_US_TICKERS", "").strip() else "auto"
|
|
236
|
+
df = fetch_us_snapshot(universe_source=universe)
|
|
237
|
+
df.attrs["snapshot_source"] = "yfinance_tickers"
|
|
238
|
+
return df
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _missing_required_columns(df: pd.DataFrame, required_columns: list[str]) -> list[str]:
|
|
242
|
+
missing: list[str] = []
|
|
243
|
+
for col in required_columns:
|
|
244
|
+
if col not in df.columns:
|
|
245
|
+
missing.append(col)
|
|
246
|
+
continue
|
|
247
|
+
if df[col].dropna().empty:
|
|
248
|
+
missing.append(col)
|
|
249
|
+
return missing
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _call_snapshot_wrapper(fetcher, *, source: str) -> pd.DataFrame:
|
|
253
|
+
return call_with_timeout(
|
|
254
|
+
fetcher,
|
|
255
|
+
timeout_sec=_snapshot_call_timeout_seconds(),
|
|
256
|
+
label=f"snapshot source {source}",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _snapshot_call_timeout_seconds() -> float | None:
|
|
261
|
+
return parse_source_timeout_seconds(
|
|
262
|
+
"ALPHASIFT_SNAPSHOT_CALL_TIMEOUT_SEC",
|
|
263
|
+
default=_SNAPSHOT_CALL_TIMEOUT_SECONDS,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class _PageBudget:
|
|
268
|
+
"""Cooperative wall-clock budget for paged direct-HTTP snapshot sources.
|
|
269
|
+
|
|
270
|
+
Wrapper sources run under ``call_with_timeout``; sina and em_datacenter
|
|
271
|
+
page through plain requests instead, so they check this before each page
|
|
272
|
+
and cap each request's read timeout by the remaining time.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
def __init__(self, source: str, *, per_request_timeout: float):
|
|
276
|
+
self.source = source
|
|
277
|
+
self.per_request_timeout = per_request_timeout
|
|
278
|
+
self.budget = _snapshot_call_timeout_seconds()
|
|
279
|
+
self.started = time.monotonic()
|
|
280
|
+
self.pages = 0
|
|
281
|
+
|
|
282
|
+
def request_timeout(self) -> tuple[float, float]:
|
|
283
|
+
if self.budget is None:
|
|
284
|
+
return (_DIRECT_CONNECT_TIMEOUT_SECONDS, self.per_request_timeout)
|
|
285
|
+
remaining = self.budget - (time.monotonic() - self.started)
|
|
286
|
+
if remaining <= 0:
|
|
287
|
+
raise TimeoutError(
|
|
288
|
+
f"{self.source} exceeded {self.budget:.0f}s snapshot budget after {self.pages} pages"
|
|
289
|
+
)
|
|
290
|
+
read = max(min(self.per_request_timeout, remaining), 1.0)
|
|
291
|
+
return (min(_DIRECT_CONNECT_TIMEOUT_SECONDS, read), read)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _source_disabled_reason(source: str) -> str | None:
|
|
295
|
+
now = time.monotonic()
|
|
296
|
+
with _SOURCE_HEALTH_LOCK:
|
|
297
|
+
state = _SOURCE_HEALTH.get(source)
|
|
298
|
+
if not state:
|
|
299
|
+
return None
|
|
300
|
+
disabled_until = float(state.get("disabled_until", 0.0))
|
|
301
|
+
if disabled_until <= now:
|
|
302
|
+
if disabled_until:
|
|
303
|
+
state["disabled_until"] = 0.0
|
|
304
|
+
return None
|
|
305
|
+
return f"temporarily disabled for {disabled_until - now:.1f}s after repeated failures"
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _record_source_success(source: str, *, rows: int | None = None) -> None:
|
|
309
|
+
with _SOURCE_HEALTH_LOCK:
|
|
310
|
+
state = _SOURCE_HEALTH.setdefault(source, {"failures": 0.0, "disabled_until": 0.0})
|
|
311
|
+
successes = float(state.get("successes", 0.0)) + 1.0
|
|
312
|
+
state["successes"] = successes
|
|
313
|
+
state["failures"] = 0.0
|
|
314
|
+
state["disabled_until"] = 0.0
|
|
315
|
+
state["last_success_at"] = time.time()
|
|
316
|
+
if rows is not None:
|
|
317
|
+
state["last_rows"] = float(rows)
|
|
318
|
+
previous_avg = float(state.get("avg_rows", rows))
|
|
319
|
+
state["avg_rows"] = previous_avg + (float(rows) - previous_avg) / successes
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _record_source_failure(source: str, error: object | None = None) -> None:
|
|
323
|
+
now = time.monotonic()
|
|
324
|
+
with _SOURCE_HEALTH_LOCK:
|
|
325
|
+
state = _SOURCE_HEALTH.setdefault(source, {"failures": 0.0, "disabled_until": 0.0})
|
|
326
|
+
failures = float(state.get("failures", 0.0)) + 1.0
|
|
327
|
+
state["failures"] = failures
|
|
328
|
+
state["total_failures"] = float(state.get("total_failures", 0.0)) + 1.0
|
|
329
|
+
state["last_failure_at"] = time.time()
|
|
330
|
+
if error is not None:
|
|
331
|
+
state["last_error"] = " ".join(str(error).split())
|
|
332
|
+
if failures >= _SOURCE_HEALTH_FAILURE_THRESHOLD:
|
|
333
|
+
state["disabled_until"] = now + _SOURCE_HEALTH_COOLDOWN_SECONDS
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
_PERSISTED_HEALTH_VERSION = 1
|
|
337
|
+
_PERSISTED_FAILURE_TTL_SECONDS = 36 * 60 * 60
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _load_persisted_source_health(path: str | Path | None) -> dict[str, dict[str, object]]:
|
|
341
|
+
"""Read persisted health, dropping malformed entries.
|
|
342
|
+
|
|
343
|
+
Health is advisory: a corrupt or hand-edited file must never block a run.
|
|
344
|
+
"""
|
|
345
|
+
if path is None:
|
|
346
|
+
return {}
|
|
347
|
+
try:
|
|
348
|
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
349
|
+
except (OSError, ValueError):
|
|
350
|
+
return {}
|
|
351
|
+
if not isinstance(payload, dict) or payload.get("version") != _PERSISTED_HEALTH_VERSION:
|
|
352
|
+
return {}
|
|
353
|
+
sources = payload.get("sources")
|
|
354
|
+
if not isinstance(sources, dict):
|
|
355
|
+
return {}
|
|
356
|
+
cleaned: dict[str, dict[str, object]] = {}
|
|
357
|
+
for name, raw in sources.items():
|
|
358
|
+
if not isinstance(raw, dict):
|
|
359
|
+
continue
|
|
360
|
+
try:
|
|
361
|
+
entry: dict[str, object] = {
|
|
362
|
+
"last_success_at": float(raw.get("last_success_at", 0) or 0),
|
|
363
|
+
"last_failure_at": float(raw.get("last_failure_at", 0) or 0),
|
|
364
|
+
"consecutive_failures": int(raw.get("consecutive_failures", 0) or 0),
|
|
365
|
+
}
|
|
366
|
+
if raw.get("last_duration_sec") is not None:
|
|
367
|
+
entry["last_duration_sec"] = float(raw["last_duration_sec"])
|
|
368
|
+
except (TypeError, ValueError):
|
|
369
|
+
continue
|
|
370
|
+
if raw.get("last_error"):
|
|
371
|
+
entry["last_error"] = str(raw["last_error"])[:300]
|
|
372
|
+
cleaned[str(name)] = entry
|
|
373
|
+
return cleaned
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _save_persisted_source_health(
|
|
377
|
+
path: str | Path | None,
|
|
378
|
+
health: dict[str, dict[str, object]],
|
|
379
|
+
touched: set[str] | None = None,
|
|
380
|
+
) -> None:
|
|
381
|
+
"""Write health atomically, keeping other runs' updates for untouched sources."""
|
|
382
|
+
if path is None:
|
|
383
|
+
return
|
|
384
|
+
target = Path(path)
|
|
385
|
+
merged = _load_persisted_source_health(target)
|
|
386
|
+
for name in (touched if touched is not None else health.keys()):
|
|
387
|
+
if name in health:
|
|
388
|
+
merged[name] = health[name]
|
|
389
|
+
try:
|
|
390
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
391
|
+
tmp = target.with_name(f".{target.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
392
|
+
tmp.write_text(
|
|
393
|
+
json.dumps({"version": _PERSISTED_HEALTH_VERSION, "sources": merged}, ensure_ascii=False, indent=2),
|
|
394
|
+
encoding="utf-8",
|
|
395
|
+
)
|
|
396
|
+
tmp.replace(target)
|
|
397
|
+
except OSError as exc:
|
|
398
|
+
logger.debug("Could not persist snapshot source health to %s: %s", target, exc)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _record_persisted_outcome(
|
|
402
|
+
health: dict[str, dict[str, object]],
|
|
403
|
+
source: str,
|
|
404
|
+
*,
|
|
405
|
+
ok: bool,
|
|
406
|
+
started: float,
|
|
407
|
+
error: object | None = None,
|
|
408
|
+
) -> None:
|
|
409
|
+
state = health.setdefault(source, {})
|
|
410
|
+
now = time.time()
|
|
411
|
+
state["last_duration_sec"] = round(time.monotonic() - started, 2)
|
|
412
|
+
if ok:
|
|
413
|
+
state["last_success_at"] = now
|
|
414
|
+
state["consecutive_failures"] = 0
|
|
415
|
+
state.pop("last_error", None)
|
|
416
|
+
else:
|
|
417
|
+
state["last_failure_at"] = now
|
|
418
|
+
state["consecutive_failures"] = int(state.get("consecutive_failures", 0) or 0) + 1
|
|
419
|
+
if error is not None:
|
|
420
|
+
state["last_error"] = " ".join(str(error).split())[:300]
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _order_sources_by_persisted_health(
|
|
424
|
+
sources: list[str],
|
|
425
|
+
health: dict[str, dict[str, object]],
|
|
426
|
+
*,
|
|
427
|
+
now: float | None = None,
|
|
428
|
+
) -> tuple[list[str], list[str]]:
|
|
429
|
+
"""Move sources whose latest attempt failed recently behind the others.
|
|
430
|
+
|
|
431
|
+
Demoted sources are still tried, only later, so a recovered source comes
|
|
432
|
+
back automatically once its failure ages out of the TTL window.
|
|
433
|
+
"""
|
|
434
|
+
if not health:
|
|
435
|
+
return list(sources), []
|
|
436
|
+
current = time.time() if now is None else now
|
|
437
|
+
healthy: list[str] = []
|
|
438
|
+
demoted: list[str] = []
|
|
439
|
+
for source in sources:
|
|
440
|
+
state = health.get(source) or {}
|
|
441
|
+
last_failure = float(state.get("last_failure_at", 0) or 0)
|
|
442
|
+
last_success = float(state.get("last_success_at", 0) or 0)
|
|
443
|
+
recently_failing = (
|
|
444
|
+
int(state.get("consecutive_failures", 0) or 0) > 0
|
|
445
|
+
and last_failure > last_success
|
|
446
|
+
and current - last_failure < _PERSISTED_FAILURE_TTL_SECONDS
|
|
447
|
+
)
|
|
448
|
+
(demoted if recently_failing else healthy).append(source)
|
|
449
|
+
if not demoted or not healthy:
|
|
450
|
+
return list(sources), []
|
|
451
|
+
ordered = healthy + demoted
|
|
452
|
+
note = (
|
|
453
|
+
"Snapshot source order adjusted by recent health: "
|
|
454
|
+
f"{','.join(ordered)} (recently failed: {','.join(demoted)})"
|
|
455
|
+
)
|
|
456
|
+
return ordered, [note]
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def snapshot_source_health_snapshot(
|
|
460
|
+
sources: list[str] | tuple[str, ...] | None = None,
|
|
461
|
+
) -> dict[str, dict[str, float | bool | str]]:
|
|
462
|
+
"""Return in-process snapshot-source health without exposing credentials."""
|
|
463
|
+
now = time.monotonic()
|
|
464
|
+
requested = tuple(sources or tuple(_SOURCE_HEALTH))
|
|
465
|
+
with _SOURCE_HEALTH_LOCK:
|
|
466
|
+
snapshot: dict[str, dict[str, float | bool | str]] = {}
|
|
467
|
+
for source in requested:
|
|
468
|
+
state = dict(_SOURCE_HEALTH.get(source, {}))
|
|
469
|
+
disabled_until = float(state.get("disabled_until", 0.0))
|
|
470
|
+
cooldown_remaining = max(disabled_until - now, 0.0)
|
|
471
|
+
snapshot[source] = {
|
|
472
|
+
"successes": float(state.get("successes", 0.0)),
|
|
473
|
+
"failures": float(state.get("failures", 0.0)),
|
|
474
|
+
"total_failures": float(state.get("total_failures", 0.0)),
|
|
475
|
+
"last_rows": float(state.get("last_rows", 0.0)),
|
|
476
|
+
"avg_rows": float(state.get("avg_rows", 0.0)),
|
|
477
|
+
"disabled": disabled_until > now,
|
|
478
|
+
"cooldown_remaining_seconds": round(cooldown_remaining, 4),
|
|
479
|
+
"last_success_at": float(state.get("last_success_at", 0.0)),
|
|
480
|
+
"last_failure_at": float(state.get("last_failure_at", 0.0)),
|
|
481
|
+
"last_error": str(state.get("last_error", "")),
|
|
482
|
+
}
|
|
483
|
+
return snapshot
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _write_last_good_snapshot(
|
|
487
|
+
path_like: str | Path | None,
|
|
488
|
+
df: pd.DataFrame,
|
|
489
|
+
) -> None:
|
|
490
|
+
if path_like is None:
|
|
491
|
+
return
|
|
492
|
+
path = Path(path_like)
|
|
493
|
+
try:
|
|
494
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
495
|
+
payload = {
|
|
496
|
+
"version": _SNAPSHOT_CACHE_VERSION,
|
|
497
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
498
|
+
"metadata": {
|
|
499
|
+
"snapshot_source": str(df.attrs.get("snapshot_source", "")),
|
|
500
|
+
"row_count": int(len(df)),
|
|
501
|
+
"columns": list(df.columns),
|
|
502
|
+
},
|
|
503
|
+
"frame": json.loads(
|
|
504
|
+
df.to_json(orient="split", date_format="iso", force_ascii=False)
|
|
505
|
+
),
|
|
506
|
+
}
|
|
507
|
+
tmp_path = path.with_name(f".{path.name}.{time.time_ns()}.tmp")
|
|
508
|
+
tmp_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
|
509
|
+
tmp_path.replace(path)
|
|
510
|
+
except Exception as exc: # noqa: BLE001 - live snapshot should remain usable.
|
|
511
|
+
logger.warning("Failed to write last-good snapshot cache %s: %s", path, exc)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _read_last_good_snapshot(
|
|
515
|
+
path_like: str | Path | None,
|
|
516
|
+
*,
|
|
517
|
+
required_columns: list[str],
|
|
518
|
+
source_errors: list[str],
|
|
519
|
+
max_age_hours: float | None = None,
|
|
520
|
+
) -> pd.DataFrame | None:
|
|
521
|
+
if path_like is None:
|
|
522
|
+
return None
|
|
523
|
+
path = Path(path_like)
|
|
524
|
+
try:
|
|
525
|
+
stat = path.stat()
|
|
526
|
+
except FileNotFoundError:
|
|
527
|
+
return None
|
|
528
|
+
|
|
529
|
+
try:
|
|
530
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
531
|
+
if payload.get("version") != _SNAPSHOT_CACHE_VERSION:
|
|
532
|
+
raise ValueError("unsupported cache version")
|
|
533
|
+
frame = payload.get("frame")
|
|
534
|
+
if not isinstance(frame, dict):
|
|
535
|
+
raise ValueError("missing cached frame")
|
|
536
|
+
columns = frame.get("columns")
|
|
537
|
+
data = frame.get("data")
|
|
538
|
+
if not isinstance(columns, list) or not isinstance(data, list):
|
|
539
|
+
raise ValueError("malformed cached frame")
|
|
540
|
+
stale_age_hours = _cache_stale_age_hours(
|
|
541
|
+
stat.st_mtime,
|
|
542
|
+
created_at=str(payload.get("created_at", "")),
|
|
543
|
+
)
|
|
544
|
+
if max_age_hours is not None and max_age_hours >= 0 and stale_age_hours > max_age_hours:
|
|
545
|
+
raise ValueError(
|
|
546
|
+
f"cache stale_age_hours={stale_age_hours:.4g} exceeds max_age_hours={max_age_hours:.4g}"
|
|
547
|
+
)
|
|
548
|
+
cached = pd.DataFrame(data, columns=columns)
|
|
549
|
+
if cached.empty:
|
|
550
|
+
raise ValueError("cached snapshot is empty")
|
|
551
|
+
missing = _missing_required_columns(cached, required_columns)
|
|
552
|
+
if missing:
|
|
553
|
+
raise ValueError(f"missing required columns {','.join(missing)}")
|
|
554
|
+
except Exception as exc: # noqa: BLE001 - invalid cache should not mask live errors.
|
|
555
|
+
source_errors.append(f"last_good_cache: {exc}")
|
|
556
|
+
return None
|
|
557
|
+
|
|
558
|
+
cached.attrs["snapshot_source"] = "last_good_cache"
|
|
559
|
+
cached.attrs["fallback_used"] = True
|
|
560
|
+
cached.attrs["stale"] = True
|
|
561
|
+
cached.attrs["stale_age_hours"] = stale_age_hours
|
|
562
|
+
cached.attrs["source_errors"] = list(source_errors)
|
|
563
|
+
metadata = payload.get("metadata")
|
|
564
|
+
if isinstance(metadata, dict):
|
|
565
|
+
cached.attrs["last_good_snapshot_source"] = str(
|
|
566
|
+
metadata.get("snapshot_source", "")
|
|
567
|
+
)
|
|
568
|
+
cached.attrs["last_good_created_at"] = str(payload.get("created_at", ""))
|
|
569
|
+
logger.warning(
|
|
570
|
+
"Using last-good snapshot cache %s after live source failures: %s",
|
|
571
|
+
path,
|
|
572
|
+
"; ".join(source_errors),
|
|
573
|
+
)
|
|
574
|
+
return cached
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _cache_stale_age_hours(mtime: float, *, created_at: str = "") -> float:
|
|
578
|
+
modified = _parse_created_at(created_at) or datetime.fromtimestamp(mtime, tz=timezone.utc)
|
|
579
|
+
age_hours = (datetime.now(timezone.utc) - modified).total_seconds() / 3600.0
|
|
580
|
+
return round(max(age_hours, 0.0), 4)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _parse_created_at(value: str) -> datetime | None:
|
|
584
|
+
if not value:
|
|
585
|
+
return None
|
|
586
|
+
try:
|
|
587
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
588
|
+
except ValueError:
|
|
589
|
+
return None
|
|
590
|
+
if parsed.tzinfo is None:
|
|
591
|
+
return parsed.replace(tzinfo=timezone.utc)
|
|
592
|
+
return parsed.astimezone(timezone.utc)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _fetch_efinance() -> pd.DataFrame:
|
|
596
|
+
"""Fetch via efinance."""
|
|
597
|
+
import efinance as ef
|
|
598
|
+
|
|
599
|
+
df = ef.stock.get_realtime_quotes()
|
|
600
|
+
if df is None or df.empty:
|
|
601
|
+
raise RuntimeError("efinance returned empty data")
|
|
602
|
+
return _normalize(df, source="efinance")
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def _fetch_akshare_em() -> pd.DataFrame:
|
|
606
|
+
"""Fetch via akshare (eastmoney)."""
|
|
607
|
+
import akshare as ak
|
|
608
|
+
|
|
609
|
+
df = ak.stock_zh_a_spot_em()
|
|
610
|
+
if df is None or df.empty:
|
|
611
|
+
raise RuntimeError("akshare returned empty data")
|
|
612
|
+
return _normalize(df, source="akshare_em")
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _fetch_sina() -> pd.DataFrame:
|
|
616
|
+
"""Fetch A-share full-market snapshot directly from Sina Finance.
|
|
617
|
+
|
|
618
|
+
Sina's market-center endpoint is a lightweight direct HTTP source with PE,
|
|
619
|
+
PB, turnover and market-cap fields. It gives AlphaSift another non-wrapper,
|
|
620
|
+
non-Eastmoney-first snapshot option before falling back to Eastmoney-heavy
|
|
621
|
+
sources.
|
|
622
|
+
"""
|
|
623
|
+
url = "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData"
|
|
624
|
+
page = 1
|
|
625
|
+
page_size = 80
|
|
626
|
+
all_items = []
|
|
627
|
+
budget = _PageBudget("sina", per_request_timeout=15.0)
|
|
628
|
+
while True:
|
|
629
|
+
request_timeout = budget.request_timeout()
|
|
630
|
+
resp = requests.get(
|
|
631
|
+
url,
|
|
632
|
+
params={
|
|
633
|
+
"page": page,
|
|
634
|
+
"num": page_size,
|
|
635
|
+
"sort": "symbol",
|
|
636
|
+
"asc": 1,
|
|
637
|
+
"node": "hs_a",
|
|
638
|
+
"symbol": "",
|
|
639
|
+
"_s_r_a": "page",
|
|
640
|
+
},
|
|
641
|
+
headers={
|
|
642
|
+
"User-Agent": "Mozilla/5.0",
|
|
643
|
+
"Referer": "https://vip.stock.finance.sina.com.cn/mkt/",
|
|
644
|
+
},
|
|
645
|
+
timeout=request_timeout,
|
|
646
|
+
)
|
|
647
|
+
budget.pages += 1
|
|
648
|
+
resp.raise_for_status()
|
|
649
|
+
items = resp.json()
|
|
650
|
+
if not isinstance(items, list):
|
|
651
|
+
raise RuntimeError("sina snapshot returned malformed data")
|
|
652
|
+
if not items:
|
|
653
|
+
break
|
|
654
|
+
all_items.extend(items)
|
|
655
|
+
if len(items) < page_size:
|
|
656
|
+
break
|
|
657
|
+
page += 1
|
|
658
|
+
if not all_items:
|
|
659
|
+
raise RuntimeError("sina returned empty data")
|
|
660
|
+
df = pd.DataFrame(all_items)
|
|
661
|
+
for col in ("mktcap", "nmc"):
|
|
662
|
+
if col in df.columns:
|
|
663
|
+
# Sina exposes market caps in ten-thousand yuan; normalize to yuan.
|
|
664
|
+
df[col] = pd.to_numeric(df[col], errors="coerce") * 10000
|
|
665
|
+
return _normalize(df, source="sina")
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _fetch_em_datacenter() -> pd.DataFrame:
|
|
669
|
+
"""Fetch via eastmoney datacenter xuangu API.
|
|
670
|
+
|
|
671
|
+
This works even on weekends (returns last trading day data).
|
|
672
|
+
"""
|
|
673
|
+
url = "https://data.eastmoney.com/dataapi/xuangu/list"
|
|
674
|
+
all_items = []
|
|
675
|
+
budget = _PageBudget("em_datacenter", per_request_timeout=30.0)
|
|
676
|
+
page = 1
|
|
677
|
+
# 2000 rows per page keeps a full A-share pull to ~3 throttled requests.
|
|
678
|
+
# The endpoint rejects much larger pages (6000 returned a non-JSON body).
|
|
679
|
+
page_size = 2000
|
|
680
|
+
|
|
681
|
+
while True:
|
|
682
|
+
params = {
|
|
683
|
+
"st": "SECURITY_CODE",
|
|
684
|
+
"sr": "1",
|
|
685
|
+
"ps": str(page_size),
|
|
686
|
+
"p": str(page),
|
|
687
|
+
"sty": "SECUCODE,SECURITY_CODE,SECURITY_NAME_ABBR,NEW_PRICE,"
|
|
688
|
+
"OPEN_PRICE,HIGH_PRICE,LOW_PRICE,PRE_CLOSE_PRICE,VOLUME,"
|
|
689
|
+
"CHANGE_RATE,VOLUME_RATIO,DEAL_AMOUNT,TURNOVERRATE,"
|
|
690
|
+
"PE9,PBNEWMRQ,TOTAL_MARKET_CAP,FREE_CAP,INDUSTRY,"
|
|
691
|
+
"MAX_TRADE_DATE",
|
|
692
|
+
"filter": '(MARKET+in+("上交所主板","深交所主板","深交所创业板","上交所科创板","北交所","北京证券交易所"))',
|
|
693
|
+
"source": "SELECT_SECURITIES",
|
|
694
|
+
"client": "WEB",
|
|
695
|
+
}
|
|
696
|
+
headers = {
|
|
697
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
698
|
+
"Referer": "https://data.eastmoney.com/xuangu/",
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
resp = _eastmoney_get(url, params=params, headers=headers, timeout=budget.request_timeout())
|
|
702
|
+
budget.pages += 1
|
|
703
|
+
data = resp.json()
|
|
704
|
+
|
|
705
|
+
if not data.get("success"):
|
|
706
|
+
raise RuntimeError(f"em_datacenter API error: {data.get('message', 'unknown')}")
|
|
707
|
+
|
|
708
|
+
result = data.get("result") or {}
|
|
709
|
+
items = result.get("data") or []
|
|
710
|
+
all_items.extend(items)
|
|
711
|
+
|
|
712
|
+
total_count = int(result.get("count") or 0)
|
|
713
|
+
if not items or page * page_size >= total_count:
|
|
714
|
+
break
|
|
715
|
+
page += 1
|
|
716
|
+
|
|
717
|
+
if not all_items:
|
|
718
|
+
raise RuntimeError("em_datacenter returned no data")
|
|
719
|
+
|
|
720
|
+
df = pd.DataFrame(all_items)
|
|
721
|
+
return _normalize(df, source="em_datacenter")
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def _eastmoney_get(url: str, **kwargs) -> requests.Response:
|
|
725
|
+
"""GET EastMoney endpoints through one throttled shared session.
|
|
726
|
+
|
|
727
|
+
EastMoney endpoints are useful but more sensitive to bursty access than
|
|
728
|
+
lightweight direct sources. Keeping all direct calls behind one retrying
|
|
729
|
+
session, a process-wide interval, and a little jitter follows the same
|
|
730
|
+
anti-ban pattern used by a-stock-data's ``em_get`` helper.
|
|
731
|
+
"""
|
|
732
|
+
global _EM_LAST_REQUEST_AT, _EM_SESSION
|
|
733
|
+
with _EM_LOCK:
|
|
734
|
+
if _EM_SESSION is None:
|
|
735
|
+
_EM_SESSION = _build_eastmoney_session()
|
|
736
|
+
elapsed = time.monotonic() - _EM_LAST_REQUEST_AT
|
|
737
|
+
interval = _eastmoney_request_interval_seconds()
|
|
738
|
+
if elapsed < interval:
|
|
739
|
+
time.sleep(interval - elapsed)
|
|
740
|
+
response = _EM_SESSION.get(url, **kwargs)
|
|
741
|
+
_EM_LAST_REQUEST_AT = time.monotonic()
|
|
742
|
+
response.raise_for_status()
|
|
743
|
+
return response
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _build_eastmoney_session() -> requests.Session:
|
|
747
|
+
session = requests.Session()
|
|
748
|
+
retry = Retry(
|
|
749
|
+
total=2,
|
|
750
|
+
backoff_factor=0.5,
|
|
751
|
+
status_forcelist=(429, 500, 502, 503, 504),
|
|
752
|
+
allowed_methods=frozenset({"GET"}),
|
|
753
|
+
raise_on_status=False,
|
|
754
|
+
)
|
|
755
|
+
adapter = HTTPAdapter(max_retries=retry)
|
|
756
|
+
session.mount("https://", adapter)
|
|
757
|
+
session.mount("http://", adapter)
|
|
758
|
+
return session
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _eastmoney_request_interval_seconds() -> float:
|
|
762
|
+
min_interval = _float_env(
|
|
763
|
+
"ALPHASIFT_EASTMONEY_MIN_INTERVAL_SEC",
|
|
764
|
+
_EM_REQUEST_MIN_INTERVAL_SECONDS,
|
|
765
|
+
)
|
|
766
|
+
jitter = _float_env(
|
|
767
|
+
"ALPHASIFT_EASTMONEY_JITTER_SEC",
|
|
768
|
+
_EM_REQUEST_JITTER_SECONDS,
|
|
769
|
+
)
|
|
770
|
+
return max(min_interval, 0.0) + random.uniform(0.0, max(jitter, 0.0))
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _float_env(name: str, default: float) -> float:
|
|
774
|
+
value = os.getenv(name, "").strip()
|
|
775
|
+
return float(value) if value else float(default)
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def _fetch_tushare() -> pd.DataFrame:
|
|
779
|
+
"""Fetch latest available A-share snapshot via Tushare Pro.
|
|
780
|
+
|
|
781
|
+
Tushare is not a real-time source here. It is used as a resilient fallback
|
|
782
|
+
by joining the latest open trading day's daily quote and daily_basic data.
|
|
783
|
+
"""
|
|
784
|
+
token = (
|
|
785
|
+
os.getenv("TUSHARE_TOKEN", "").strip()
|
|
786
|
+
or os.getenv("TUSHARE_API_TOKEN", "").strip()
|
|
787
|
+
)
|
|
788
|
+
if not token:
|
|
789
|
+
raise RuntimeError("tushare requires TUSHARE_TOKEN")
|
|
790
|
+
|
|
791
|
+
import tushare as ts
|
|
792
|
+
|
|
793
|
+
pro = ts.pro_api(token)
|
|
794
|
+
_configure_tushare_client(pro, token=token)
|
|
795
|
+
trade_date = _resolve_tushare_trade_date(pro)
|
|
796
|
+
daily = pro.daily(
|
|
797
|
+
trade_date=trade_date,
|
|
798
|
+
fields="ts_code,trade_date,close,pct_chg,amount",
|
|
799
|
+
)
|
|
800
|
+
daily_basic = pro.daily_basic(
|
|
801
|
+
trade_date=trade_date,
|
|
802
|
+
fields="ts_code,turnover_rate,volume_ratio,pe,pb,total_mv,circ_mv",
|
|
803
|
+
)
|
|
804
|
+
stock_basic = pro.stock_basic(
|
|
805
|
+
exchange="",
|
|
806
|
+
list_status="L",
|
|
807
|
+
fields="ts_code,symbol,name,industry",
|
|
808
|
+
)
|
|
809
|
+
|
|
810
|
+
if daily is None or daily.empty:
|
|
811
|
+
raise RuntimeError(f"tushare daily returned empty data for {trade_date}")
|
|
812
|
+
if daily_basic is None or daily_basic.empty:
|
|
813
|
+
raise RuntimeError(f"tushare daily_basic returned empty data for {trade_date}")
|
|
814
|
+
|
|
815
|
+
return _prepare_tushare_snapshot(daily, daily_basic, stock_basic)
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def _configure_tushare_client(pro: object, *, token: str) -> None:
|
|
819
|
+
try:
|
|
820
|
+
setattr(pro, "_DataApi__token", token)
|
|
821
|
+
except Exception:
|
|
822
|
+
pass
|
|
823
|
+
|
|
824
|
+
http_url = (
|
|
825
|
+
os.getenv("TUSHARE_API_URL", "").strip()
|
|
826
|
+
or os.getenv("TUSHARE_HTTP_URL", "").strip()
|
|
827
|
+
or _DEFAULT_TUSHARE_HTTP_URL
|
|
828
|
+
)
|
|
829
|
+
try:
|
|
830
|
+
setattr(pro, "_DataApi__http_url", http_url)
|
|
831
|
+
except Exception:
|
|
832
|
+
pass
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def _resolve_tushare_trade_date(pro) -> str:
|
|
836
|
+
"""Return the latest open trade date for Tushare requests."""
|
|
837
|
+
explicit = os.getenv("TUSHARE_TRADE_DATE", "").strip()
|
|
838
|
+
if explicit:
|
|
839
|
+
return explicit
|
|
840
|
+
|
|
841
|
+
end = date.today()
|
|
842
|
+
start = end - timedelta(days=30)
|
|
843
|
+
calendar = pro.trade_cal(
|
|
844
|
+
exchange="",
|
|
845
|
+
start_date=start.strftime("%Y%m%d"),
|
|
846
|
+
end_date=end.strftime("%Y%m%d"),
|
|
847
|
+
is_open="1",
|
|
848
|
+
fields="cal_date,is_open",
|
|
849
|
+
)
|
|
850
|
+
if calendar is None or calendar.empty or "cal_date" not in calendar.columns:
|
|
851
|
+
raise RuntimeError("tushare trade_cal returned no open trading days")
|
|
852
|
+
return str(calendar["cal_date"].max())
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def _prepare_tushare_snapshot(
|
|
856
|
+
daily: pd.DataFrame,
|
|
857
|
+
daily_basic: pd.DataFrame,
|
|
858
|
+
stock_basic: pd.DataFrame | None,
|
|
859
|
+
) -> pd.DataFrame:
|
|
860
|
+
"""Join and unit-normalize Tushare tables into the common snapshot schema."""
|
|
861
|
+
merged = daily.merge(daily_basic, on="ts_code", how="left")
|
|
862
|
+
if stock_basic is not None and not stock_basic.empty:
|
|
863
|
+
merged = merged.merge(stock_basic, on="ts_code", how="left")
|
|
864
|
+
if "symbol" not in merged.columns:
|
|
865
|
+
merged["symbol"] = merged["ts_code"].astype(str).str.split(".").str[0]
|
|
866
|
+
else:
|
|
867
|
+
fallback_symbol = merged["ts_code"].astype(str).str.split(".").str[0]
|
|
868
|
+
merged["symbol"] = merged["symbol"].fillna(fallback_symbol)
|
|
869
|
+
|
|
870
|
+
# Tushare units: amount is thousand yuan; market caps are ten-thousand yuan.
|
|
871
|
+
for col, multiplier in {
|
|
872
|
+
"amount": 1000,
|
|
873
|
+
"total_mv": 10000,
|
|
874
|
+
"circ_mv": 10000,
|
|
875
|
+
}.items():
|
|
876
|
+
if col in merged.columns:
|
|
877
|
+
merged[col] = pd.to_numeric(merged[col], errors="coerce") * multiplier
|
|
878
|
+
|
|
879
|
+
return _normalize(merged, source="tushare")
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _extract_cn_quote_date(df: pd.DataFrame) -> str | None:
|
|
883
|
+
"""Extract latest ISO trading date from common CN snapshot date columns."""
|
|
884
|
+
for col in ("trade_date", "date", "日期", "MAX_TRADE_DATE"):
|
|
885
|
+
if col not in df.columns:
|
|
886
|
+
continue
|
|
887
|
+
dates: list[str] = []
|
|
888
|
+
for raw in df[col].dropna().astype(str):
|
|
889
|
+
token = raw.strip()
|
|
890
|
+
if len(token) == 8 and token.isdigit():
|
|
891
|
+
token = f"{token[:4]}-{token[4:6]}-{token[6:8]}"
|
|
892
|
+
else:
|
|
893
|
+
token = token[:10]
|
|
894
|
+
try:
|
|
895
|
+
dates.append(date.fromisoformat(token).isoformat())
|
|
896
|
+
except ValueError:
|
|
897
|
+
continue
|
|
898
|
+
if dates:
|
|
899
|
+
return max(dates)
|
|
900
|
+
return None
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def _normalize(df: pd.DataFrame, source: str) -> pd.DataFrame:
|
|
904
|
+
"""Normalize column names to a standard schema.
|
|
905
|
+
|
|
906
|
+
Standard columns: code, name, price, change_pct, amount, total_mv,
|
|
907
|
+
circ_mv, pe_ratio, pb_ratio, volume_ratio, turnover_rate
|
|
908
|
+
"""
|
|
909
|
+
df = df.copy()
|
|
910
|
+
|
|
911
|
+
if source == "efinance":
|
|
912
|
+
standard_cols = {
|
|
913
|
+
"code": ["股票代码", "代码"],
|
|
914
|
+
"name": ["股票名称", "名称"],
|
|
915
|
+
"price": ["最新价"],
|
|
916
|
+
"change_pct": ["涨跌幅"],
|
|
917
|
+
"amount": ["成交额"],
|
|
918
|
+
"total_mv": ["总市值"],
|
|
919
|
+
"circ_mv": ["流通市值"],
|
|
920
|
+
"pe_ratio": ["动态市盈率", "市盈率(动)"],
|
|
921
|
+
"pb_ratio": ["市净率"],
|
|
922
|
+
"volume_ratio": ["量比"],
|
|
923
|
+
"turnover_rate": ["换手率"],
|
|
924
|
+
"industry": ["行业", "所属行业", "行业板块"],
|
|
925
|
+
"concepts": ["概念", "概念题材", "题材"],
|
|
926
|
+
}
|
|
927
|
+
elif source == "akshare_em":
|
|
928
|
+
standard_cols = {
|
|
929
|
+
"code": ["代码"],
|
|
930
|
+
"name": ["名称"],
|
|
931
|
+
"price": ["最新价"],
|
|
932
|
+
"change_pct": ["涨跌幅"],
|
|
933
|
+
"amount": ["成交额"],
|
|
934
|
+
"total_mv": ["总市值"],
|
|
935
|
+
"circ_mv": ["流通市值"],
|
|
936
|
+
"pe_ratio": ["市盈率-动态", "市盈率(动)"],
|
|
937
|
+
"pb_ratio": ["市净率"],
|
|
938
|
+
"volume_ratio": ["量比"],
|
|
939
|
+
"turnover_rate": ["换手率"],
|
|
940
|
+
"industry": ["行业", "所属行业", "行业板块"],
|
|
941
|
+
"concepts": ["概念", "概念题材", "题材"],
|
|
942
|
+
}
|
|
943
|
+
elif source == "sina":
|
|
944
|
+
standard_cols = {
|
|
945
|
+
"code": ["code"],
|
|
946
|
+
"name": ["name"],
|
|
947
|
+
"price": ["trade"],
|
|
948
|
+
"change_pct": ["changepercent"],
|
|
949
|
+
"amount": ["amount"],
|
|
950
|
+
"total_mv": ["mktcap"],
|
|
951
|
+
"circ_mv": ["nmc"],
|
|
952
|
+
"pe_ratio": ["per"],
|
|
953
|
+
"pb_ratio": ["pb"],
|
|
954
|
+
"turnover_rate": ["turnoverratio"],
|
|
955
|
+
}
|
|
956
|
+
elif source == "em_datacenter":
|
|
957
|
+
standard_cols = {
|
|
958
|
+
"code": ["SECURITY_CODE"],
|
|
959
|
+
"name": ["SECURITY_NAME_ABBR"],
|
|
960
|
+
"price": ["NEW_PRICE"],
|
|
961
|
+
"change_pct": ["CHANGE_RATE"],
|
|
962
|
+
"amount": ["DEAL_AMOUNT"],
|
|
963
|
+
"total_mv": ["TOTAL_MARKET_CAP"],
|
|
964
|
+
"circ_mv": ["FREE_CAP", "CIRCULATION_MARKET_CAP"],
|
|
965
|
+
"pe_ratio": ["PE9"],
|
|
966
|
+
"pb_ratio": ["PBNEWMRQ"],
|
|
967
|
+
"volume_ratio": ["VOLUME_RATIO"],
|
|
968
|
+
"turnover_rate": ["TURNOVERRATE"],
|
|
969
|
+
"industry": ["INDUSTRY", "INDUSTRY_NAME", "BOARD_NAME"],
|
|
970
|
+
"concepts": ["CONCEPT", "CONCEPT_NAME", "THEME_NAME"],
|
|
971
|
+
}
|
|
972
|
+
elif source == "tushare":
|
|
973
|
+
standard_cols = {
|
|
974
|
+
"code": ["symbol", "code"],
|
|
975
|
+
"name": ["name"],
|
|
976
|
+
"price": ["close"],
|
|
977
|
+
"change_pct": ["pct_chg"],
|
|
978
|
+
"amount": ["amount"],
|
|
979
|
+
"total_mv": ["total_mv"],
|
|
980
|
+
"circ_mv": ["circ_mv"],
|
|
981
|
+
"pe_ratio": ["pe"],
|
|
982
|
+
"pb_ratio": ["pb"],
|
|
983
|
+
"volume_ratio": ["volume_ratio"],
|
|
984
|
+
"turnover_rate": ["turnover_rate"],
|
|
985
|
+
"industry": ["industry"],
|
|
986
|
+
"concepts": ["concepts"],
|
|
987
|
+
}
|
|
988
|
+
else:
|
|
989
|
+
standard_cols = {}
|
|
990
|
+
|
|
991
|
+
df = _rename_standard_columns(df, standard_cols)
|
|
992
|
+
|
|
993
|
+
# Coerce numeric columns
|
|
994
|
+
numeric_cols = [
|
|
995
|
+
"price", "change_pct", "amount", "total_mv", "circ_mv",
|
|
996
|
+
"pe_ratio", "pb_ratio", "volume_ratio", "turnover_rate",
|
|
997
|
+
]
|
|
998
|
+
for col in numeric_cols:
|
|
999
|
+
if col in df.columns:
|
|
1000
|
+
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
1001
|
+
|
|
1002
|
+
# Drop rows without a valid price
|
|
1003
|
+
if "price" in df.columns:
|
|
1004
|
+
df = df.dropna(subset=["price"])
|
|
1005
|
+
df = df[df["price"] > 0]
|
|
1006
|
+
|
|
1007
|
+
quote_date = _extract_cn_quote_date(df)
|
|
1008
|
+
if quote_date:
|
|
1009
|
+
df.attrs["quote_date"] = quote_date
|
|
1010
|
+
df.attrs["snapshot_source"] = source
|
|
1011
|
+
return df
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
def _rename_standard_columns(
|
|
1015
|
+
df: pd.DataFrame,
|
|
1016
|
+
standard_cols: dict[str, list[str]],
|
|
1017
|
+
) -> pd.DataFrame:
|
|
1018
|
+
"""Rename the first matching source column for each standard field."""
|
|
1019
|
+
rename_map: dict[str, str] = {}
|
|
1020
|
+
for standard_name, candidates in standard_cols.items():
|
|
1021
|
+
for candidate in candidates:
|
|
1022
|
+
if candidate in df.columns:
|
|
1023
|
+
rename_map[candidate] = standard_name
|
|
1024
|
+
break
|
|
1025
|
+
return df.rename(columns=rename_map)
|