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/pack.py
ADDED
|
@@ -0,0 +1,1470 @@
|
|
|
1
|
+
"""Build, verify, and use the offline CN daily bar pack."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import socket
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Iterator, Sequence
|
|
14
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
15
|
+
from contextlib import contextmanager
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from datetime import date, datetime, timedelta, timezone
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from tempfile import TemporaryDirectory
|
|
20
|
+
import time
|
|
21
|
+
from typing import Any, Protocol
|
|
22
|
+
from urllib.parse import urlencode
|
|
23
|
+
from zoneinfo import ZoneInfo
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
import pandas as pd
|
|
27
|
+
import requests
|
|
28
|
+
from requests.adapters import HTTPAdapter
|
|
29
|
+
|
|
30
|
+
from alphasift.config import Config
|
|
31
|
+
from alphasift.daily import _BAOSTOCK_LOCK, _to_baostock_code, _to_tencent_code, fetch_daily_history
|
|
32
|
+
from alphasift.markets import get_market, latest_settled_close
|
|
33
|
+
from alphasift.snapshot import fetch_cn_snapshot, fetch_snapshot_with_fallback
|
|
34
|
+
|
|
35
|
+
DEFAULT_DAYS = 250
|
|
36
|
+
DEFAULT_TAG = "data-cn"
|
|
37
|
+
DEFAULT_REPO = ""
|
|
38
|
+
FIELDS = ("open", "high", "low", "close", "pre_close", "volume", "amount")
|
|
39
|
+
PRICE_FIELDS = FIELDS[:5]
|
|
40
|
+
META_FIELDS = ("name", "industry", "pe_ratio", "pb_ratio", "total_mv", "circ_mv", "list_date", "is_st")
|
|
41
|
+
_ASSETS = ("daily.npz", "meta.csv.gz")
|
|
42
|
+
_MANIFEST = "manifest.json"
|
|
43
|
+
_SCHEMA_VERSION = 1
|
|
44
|
+
_MIN_COVERAGE = 0.8
|
|
45
|
+
_TICKPLUS_FIELDS = dict(zip(("o", "h", "l", "c", "pc", "v", "a"), FIELDS))
|
|
46
|
+
_BAOSTOCK_FIELDS = ("date", "open", "high", "low", "close", "preclose", "volume", "amount", "tradestatus")
|
|
47
|
+
_CODE_PATTERN = re.compile(r"(?:(?:sh|sz|bj)\.?)?([0-9]{1,6})(?:\.(?:sh|ss|sz|bj)|\.0)?", re.I)
|
|
48
|
+
_A_SHARE = ("600", "601", "603", "605", "688", "689", "000", "001", "002", "003", "300", "301", "4", "8", "920")
|
|
49
|
+
_CN_TZ = ZoneInfo(get_market("cn").timezone)
|
|
50
|
+
# Raw quote columns the existing CN snapshot sources keep next to the normalized ones:
|
|
51
|
+
# source -> (open, high, low, previous close, volume, shares per volume unit).
|
|
52
|
+
_SNAPSHOT_QUOTES = {
|
|
53
|
+
"sina": ("open", "high", "low", "settlement", "volume", 1),
|
|
54
|
+
"efinance": ("今开", "最高", "最低", "昨日收盘", "成交量", 100),
|
|
55
|
+
"akshare_em": ("今开", "最高", "最低", "昨收", "成交量", 100),
|
|
56
|
+
"em_datacenter": ("OPEN_PRICE", "HIGH_PRICE", "LOW_PRICE", "PRE_CLOSE_PRICE", "VOLUME", 100),
|
|
57
|
+
}
|
|
58
|
+
_REFERENCE_CODES = ("000001", "600519", "601398")
|
|
59
|
+
_MAX_FAILED_CODES = 0.05
|
|
60
|
+
_PACK_THREAD_LOCK = threading.Lock()
|
|
61
|
+
_TENCENT_QUOTE_URL = "https://qt.gtimg.cn/q="
|
|
62
|
+
_TENCENT_HEADERS = {"User-Agent": "Mozilla/5.0"}
|
|
63
|
+
_YFINANCE_BATCH_SIZE = 100
|
|
64
|
+
_YFINANCE_CHUNK_DELAY_SEC = 0.25
|
|
65
|
+
logger = logging.getLogger(__name__)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _tencent_volume_multiplier(code: str) -> int:
|
|
69
|
+
"""STAR (688) and CDR (689) report Tencent volume in shares; others use lots."""
|
|
70
|
+
return 1 if code.startswith(("688", "689")) else 100
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _tencent_session(workers: int = 2) -> requests.Session:
|
|
74
|
+
session = requests.Session()
|
|
75
|
+
pool = max(4, int(workers))
|
|
76
|
+
adapter = HTTPAdapter(pool_connections=pool, pool_maxsize=pool)
|
|
77
|
+
session.mount("https://", adapter)
|
|
78
|
+
session.mount("http://", adapter)
|
|
79
|
+
return session
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class PackError(ValueError):
|
|
83
|
+
"""The pack or its input did not pass validation."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class SnapshotStitchError(PackError):
|
|
87
|
+
"""The error text can be surfaced as a snapshot degradation note."""
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class DailyPack:
|
|
92
|
+
dates: np.ndarray
|
|
93
|
+
codes: np.ndarray
|
|
94
|
+
matrices: dict[str, np.ndarray]
|
|
95
|
+
meta: pd.DataFrame
|
|
96
|
+
sources: tuple[str, ...] = ()
|
|
97
|
+
manifest: dict = field(default_factory=dict)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def trade_date(self) -> str:
|
|
101
|
+
return str(self.dates[-1])
|
|
102
|
+
|
|
103
|
+
def history(self, code: str, *, include_missing: bool = False) -> pd.DataFrame:
|
|
104
|
+
"""Return one code's raw bars, dropping missing sessions by default."""
|
|
105
|
+
code = _code(code)
|
|
106
|
+
index = self.codes.searchsorted(code)
|
|
107
|
+
if index == len(self.codes) or self.codes[index] != code:
|
|
108
|
+
raise KeyError(code)
|
|
109
|
+
frame = pd.DataFrame({"date": self.dates, **{key: self.matrices[key][:, index] for key in FIELDS}})
|
|
110
|
+
return frame if include_missing else frame.dropna(subset=["close"]).reset_index(drop=True)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class IncrementalProvider(Protocol):
|
|
114
|
+
name: str
|
|
115
|
+
|
|
116
|
+
def fetch_day(self, trade_date: str) -> pd.DataFrame:
|
|
117
|
+
"""Return raw CN bars for one session, with code and all FIELDS (volume in shares)."""
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class TickPlusProvider:
|
|
122
|
+
"""Optional TickPlus updatedaykline source, used only when TICKPLUS_API_KEY is set.
|
|
123
|
+
|
|
124
|
+
Covers about a week. Not live-verified: fixture coverage follows the
|
|
125
|
+
documented fields and the API's list format. The documented endpoint uses
|
|
126
|
+
HTTP and places the key in the query string.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
name = "tickplus"
|
|
130
|
+
|
|
131
|
+
def fetch_day(self, trade_date: str) -> pd.DataFrame:
|
|
132
|
+
day = _iso_date(trade_date)
|
|
133
|
+
token = os.getenv("TICKPLUS_API_KEY", "").strip()
|
|
134
|
+
if not token:
|
|
135
|
+
raise PackError("TickPlus requires TICKPLUS_API_KEY")
|
|
136
|
+
if day < (datetime.now(_CN_TZ).date() - timedelta(days=7)).isoformat():
|
|
137
|
+
raise PackError("TickPlus updatedaykline only covers roughly the last week")
|
|
138
|
+
query = urlencode({"symbol": "stock", "dividend": "1", "tradeDate": day, "token": token})
|
|
139
|
+
# http.client has request tracing off by default. Avoid HTTP adapters
|
|
140
|
+
# whose DEBUG logs include request targets, and never follow redirects.
|
|
141
|
+
conn = http.client.HTTPConnection("api.tickplus.org", timeout=30)
|
|
142
|
+
try:
|
|
143
|
+
conn.request("GET", "/plus/basic/updatedaykline?" + query)
|
|
144
|
+
response = conn.getresponse()
|
|
145
|
+
status = response.status
|
|
146
|
+
body = response.read() if status == 200 else b""
|
|
147
|
+
except (OSError, http.client.HTTPException, ValueError):
|
|
148
|
+
raise PackError("TickPlus updatedaykline request failed") from None
|
|
149
|
+
finally:
|
|
150
|
+
conn.close()
|
|
151
|
+
if status != 200:
|
|
152
|
+
raise PackError(f"TickPlus updatedaykline HTTP status {status}")
|
|
153
|
+
try:
|
|
154
|
+
payload = json.loads(body)
|
|
155
|
+
except ValueError:
|
|
156
|
+
raise PackError("TickPlus updatedaykline returned invalid JSON") from None
|
|
157
|
+
return _parse_tickplus_day(payload, day)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class SnapshotProvider:
|
|
161
|
+
"""Today's full-market bars from the project's existing CN snapshot sources.
|
|
162
|
+
|
|
163
|
+
Only valid for the latest settled session: a snapshot has no history, so
|
|
164
|
+
an older date is left to the daily-history gap fill.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
name = "snapshot"
|
|
168
|
+
|
|
169
|
+
def __init__(self, config: Config | None = None) -> None:
|
|
170
|
+
self._config = config
|
|
171
|
+
|
|
172
|
+
def fetch_day(self, trade_date: str) -> pd.DataFrame:
|
|
173
|
+
day = _iso_date(trade_date)
|
|
174
|
+
if day != expected_trade_date():
|
|
175
|
+
raise PackError("A snapshot only covers the latest settled session")
|
|
176
|
+
config = self._config or Config.from_env()
|
|
177
|
+
for source in config.snapshot_source_priority:
|
|
178
|
+
if source not in _SNAPSHOT_QUOTES:
|
|
179
|
+
continue
|
|
180
|
+
try:
|
|
181
|
+
snapshot = fetch_cn_snapshot(source)
|
|
182
|
+
if snapshot.attrs.get("quote_date") not in (None, day):
|
|
183
|
+
raise PackError("Snapshot quote date does not match the requested date")
|
|
184
|
+
bars = _normalize_day(_snapshot_bars(snapshot))
|
|
185
|
+
except Exception as exc:
|
|
186
|
+
logger.warning("Snapshot source %s cannot supply daily bars: %s", source, exc)
|
|
187
|
+
continue
|
|
188
|
+
self.name = f"snapshot:{source}"
|
|
189
|
+
return bars
|
|
190
|
+
raise PackError("No snapshot source supplied open/high/low/previous close")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class TencentQuoteProvider:
|
|
194
|
+
"""Today's full-market bars from Tencent batch quotes (qt.gtimg.cn)."""
|
|
195
|
+
|
|
196
|
+
name = "tencent_quote"
|
|
197
|
+
|
|
198
|
+
def __init__(
|
|
199
|
+
self,
|
|
200
|
+
codes: Sequence[str] | None = None,
|
|
201
|
+
*,
|
|
202
|
+
config: Config | None = None,
|
|
203
|
+
batch_size: int = 80,
|
|
204
|
+
workers: int = 2,
|
|
205
|
+
batch_delay_sec: float = 0.15,
|
|
206
|
+
) -> None:
|
|
207
|
+
self._codes = list(dict.fromkeys(_code(c) for c in codes)) if codes else []
|
|
208
|
+
self._config = config
|
|
209
|
+
self._batch_size = max(1, int(batch_size))
|
|
210
|
+
self._workers = max(1, int(workers))
|
|
211
|
+
self._batch_delay_sec = max(0.0, float(batch_delay_sec))
|
|
212
|
+
|
|
213
|
+
def fetch_day(self, trade_date: str) -> pd.DataFrame:
|
|
214
|
+
day = _iso_date(trade_date)
|
|
215
|
+
codes = list(self._codes)
|
|
216
|
+
if not codes:
|
|
217
|
+
snapshot = _latest_snapshot(self._config or Config.from_env())
|
|
218
|
+
codes = sorted({c for c in snapshot["code"].map(_code) if c.startswith(_A_SHARE)})
|
|
219
|
+
if not codes:
|
|
220
|
+
raise PackError("No A-share codes available for Tencent batch quotes")
|
|
221
|
+
chunks = [codes[i:i + self._batch_size] for i in range(0, len(codes), self._batch_size)]
|
|
222
|
+
local_state = threading.local()
|
|
223
|
+
created_sessions: list[requests.Session] = []
|
|
224
|
+
sessions_lock = threading.Lock()
|
|
225
|
+
|
|
226
|
+
def fetch_chunk(idx_chunk: tuple[int, list[str]]) -> list[dict[str, object]]:
|
|
227
|
+
idx, chunk = idx_chunk
|
|
228
|
+
if idx > 0 and self._batch_delay_sec > 0:
|
|
229
|
+
time.sleep(self._batch_delay_sec)
|
|
230
|
+
session = getattr(local_state, "session", None)
|
|
231
|
+
if session is None:
|
|
232
|
+
session = _tencent_session(self._workers)
|
|
233
|
+
local_state.session = session
|
|
234
|
+
with sessions_lock:
|
|
235
|
+
created_sessions.append(session)
|
|
236
|
+
symbols = ",".join(_to_tencent_code(c) for c in chunk)
|
|
237
|
+
resp = session.get(f"{_TENCENT_QUOTE_URL}{symbols}", headers=_TENCENT_HEADERS, timeout=10)
|
|
238
|
+
resp.raise_for_status()
|
|
239
|
+
text = resp.content.decode("gbk", errors="replace")
|
|
240
|
+
return _parse_tencent_quote_lines(text, day)
|
|
241
|
+
|
|
242
|
+
rows: list[dict[str, object]] = []
|
|
243
|
+
indexed_chunks = list(enumerate(chunks))
|
|
244
|
+
try:
|
|
245
|
+
if self._workers <= 1 or len(chunks) <= 1:
|
|
246
|
+
for item in indexed_chunks:
|
|
247
|
+
rows.extend(fetch_chunk(item))
|
|
248
|
+
else:
|
|
249
|
+
with ThreadPoolExecutor(max_workers=min(self._workers, len(chunks))) as pool:
|
|
250
|
+
for chunk_rows in pool.map(fetch_chunk, indexed_chunks):
|
|
251
|
+
rows.extend(chunk_rows)
|
|
252
|
+
finally:
|
|
253
|
+
for sess in created_sessions:
|
|
254
|
+
sess.close()
|
|
255
|
+
if not rows:
|
|
256
|
+
raise PackError(f"Tencent batch quotes returned no bars for {day}")
|
|
257
|
+
frame = pd.DataFrame(rows, columns=["code", *FIELDS]).drop_duplicates("code", keep="last")
|
|
258
|
+
return _normalize_day(frame).reset_index(drop=True)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _parse_tencent_quote_lines(text: str, trade_date: str) -> list[dict[str, object]]:
|
|
262
|
+
rows: list[dict[str, object]] = []
|
|
263
|
+
for line in text.splitlines():
|
|
264
|
+
if "=\"" not in line:
|
|
265
|
+
continue
|
|
266
|
+
body = line.split("=\"", 1)[1].rsplit("\";", 1)[0]
|
|
267
|
+
parts = body.split("~")
|
|
268
|
+
if len(parts) <= 37:
|
|
269
|
+
continue
|
|
270
|
+
raw_code = parts[2].strip()
|
|
271
|
+
if not raw_code:
|
|
272
|
+
continue
|
|
273
|
+
try:
|
|
274
|
+
code = _code(raw_code)
|
|
275
|
+
except PackError:
|
|
276
|
+
continue
|
|
277
|
+
digits = "".join(ch for ch in parts[30] if ch.isdigit())
|
|
278
|
+
if len(digits) < 8:
|
|
279
|
+
continue
|
|
280
|
+
quote_date = f"{digits[:4]}-{digits[4:6]}-{digits[6:8]}"
|
|
281
|
+
if quote_date != trade_date:
|
|
282
|
+
continue
|
|
283
|
+
try:
|
|
284
|
+
close_v = float(parts[3])
|
|
285
|
+
pre_close_v = float(parts[4])
|
|
286
|
+
open_v = float(parts[5])
|
|
287
|
+
high_v = float(parts[33])
|
|
288
|
+
low_v = float(parts[34])
|
|
289
|
+
vol_v = float(parts[6])
|
|
290
|
+
amt_wan = float(parts[37]) if parts[37].strip() else 0.0
|
|
291
|
+
except ValueError:
|
|
292
|
+
continue
|
|
293
|
+
if not all(np.isfinite(v) for v in (close_v, pre_close_v, open_v, high_v, low_v, vol_v, amt_wan)):
|
|
294
|
+
continue
|
|
295
|
+
if open_v <= 0 or close_v <= 0 or high_v <= 0 or low_v <= 0 or pre_close_v <= 0 or vol_v <= 0 or amt_wan < 0:
|
|
296
|
+
continue
|
|
297
|
+
rows.append({
|
|
298
|
+
"code": code,
|
|
299
|
+
"open": open_v,
|
|
300
|
+
"high": high_v,
|
|
301
|
+
"low": low_v,
|
|
302
|
+
"close": close_v,
|
|
303
|
+
"pre_close": pre_close_v,
|
|
304
|
+
"volume": vol_v * _tencent_volume_multiplier(code),
|
|
305
|
+
"amount": amt_wan * 10000.0,
|
|
306
|
+
})
|
|
307
|
+
return rows
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _snapshot_bars(snapshot: pd.DataFrame) -> pd.DataFrame:
|
|
311
|
+
"""Map a snapshot's raw quote columns onto the pack fields; drop untraded rows."""
|
|
312
|
+
frame = snapshot.copy()
|
|
313
|
+
if "close" not in frame.columns and "price" in frame.columns:
|
|
314
|
+
frame = frame.rename(columns={"price": "close"})
|
|
315
|
+
quotes = _SNAPSHOT_QUOTES.get(str(snapshot.attrs.get("snapshot_source", "")))
|
|
316
|
+
if quotes and "pre_close" not in frame.columns:
|
|
317
|
+
*names, lot = quotes
|
|
318
|
+
if all(name in frame.columns for name in names):
|
|
319
|
+
for key, name in zip(("open", "high", "low", "pre_close", "volume"), names):
|
|
320
|
+
frame[key] = pd.to_numeric(frame[name], errors="coerce")
|
|
321
|
+
frame["volume"] *= lot
|
|
322
|
+
if {"open", "volume"} <= set(frame.columns):
|
|
323
|
+
traded = pd.to_numeric(frame["open"], errors="coerce").gt(0) & pd.to_numeric(frame["volume"], errors="coerce").gt(0)
|
|
324
|
+
frame = frame.loc[traded]
|
|
325
|
+
return frame
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _parse_tickplus_day(payload: object, trade_date: str) -> pd.DataFrame:
|
|
329
|
+
expected = {"t", "code", *_TICKPLUS_FIELDS}
|
|
330
|
+
if not isinstance(payload, list) or not payload or any(
|
|
331
|
+
not isinstance(row, dict) or not expected <= row.keys() for row in payload
|
|
332
|
+
):
|
|
333
|
+
raise PackError("TickPlus updatedaykline returned invalid or empty bar data")
|
|
334
|
+
# Select only documented fields. Ignore any vendor messages or other extras.
|
|
335
|
+
frame = pd.DataFrame.from_records(payload, columns=["t", "code", *_TICKPLUS_FIELDS])
|
|
336
|
+
if not frame["t"].astype("string").str.slice(0, 10).eq(trade_date).fillna(False).all():
|
|
337
|
+
raise PackError("TickPlus updatedaykline returned bars for a different trade date")
|
|
338
|
+
frame = frame.drop(columns="t").rename(columns=_TICKPLUS_FIELDS)
|
|
339
|
+
frame["volume"] = pd.to_numeric(frame["volume"], errors="coerce") * 100
|
|
340
|
+
# Suspensions can be omitted or carried as zero-volume rows by a feed.
|
|
341
|
+
bars = _normalize_day(frame.loc[frame["volume"] != 0])
|
|
342
|
+
if bars.empty:
|
|
343
|
+
raise PackError("TickPlus updatedaykline returned no trading bars")
|
|
344
|
+
return bars.reset_index(drop=True)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def pack_dir(config: Config | None = None) -> Path:
|
|
348
|
+
"""Resolve the pack directory from config override, environment, or AlphaSift's data dir."""
|
|
349
|
+
if config is not None and config.daily_pack_dir is not None:
|
|
350
|
+
return Path(config.daily_pack_dir).expanduser()
|
|
351
|
+
override = os.getenv("ALPHASIFT_PACK_DIR", "").strip()
|
|
352
|
+
if override:
|
|
353
|
+
return Path(override).expanduser()
|
|
354
|
+
resolved = config or Config.from_env()
|
|
355
|
+
if resolved.daily_pack_dir is not None:
|
|
356
|
+
return Path(resolved.daily_pack_dir).expanduser()
|
|
357
|
+
return resolved.data_dir / "pack" / "cn"
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def expected_trade_date(now: datetime | None = None) -> str:
|
|
361
|
+
"""Estimate the latest settled CN session using weekdays; use an explicit date on holidays."""
|
|
362
|
+
local = (now or datetime.now(_CN_TZ)).astimezone(_CN_TZ)
|
|
363
|
+
settled = latest_settled_close("cn", local)
|
|
364
|
+
if settled:
|
|
365
|
+
return settled[0].isoformat()
|
|
366
|
+
day = local.date() - timedelta(days=1)
|
|
367
|
+
while day.weekday() >= 5:
|
|
368
|
+
day -= timedelta(days=1)
|
|
369
|
+
return day.isoformat()
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def is_fresh(pack: DailyPack, expected: str | date) -> bool:
|
|
373
|
+
"""Return whether the pack ends on the expected CN trade date."""
|
|
374
|
+
return pack.trade_date == _iso_date(expected)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def load_pack(directory: str | Path | None = None) -> DailyPack:
|
|
378
|
+
"""Verify and load the CN pack, including both assets' SHA-256 hashes."""
|
|
379
|
+
path = Path(directory) if directory is not None else pack_dir()
|
|
380
|
+
with _pack_lock(path):
|
|
381
|
+
return _load_pack(path)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _load_pack(path: Path) -> DailyPack:
|
|
385
|
+
manifest = _read_manifest(path)
|
|
386
|
+
for name in _ASSETS:
|
|
387
|
+
_verify_asset(path / name, manifest["files"][name])
|
|
388
|
+
with np.load(path / "daily.npz", allow_pickle=False) as archive:
|
|
389
|
+
dates, codes = archive["dates"], archive["codes"]
|
|
390
|
+
matrices = {key: archive[key] for key in FIELDS}
|
|
391
|
+
meta = pd.read_csv(
|
|
392
|
+
path / "meta.csv.gz", dtype={"code": str, "name": str, "industry": str, "list_date": str, "is_st": "boolean"},
|
|
393
|
+
)
|
|
394
|
+
pack = DailyPack(dates, codes, matrices, meta, tuple(manifest["sources"]), manifest)
|
|
395
|
+
_check_structure(pack)
|
|
396
|
+
if any(manifest.get(key) != value for key, value in _pack_dimensions(pack).items()):
|
|
397
|
+
raise PackError("Pack manifest dates or dimensions do not match daily.npz")
|
|
398
|
+
return pack
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def save_pack(directory: str | Path, pack: DailyPack) -> dict:
|
|
402
|
+
"""Validate, then publish a pack and return its new manifest."""
|
|
403
|
+
path = Path(directory)
|
|
404
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
405
|
+
with _pack_lock(path, write=True):
|
|
406
|
+
return _save_pack(path, pack)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _save_pack(path: Path, pack: DailyPack) -> dict:
|
|
410
|
+
_check_structure(pack)
|
|
411
|
+
_check_coverage(pack.dates, pack.matrices["close"])
|
|
412
|
+
with TemporaryDirectory(prefix=".pack-", dir=path) as tmp:
|
|
413
|
+
stage = Path(tmp)
|
|
414
|
+
np.savez_compressed(stage / "daily.npz", dates=pack.dates, codes=pack.codes, **pack.matrices)
|
|
415
|
+
pack.meta.to_csv(stage / "meta.csv.gz", index=False, compression="gzip")
|
|
416
|
+
manifest = {
|
|
417
|
+
"schema_version": _SCHEMA_VERSION,
|
|
418
|
+
"market": "cn",
|
|
419
|
+
**_pack_dimensions(pack),
|
|
420
|
+
"built_at": datetime.now(timezone.utc).isoformat(),
|
|
421
|
+
"sources": list(pack.sources),
|
|
422
|
+
"files": {name: _asset_info(stage / name) for name in _ASSETS},
|
|
423
|
+
}
|
|
424
|
+
(stage / _MANIFEST).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
425
|
+
_publish(stage, path)
|
|
426
|
+
return manifest
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def forward_adjust(pack: DailyPack, *, rtol: float = 1e-5) -> dict[str, np.ndarray]:
|
|
430
|
+
"""Return qfq matrices anchored to the last available bar of each code.
|
|
431
|
+
|
|
432
|
+
Scale each price field, including pre_close, by factors after its row.
|
|
433
|
+
Volume (shares) and amount (yuan) stay in original units, as in daily.py's
|
|
434
|
+
qfq adjustment. The returned mapping shares those two raw arrays.
|
|
435
|
+
"""
|
|
436
|
+
close = pack.matrices["close"]
|
|
437
|
+
pre_close = pack.matrices["pre_close"]
|
|
438
|
+
valid = np.isfinite(close) & (close > 0)
|
|
439
|
+
rows = np.arange(len(close), dtype=np.intp)[:, None]
|
|
440
|
+
last = np.maximum.accumulate(np.where(valid, rows, -1), axis=0)
|
|
441
|
+
previous = np.take_along_axis(close, last[:-1].clip(min=0), axis=0)
|
|
442
|
+
reference = pre_close[1:]
|
|
443
|
+
event = valid[1:] & (last[:-1] >= 0) & np.isfinite(reference) & (reference > 0)
|
|
444
|
+
event &= ~np.isclose(reference, previous, rtol=rtol, atol=0)
|
|
445
|
+
factors = np.ones(close.shape, dtype=np.float64)
|
|
446
|
+
np.divide(reference, previous, out=factors[:-1], where=event, dtype=np.float64)
|
|
447
|
+
scales = np.cumprod(factors[::-1], axis=0)[::-1]
|
|
448
|
+
return {
|
|
449
|
+
**pack.matrices,
|
|
450
|
+
**{key: (pack.matrices[key] * scales).astype(np.float32) for key in PRICE_FIELDS},
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def pack_price_paths(
|
|
455
|
+
pack: DailyPack,
|
|
456
|
+
codes: Sequence[str] | None = None,
|
|
457
|
+
*,
|
|
458
|
+
adjusted: bool = True,
|
|
459
|
+
include_raw: bool = True,
|
|
460
|
+
) -> dict[str, pd.DataFrame]:
|
|
461
|
+
"""Extract per-code OHLCV price path DataFrames from ``pack`` for evaluation.
|
|
462
|
+
|
|
463
|
+
When ``include_raw=True``, also attaches unadjusted ``raw_open``, ``raw_high``,
|
|
464
|
+
``raw_low``, ``raw_close`` and ``raw_pre_close`` (rounded to 4 decimals to
|
|
465
|
+
remove float32 storage drift) so CN price-limit checks evaluate exact raw quotes.
|
|
466
|
+
"""
|
|
467
|
+
mats = forward_adjust(pack) if adjusted else pack.matrices
|
|
468
|
+
if codes is None:
|
|
469
|
+
target_codes = [str(c) for c in pack.codes]
|
|
470
|
+
else:
|
|
471
|
+
seen: set[str] = set()
|
|
472
|
+
target_codes = []
|
|
473
|
+
for raw in codes:
|
|
474
|
+
try:
|
|
475
|
+
norm = _code(raw)
|
|
476
|
+
except PackError:
|
|
477
|
+
continue
|
|
478
|
+
if norm not in seen:
|
|
479
|
+
seen.add(norm)
|
|
480
|
+
target_codes.append(norm)
|
|
481
|
+
|
|
482
|
+
dates = pack.dates
|
|
483
|
+
out: dict[str, pd.DataFrame] = {}
|
|
484
|
+
for code in target_codes:
|
|
485
|
+
idx = int(pack.codes.searchsorted(code))
|
|
486
|
+
if idx >= len(pack.codes) or pack.codes[idx] != code:
|
|
487
|
+
continue
|
|
488
|
+
data: dict[str, Any] = {
|
|
489
|
+
"date": dates,
|
|
490
|
+
**{key: mats[key][:, idx].astype(np.float64) for key in FIELDS},
|
|
491
|
+
}
|
|
492
|
+
if include_raw:
|
|
493
|
+
for key in PRICE_FIELDS:
|
|
494
|
+
data[f"raw_{key}"] = np.round(pack.matrices[key][:, idx].astype(np.float64), 4)
|
|
495
|
+
frame = pd.DataFrame(data)
|
|
496
|
+
valid = frame["close"].notna() & (frame["close"] > 0)
|
|
497
|
+
frame = frame.loc[valid].reset_index(drop=True)
|
|
498
|
+
if not frame.empty:
|
|
499
|
+
frame.attrs["daily_source"] = "daily_pack"
|
|
500
|
+
out[code] = frame
|
|
501
|
+
return out
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def stitch_snapshot(pack: DailyPack, snapshot: pd.DataFrame, trade_date: str | date | None = None) -> DailyPack:
|
|
505
|
+
"""Return an in-memory pack with a provisional snapshot row appended.
|
|
506
|
+
|
|
507
|
+
Requires code, open, high, low, close (or price), pre_close, volume in
|
|
508
|
+
shares, and amount in yuan. Snapshots from sina, efinance, akshare_em and
|
|
509
|
+
em_datacenter carry these under their own column names and are mapped
|
|
510
|
+
automatically; tushare snapshots do not. SnapshotStitchError gives a
|
|
511
|
+
degradation note.
|
|
512
|
+
"""
|
|
513
|
+
day = _iso_date(trade_date or datetime.now(_CN_TZ).date())
|
|
514
|
+
if day <= pack.trade_date:
|
|
515
|
+
return pack
|
|
516
|
+
if snapshot.attrs.get("quote_date") not in (None, day):
|
|
517
|
+
raise SnapshotStitchError("Snapshot stitch skipped: quote date does not match the requested date")
|
|
518
|
+
try:
|
|
519
|
+
bars = _normalize_day(_snapshot_bars(snapshot))
|
|
520
|
+
meta = _snapshot_meta(snapshot)
|
|
521
|
+
row = _from_day(day, bars, meta, _snapshot_source(snapshot))
|
|
522
|
+
return _append(pack, row, meta)
|
|
523
|
+
except PackError as exc:
|
|
524
|
+
raise SnapshotStitchError(f"Snapshot stitch skipped: {exc}") from None
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def pull(directory: str | Path | None = None, *, repo: str | None = None, tag: str = DEFAULT_TAG) -> dict:
|
|
528
|
+
"""Fetch the manifest and publish verified GitHub assets if hashes changed."""
|
|
529
|
+
path = Path(directory) if directory is not None else pack_dir()
|
|
530
|
+
repo = (repo or os.getenv("ALPHASIFT_PACK_REPO", "") or DEFAULT_REPO).strip()
|
|
531
|
+
if not repo:
|
|
532
|
+
raise PackError(
|
|
533
|
+
"CN daily pack is private and not publicly distributed; build locally with "
|
|
534
|
+
"'alphasift pack build' / 'python scripts/build_pack.py backfill' or set ALPHASIFT_PACK_REPO"
|
|
535
|
+
)
|
|
536
|
+
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo) or not re.fullmatch(r"[A-Za-z0-9_.-]+", tag):
|
|
537
|
+
raise PackError("Invalid GitHub pack repository or release tag")
|
|
538
|
+
base = f"https://github.com/{repo}/releases/download/{tag}"
|
|
539
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
540
|
+
with _pack_lock(path, write=True), TemporaryDirectory(prefix=".pack-", dir=path) as tmp:
|
|
541
|
+
stage = Path(tmp)
|
|
542
|
+
_download(base, stage / _MANIFEST)
|
|
543
|
+
remote = _read_manifest(stage)
|
|
544
|
+
try:
|
|
545
|
+
local = _read_manifest(path)
|
|
546
|
+
if all(local["files"][key]["sha256"] == remote["files"][key]["sha256"] for key in _ASSETS):
|
|
547
|
+
for key in _ASSETS:
|
|
548
|
+
_verify_asset(path / key, local["files"][key])
|
|
549
|
+
return local
|
|
550
|
+
except (FileNotFoundError, PackError):
|
|
551
|
+
pass
|
|
552
|
+
for key in _ASSETS:
|
|
553
|
+
_download(base, stage / key)
|
|
554
|
+
_load_pack(stage)
|
|
555
|
+
_publish(stage, path)
|
|
556
|
+
return remote
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def pull_with_wait(
|
|
560
|
+
directory: str | Path | None = None,
|
|
561
|
+
*,
|
|
562
|
+
repo: str | None = None,
|
|
563
|
+
tag: str = DEFAULT_TAG,
|
|
564
|
+
expected_trade_date: str | date | None = None,
|
|
565
|
+
max_wait_sec: float = 0.0,
|
|
566
|
+
poll_interval_sec: float = 30.0,
|
|
567
|
+
sleep_fn=time.sleep,
|
|
568
|
+
) -> dict:
|
|
569
|
+
"""Pull a private ``data-cn`` release pack when ``ALPHASIFT_PACK_REPO`` is configured, optionally polling until ``expected_trade_date`` arrives."""
|
|
570
|
+
target = _iso_date(expected_trade_date) if expected_trade_date is not None else expected_trade_date_str()
|
|
571
|
+
budget = max(0.0, float(max_wait_sec))
|
|
572
|
+
interval = max(0.1, float(poll_interval_sec))
|
|
573
|
+
waited = 0.0
|
|
574
|
+
attempts = 0
|
|
575
|
+
last_manifest: dict | None = None
|
|
576
|
+
last_error: Exception | None = None
|
|
577
|
+
|
|
578
|
+
while True:
|
|
579
|
+
attempts += 1
|
|
580
|
+
try:
|
|
581
|
+
manifest = pull(directory, repo=repo, tag=tag)
|
|
582
|
+
last_manifest = manifest
|
|
583
|
+
if target is None or str(manifest.get("trade_date", "")) >= target:
|
|
584
|
+
return {
|
|
585
|
+
**manifest,
|
|
586
|
+
"expected_trade_date": target,
|
|
587
|
+
"fresh": True if target is None else str(manifest.get("trade_date", "")) >= target,
|
|
588
|
+
"attempts": attempts,
|
|
589
|
+
"waited_sec": round(waited, 2),
|
|
590
|
+
}
|
|
591
|
+
except (OSError, PackError) as exc:
|
|
592
|
+
last_error = exc
|
|
593
|
+
|
|
594
|
+
if waited >= budget:
|
|
595
|
+
if last_manifest is not None:
|
|
596
|
+
return {
|
|
597
|
+
**last_manifest,
|
|
598
|
+
"expected_trade_date": target,
|
|
599
|
+
"fresh": False if target is not None else True,
|
|
600
|
+
"attempts": attempts,
|
|
601
|
+
"waited_sec": round(waited, 2),
|
|
602
|
+
}
|
|
603
|
+
if last_error is not None:
|
|
604
|
+
raise last_error
|
|
605
|
+
raise PackError("Pack pull failed without manifest")
|
|
606
|
+
|
|
607
|
+
step = min(interval, budget - waited)
|
|
608
|
+
if step > 0:
|
|
609
|
+
sleep_fn(step)
|
|
610
|
+
waited += step
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def expected_trade_date_str() -> str:
|
|
614
|
+
return expected_trade_date()
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _download(base: str, dst: Path) -> None:
|
|
618
|
+
token = (os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN") or "").strip()
|
|
619
|
+
kwargs: dict[str, Any] = {"headers": {"Authorization": f"Bearer {token}"}} if token else {}
|
|
620
|
+
try:
|
|
621
|
+
with requests.get(f"{base}/{dst.name}", stream=True, timeout=(10, 60), **kwargs) as response:
|
|
622
|
+
response.raise_for_status()
|
|
623
|
+
with dst.open("wb") as out:
|
|
624
|
+
for chunk in response.iter_content(chunk_size=1024 * 1024):
|
|
625
|
+
out.write(chunk)
|
|
626
|
+
except requests.RequestException:
|
|
627
|
+
raise PackError(f"GitHub pack download failed for {dst.name}") from None
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _read_manifest(path: Path) -> dict:
|
|
631
|
+
try:
|
|
632
|
+
manifest = json.loads((path / _MANIFEST).read_text(encoding="utf-8"))
|
|
633
|
+
except ValueError:
|
|
634
|
+
raise PackError("Invalid pack manifest JSON") from None
|
|
635
|
+
if not isinstance(manifest, dict) or manifest.get("market") != "cn" or manifest.get("schema_version") != _SCHEMA_VERSION:
|
|
636
|
+
raise PackError("Unsupported CN pack manifest schema")
|
|
637
|
+
files, sources = manifest.get("files"), manifest.get("sources")
|
|
638
|
+
if not isinstance(files, dict) or not isinstance(sources, list) or not all(isinstance(x, str) for x in sources):
|
|
639
|
+
raise PackError("Pack manifest is missing valid files or sources")
|
|
640
|
+
first, last = _iso_date(manifest.get("first_date")), _iso_date(manifest.get("trade_date"))
|
|
641
|
+
if first > last or any(type(manifest.get(key)) is not int or manifest[key] < 1 for key in ("n_dates", "n_codes")):
|
|
642
|
+
raise PackError("Pack manifest is missing valid dates or dimensions")
|
|
643
|
+
for key in _ASSETS:
|
|
644
|
+
asset = files.get(key)
|
|
645
|
+
if (not isinstance(asset, dict) or type(asset.get("size")) is not int or asset["size"] < 0
|
|
646
|
+
or not isinstance(asset.get("sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", asset["sha256"])):
|
|
647
|
+
raise PackError(f"Invalid pack manifest asset entry for {key}")
|
|
648
|
+
return manifest
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _asset_info(path: Path) -> dict:
|
|
652
|
+
digest = hashlib.sha256()
|
|
653
|
+
with path.open("rb") as src:
|
|
654
|
+
for chunk in iter(lambda: src.read(1024 * 1024), b""):
|
|
655
|
+
digest.update(chunk)
|
|
656
|
+
return {"sha256": digest.hexdigest(), "size": path.stat().st_size}
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _verify_asset(path: Path, expected: dict) -> None:
|
|
660
|
+
actual = _asset_info(path)
|
|
661
|
+
if actual["sha256"] != expected["sha256"]:
|
|
662
|
+
raise PackError(f"Pack SHA-256 mismatch for {path.name}")
|
|
663
|
+
if actual["size"] != expected["size"]:
|
|
664
|
+
raise PackError(f"Pack size mismatch for {path.name}")
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
@contextmanager
|
|
668
|
+
def _pack_lock(path: Path, *, write: bool = False) -> Iterator[None]:
|
|
669
|
+
if os.name != "posix":
|
|
670
|
+
with _PACK_THREAD_LOCK:
|
|
671
|
+
yield
|
|
672
|
+
return
|
|
673
|
+
import fcntl
|
|
674
|
+
|
|
675
|
+
fd = os.open(path, os.O_RDONLY)
|
|
676
|
+
try:
|
|
677
|
+
fcntl.flock(fd, fcntl.LOCK_EX if write else fcntl.LOCK_SH)
|
|
678
|
+
yield
|
|
679
|
+
finally:
|
|
680
|
+
os.close(fd)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _publish(stage: Path, path: Path) -> None:
|
|
684
|
+
# Publish the manifest last and restore the previous files if a rename fails.
|
|
685
|
+
names = (*_ASSETS, _MANIFEST)
|
|
686
|
+
for name in names:
|
|
687
|
+
if (path / name).exists():
|
|
688
|
+
os.link(path / name, stage / (name + ".prev"))
|
|
689
|
+
replaced = []
|
|
690
|
+
try:
|
|
691
|
+
for name in names:
|
|
692
|
+
(stage / name).replace(path / name)
|
|
693
|
+
replaced.append(name)
|
|
694
|
+
except (OSError, KeyboardInterrupt):
|
|
695
|
+
for name in reversed(replaced):
|
|
696
|
+
backup = stage / (name + ".prev")
|
|
697
|
+
if backup.exists():
|
|
698
|
+
backup.replace(path / name)
|
|
699
|
+
else:
|
|
700
|
+
(path / name).unlink()
|
|
701
|
+
raise
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def _pack_dimensions(pack: DailyPack) -> dict:
|
|
705
|
+
return {"first_date": str(pack.dates[0]), "trade_date": pack.trade_date,
|
|
706
|
+
"n_dates": len(pack.dates), "n_codes": len(pack.codes)}
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _check_structure(pack: DailyPack) -> None:
|
|
710
|
+
if pack.dates.ndim != 1 or pack.dates.dtype.kind != "U" or not len(pack.dates):
|
|
711
|
+
raise PackError("Pack dates must be a nonempty ISO date vector")
|
|
712
|
+
_check_dates(pack.dates)
|
|
713
|
+
if (pack.codes.ndim != 1 or pack.codes.dtype.kind != "U" or not len(pack.codes)
|
|
714
|
+
or not all(re.fullmatch(r"[0-9]{6}", code) for code in pack.codes)
|
|
715
|
+
or np.any(pack.codes[1:] <= pack.codes[:-1])):
|
|
716
|
+
raise PackError("Pack codes must be six digits, unique and sorted")
|
|
717
|
+
shape = (len(pack.dates), len(pack.codes))
|
|
718
|
+
if set(pack.matrices) != set(FIELDS) or any(
|
|
719
|
+
arr.shape != shape or arr.dtype != np.float32 for arr in pack.matrices.values()
|
|
720
|
+
):
|
|
721
|
+
raise PackError("Pack fields must all be float32 date-by-code matrices")
|
|
722
|
+
if ("code" not in pack.meta or pack.meta["code"].duplicated().any()
|
|
723
|
+
or set(pack.meta["code"]) != set(pack.codes)):
|
|
724
|
+
raise PackError("Pack metadata must include one row per code")
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _check_dates(dates: Sequence[str] | np.ndarray) -> None:
|
|
728
|
+
for value in dates:
|
|
729
|
+
_iso_date(value)
|
|
730
|
+
if any(right <= left for left, right in zip(dates, dates[1:])):
|
|
731
|
+
raise PackError("Pack dates must be strictly increasing with no duplicates")
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
class _CoverageError(PackError):
|
|
735
|
+
def __init__(self, dates: Sequence[str] | np.ndarray, counts: np.ndarray, bad: np.ndarray, previous: int):
|
|
736
|
+
self.bad = bad
|
|
737
|
+
index = int(np.flatnonzero(bad)[0])
|
|
738
|
+
prior = counts[index - 1] if index else previous
|
|
739
|
+
comparison = f", previous day {prior}" if prior else ""
|
|
740
|
+
super().__init__(f"Truncated daily bar coverage on {dates[index]} ({counts[index]} bars{comparison})")
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _check_coverage(dates: Sequence[str] | np.ndarray, close: np.ndarray, *, previous: int = 0) -> None:
|
|
744
|
+
counts = np.count_nonzero(np.isfinite(close), axis=1)
|
|
745
|
+
bad = (counts == 0) | (counts < np.r_[previous, counts[:-1]] * _MIN_COVERAGE)
|
|
746
|
+
if bad.any():
|
|
747
|
+
raise _CoverageError(dates, counts, bad, previous)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _iso_date(value: object) -> str:
|
|
751
|
+
try:
|
|
752
|
+
text = str(value)
|
|
753
|
+
if date.fromisoformat(text).isoformat() == text:
|
|
754
|
+
return text
|
|
755
|
+
except ValueError:
|
|
756
|
+
pass
|
|
757
|
+
raise PackError("Expected a trade date in YYYY-MM-DD format")
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _code(value: object) -> str:
|
|
761
|
+
match = _CODE_PATTERN.fullmatch(str(value).strip())
|
|
762
|
+
if not match:
|
|
763
|
+
raise PackError("Invalid CN stock code")
|
|
764
|
+
return match[1].zfill(6)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def _normalize_day(frame: pd.DataFrame) -> pd.DataFrame:
|
|
768
|
+
columns = ["code", *FIELDS]
|
|
769
|
+
missing = sorted(set(columns) - set(frame.columns))
|
|
770
|
+
if missing:
|
|
771
|
+
raise PackError(f"Missing required bar columns: {', '.join(missing)}")
|
|
772
|
+
bars = frame[columns].copy()
|
|
773
|
+
bars["code"] = bars["code"].map(_code)
|
|
774
|
+
if bars["code"].duplicated().any():
|
|
775
|
+
raise PackError("Duplicate code in daily bars")
|
|
776
|
+
bars[list(FIELDS)] = _numeric_bars(bars)
|
|
777
|
+
return bars.dropna(subset=["close"])
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def _numeric_bars(frame: pd.DataFrame) -> pd.DataFrame:
|
|
781
|
+
values = frame[list(FIELDS)].apply(pd.to_numeric, errors="coerce").astype(np.float32)
|
|
782
|
+
values = values.loc[~values.isna().all(axis=1)]
|
|
783
|
+
# Amount may be unknown: the free daily K-line sources do not report it.
|
|
784
|
+
if (not np.isfinite(values.drop(columns="amount").to_numpy()).all() or np.isinf(values["amount"]).any()
|
|
785
|
+
or (values[list(PRICE_FIELDS[:4])] <= 0).any().any()
|
|
786
|
+
or (values[["pre_close", "volume", "amount"]] < 0).any().any()):
|
|
787
|
+
raise PackError("Daily bar has missing or invalid numeric fields")
|
|
788
|
+
return values
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _snapshot_meta(snapshot: pd.DataFrame) -> pd.DataFrame:
|
|
792
|
+
meta = snapshot[["code", *(key for key in META_FIELDS if key in snapshot)]].copy()
|
|
793
|
+
meta["code"] = meta["code"].map(_code)
|
|
794
|
+
if "is_st" in meta:
|
|
795
|
+
flag = meta["is_st"].astype("string").str.strip().str.lower()
|
|
796
|
+
meta["is_st"] = flag.map({"true": True, "false": False, "1": True, "0": False}).astype("boolean")
|
|
797
|
+
elif "name" in meta:
|
|
798
|
+
meta["is_st"] = meta["name"].astype("string").str.strip().str.contains(r"^S?\*?ST", case=False)
|
|
799
|
+
return meta.drop_duplicates("code").set_index("code")
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _snapshot_source(snapshot: pd.DataFrame) -> str:
|
|
803
|
+
return f"snapshot:{snapshot.attrs.get('snapshot_source', 'provided')}"
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def _empty_matrices(n_dates: int, n_codes: int) -> dict[str, np.ndarray]:
|
|
807
|
+
return {key: np.full((n_dates, n_codes), np.nan, dtype=np.float32) for key in FIELDS}
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def _from_day(day: str, bars: pd.DataFrame, meta: pd.DataFrame, source: str) -> DailyPack:
|
|
811
|
+
ordered = bars.sort_values("code")
|
|
812
|
+
codes = ordered["code"].to_numpy(dtype="U6")
|
|
813
|
+
matrices = {key: ordered[key].to_numpy(dtype=np.float32)[None, :] for key in FIELDS}
|
|
814
|
+
return DailyPack(np.array([day]), codes, matrices, meta.reindex(codes).reset_index(), (source,))
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def _append(pack: DailyPack, newer: DailyPack, meta: pd.DataFrame, *, days: int | None = None) -> DailyPack:
|
|
818
|
+
dates = np.concatenate([pack.dates, newer.dates])
|
|
819
|
+
_check_dates(dates)
|
|
820
|
+
codes = np.union1d(pack.codes, newer.codes)
|
|
821
|
+
matrices = _empty_matrices(len(dates), len(codes))
|
|
822
|
+
left, right = codes.searchsorted(pack.codes), codes.searchsorted(newer.codes)
|
|
823
|
+
for key, values in matrices.items():
|
|
824
|
+
values[:len(pack.dates), left] = pack.matrices[key]
|
|
825
|
+
values[len(pack.dates):, right] = newer.matrices[key]
|
|
826
|
+
_check_coverage(dates, matrices["close"])
|
|
827
|
+
if days is not None:
|
|
828
|
+
dates = dates[-days:]
|
|
829
|
+
matrices = {key: values[-days:] for key, values in matrices.items()}
|
|
830
|
+
keep = np.isfinite(matrices["close"]).any(axis=0) | np.isin(codes, meta.index)
|
|
831
|
+
codes = codes[keep]
|
|
832
|
+
matrices = {key: values[:, keep] for key, values in matrices.items()}
|
|
833
|
+
meta = meta.reindex(codes).reset_index()
|
|
834
|
+
sources = tuple(dict.fromkeys((*pack.sources, *newer.sources)))
|
|
835
|
+
return DailyPack(dates, codes, matrices, meta, sources)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
@contextmanager
|
|
839
|
+
def _baostock_session() -> Iterator:
|
|
840
|
+
import baostock as bs
|
|
841
|
+
|
|
842
|
+
# The SDK has one process-global socket, shared with the existing daily path.
|
|
843
|
+
with _BAOSTOCK_LOCK:
|
|
844
|
+
prev_timeout = socket.getdefaulttimeout()
|
|
845
|
+
socket.setdefaulttimeout(15.0)
|
|
846
|
+
try:
|
|
847
|
+
login = bs.login()
|
|
848
|
+
_check_baostock(login)
|
|
849
|
+
try:
|
|
850
|
+
yield bs
|
|
851
|
+
finally:
|
|
852
|
+
try:
|
|
853
|
+
bs.logout()
|
|
854
|
+
except Exception:
|
|
855
|
+
logger.warning("Baostock logout failed")
|
|
856
|
+
finally:
|
|
857
|
+
socket.setdefaulttimeout(prev_timeout)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def _baostock_reachable() -> bool:
|
|
861
|
+
if os.getenv("GITHUB_ACTIONS", "").strip().lower() == "true":
|
|
862
|
+
return False
|
|
863
|
+
try:
|
|
864
|
+
import baostock.common.contants as constants
|
|
865
|
+
|
|
866
|
+
with socket.create_connection((constants.BAOSTOCK_SERVER_IP, constants.BAOSTOCK_SERVER_PORT), timeout=5):
|
|
867
|
+
return True
|
|
868
|
+
except Exception:
|
|
869
|
+
return False
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
@contextmanager
|
|
873
|
+
def _history_session(source: str = "auto") -> Iterator[tuple[object | None, str]]:
|
|
874
|
+
"""Yield ``(baostock_session_or_none, mode)`` where mode is baostock, yfinance or daily."""
|
|
875
|
+
if source not in ("auto", "baostock", "yfinance", "daily"):
|
|
876
|
+
raise PackError("history source must be auto, baostock, yfinance or daily")
|
|
877
|
+
if source == "daily":
|
|
878
|
+
logger.info("Using daily (sina+tencent) history source")
|
|
879
|
+
yield None, "daily"
|
|
880
|
+
return
|
|
881
|
+
if source == "yfinance":
|
|
882
|
+
logger.info("Using yfinance history source")
|
|
883
|
+
yield None, "yfinance"
|
|
884
|
+
return
|
|
885
|
+
if source == "auto" and not _baostock_reachable():
|
|
886
|
+
logger.info("Using batched yfinance daily history (baostock skipped or unreachable)")
|
|
887
|
+
yield None, "yfinance"
|
|
888
|
+
return
|
|
889
|
+
logger.info("Using baostock history source")
|
|
890
|
+
with _baostock_session() as bs:
|
|
891
|
+
yield bs, "baostock"
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _source_frame(code: str, count: int, source: str) -> pd.DataFrame:
|
|
895
|
+
frame = fetch_daily_history(code, lookback_days=count, source=source, cache_write=False)
|
|
896
|
+
frame = frame.assign(date=pd.to_datetime(frame["date"]).dt.strftime("%Y-%m-%d"))
|
|
897
|
+
return frame.drop_duplicates("date").set_index("date").sort_index()
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def _is_bse_code(code: str) -> bool:
|
|
901
|
+
return _code(code).startswith(("4", "8", "920"))
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def _to_yahoo_cn_symbol(code: str) -> str | None:
|
|
905
|
+
normalized = _code(code)
|
|
906
|
+
if _is_bse_code(normalized):
|
|
907
|
+
return None
|
|
908
|
+
if normalized.startswith(("6", "9", "5")):
|
|
909
|
+
return f"{normalized}.SS"
|
|
910
|
+
if normalized.startswith(("0", "3")):
|
|
911
|
+
return f"{normalized}.SZ"
|
|
912
|
+
return None
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def _yf_download(
|
|
916
|
+
tickers: str | list[str],
|
|
917
|
+
*,
|
|
918
|
+
start: str,
|
|
919
|
+
end: str,
|
|
920
|
+
actions: bool = True,
|
|
921
|
+
) -> pd.DataFrame:
|
|
922
|
+
import yfinance as yf
|
|
923
|
+
|
|
924
|
+
return yf.download(
|
|
925
|
+
tickers,
|
|
926
|
+
start=start,
|
|
927
|
+
end=end,
|
|
928
|
+
interval="1d",
|
|
929
|
+
auto_adjust=False,
|
|
930
|
+
actions=actions,
|
|
931
|
+
group_by="ticker",
|
|
932
|
+
progress=False,
|
|
933
|
+
threads=True,
|
|
934
|
+
)
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _extract_yf_frame(raw: pd.DataFrame, symbol: str, *, single: bool) -> pd.DataFrame:
|
|
938
|
+
if raw is None or raw.empty:
|
|
939
|
+
return pd.DataFrame()
|
|
940
|
+
if isinstance(raw.columns, pd.MultiIndex):
|
|
941
|
+
if symbol not in raw.columns.get_level_values(0):
|
|
942
|
+
return pd.DataFrame()
|
|
943
|
+
return raw[symbol].copy()
|
|
944
|
+
return raw.copy() if single else pd.DataFrame()
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _session_dates(bs, start: str, end: str, *, mode: str = "daily") -> list[str]:
|
|
948
|
+
if bs is not None:
|
|
949
|
+
return _baostock_dates(bs, start, end)
|
|
950
|
+
days: set[str] = set()
|
|
951
|
+
if mode == "yfinance":
|
|
952
|
+
end_pad = (date.fromisoformat(end) + timedelta(days=3)).isoformat()
|
|
953
|
+
symbols = [sym for code in _REFERENCE_CODES if (sym := _to_yahoo_cn_symbol(code)) is not None]
|
|
954
|
+
try:
|
|
955
|
+
raw = _yf_download(symbols, start=start, end=end_pad, actions=False)
|
|
956
|
+
for sym in symbols:
|
|
957
|
+
sub = _extract_yf_frame(raw, sym, single=len(symbols) == 1)
|
|
958
|
+
if sub.empty or "Close" not in sub.columns:
|
|
959
|
+
continue
|
|
960
|
+
valid = sub.dropna(subset=["Close"])
|
|
961
|
+
if not valid.empty:
|
|
962
|
+
idx = pd.to_datetime(valid.index, errors="coerce")
|
|
963
|
+
days.update(idx[~idx.isna()].strftime("%Y-%m-%d").tolist())
|
|
964
|
+
except Exception as exc:
|
|
965
|
+
logger.warning("Yahoo trading calendar reference failed: %s", exc)
|
|
966
|
+
if not days:
|
|
967
|
+
count = max((datetime.now(_CN_TZ).date() - date.fromisoformat(start)).days + 20, 30)
|
|
968
|
+
for code in _REFERENCE_CODES:
|
|
969
|
+
try:
|
|
970
|
+
days.update(_source_frame(code, count, "sina").index)
|
|
971
|
+
except Exception as exc:
|
|
972
|
+
logger.warning("Trading calendar reference %s failed: %s", code, exc)
|
|
973
|
+
dates = sorted(day for day in days if start <= day <= end)
|
|
974
|
+
if not dates and not days:
|
|
975
|
+
raise PackError("No daily source returned a trading calendar")
|
|
976
|
+
return dates
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
def _yfinance_bars_from_frame(frame: pd.DataFrame, dates: list[str]) -> pd.DataFrame:
|
|
980
|
+
"""Convert a yfinance auto_adjust=False, actions=True DataFrame to unadjusted pack bars."""
|
|
981
|
+
if frame is None or frame.empty:
|
|
982
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
983
|
+
required_ohlcv = ("Open", "High", "Low", "Close", "Volume")
|
|
984
|
+
if any(col not in frame.columns for col in required_ohlcv):
|
|
985
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
986
|
+
|
|
987
|
+
sub = frame.copy()
|
|
988
|
+
idx = pd.to_datetime(sub.index, errors="coerce")
|
|
989
|
+
sub = sub.loc[~idx.isna()].copy()
|
|
990
|
+
if sub.empty:
|
|
991
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
992
|
+
sub.index = idx[~idx.isna()].strftime("%Y-%m-%d")
|
|
993
|
+
sub = sub[~sub.index.duplicated(keep="last")].sort_index()
|
|
994
|
+
sub = sub.loc[sub.index <= dates[-1]]
|
|
995
|
+
if sub.empty:
|
|
996
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
997
|
+
|
|
998
|
+
for col in (*required_ohlcv, "Adj Close", "Dividends", "Stock Splits"):
|
|
999
|
+
if col in sub.columns:
|
|
1000
|
+
sub[col] = pd.to_numeric(sub[col], errors="coerce")
|
|
1001
|
+
|
|
1002
|
+
valid_close = np.isfinite(sub["Close"]) & sub["Close"].gt(0)
|
|
1003
|
+
sub = sub.loc[valid_close].copy()
|
|
1004
|
+
if sub.empty:
|
|
1005
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
1006
|
+
|
|
1007
|
+
splits = sub["Stock Splits"].fillna(0.0) if "Stock Splits" in sub.columns else pd.Series(0.0, index=sub.index)
|
|
1008
|
+
factors = splits.where(splits > 0, 1.0).to_numpy(dtype=np.float64)
|
|
1009
|
+
cum_split = np.cumprod(factors[::-1])[::-1]
|
|
1010
|
+
future_split = np.ones_like(cum_split)
|
|
1011
|
+
if len(cum_split) > 1:
|
|
1012
|
+
future_split[:-1] = cum_split[1:]
|
|
1013
|
+
sub["_cum_split"] = future_split
|
|
1014
|
+
|
|
1015
|
+
traded = (
|
|
1016
|
+
np.isfinite(sub["Open"]) & sub["Open"].gt(0)
|
|
1017
|
+
& np.isfinite(sub["High"]) & sub["High"].gt(0)
|
|
1018
|
+
& np.isfinite(sub["Low"]) & sub["Low"].gt(0)
|
|
1019
|
+
& np.isfinite(sub["Close"]) & sub["Close"].gt(0)
|
|
1020
|
+
& np.isfinite(sub["Volume"]) & sub["Volume"].gt(0)
|
|
1021
|
+
)
|
|
1022
|
+
sub = sub.loc[traded].copy()
|
|
1023
|
+
if sub.empty:
|
|
1024
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
1025
|
+
|
|
1026
|
+
mult = sub["_cum_split"].to_numpy(dtype=np.float64)
|
|
1027
|
+
raw_open = np.round(sub["Open"].to_numpy(dtype=np.float64) * mult, 4)
|
|
1028
|
+
raw_high = np.round(sub["High"].to_numpy(dtype=np.float64) * mult, 4)
|
|
1029
|
+
raw_low = np.round(sub["Low"].to_numpy(dtype=np.float64) * mult, 4)
|
|
1030
|
+
raw_close = np.round(sub["Close"].to_numpy(dtype=np.float64) * mult, 4)
|
|
1031
|
+
raw_vol = sub["Volume"].to_numpy(dtype=np.float64) / mult
|
|
1032
|
+
|
|
1033
|
+
pre_close = np.empty(len(sub), dtype=np.float64)
|
|
1034
|
+
pre_close[0] = raw_open[0]
|
|
1035
|
+
if len(sub) > 1:
|
|
1036
|
+
pre_close[1:] = raw_close[:-1]
|
|
1037
|
+
|
|
1038
|
+
divs = sub["Dividends"].fillna(0.0).to_numpy(dtype=np.float64) if "Dividends" in sub.columns else np.zeros(len(sub))
|
|
1039
|
+
s_vals = (
|
|
1040
|
+
sub["Stock Splits"].fillna(0.0).to_numpy(dtype=np.float64)
|
|
1041
|
+
if "Stock Splits" in sub.columns
|
|
1042
|
+
else np.zeros(len(sub))
|
|
1043
|
+
)
|
|
1044
|
+
adj_close = (
|
|
1045
|
+
sub["Adj Close"].to_numpy(dtype=np.float64)
|
|
1046
|
+
if "Adj Close" in sub.columns
|
|
1047
|
+
else np.full(len(sub), np.nan)
|
|
1048
|
+
)
|
|
1049
|
+
for i in range(1, len(sub)):
|
|
1050
|
+
if divs[i] > 0 or s_vals[i] > 0:
|
|
1051
|
+
p_adj, c_adj = adj_close[i - 1], adj_close[i]
|
|
1052
|
+
if np.isfinite(p_adj) and np.isfinite(c_adj) and p_adj > 0 and c_adj > 0:
|
|
1053
|
+
derived = round(float(raw_close[i] * (p_adj / c_adj)), 2)
|
|
1054
|
+
if derived > 0:
|
|
1055
|
+
pre_close[i] = derived
|
|
1056
|
+
|
|
1057
|
+
out = pd.DataFrame({
|
|
1058
|
+
"date": sub.index.to_numpy(dtype=str),
|
|
1059
|
+
"open": raw_open,
|
|
1060
|
+
"high": raw_high,
|
|
1061
|
+
"low": raw_low,
|
|
1062
|
+
"close": raw_close,
|
|
1063
|
+
"pre_close": pre_close,
|
|
1064
|
+
"volume": raw_vol,
|
|
1065
|
+
"amount": np.nan,
|
|
1066
|
+
})
|
|
1067
|
+
out = out.loc[out["date"].isin(set(dates))].copy()
|
|
1068
|
+
if out.empty:
|
|
1069
|
+
return pd.DataFrame(columns=["date", *FIELDS])
|
|
1070
|
+
values = _numeric_bars(out)
|
|
1071
|
+
values.insert(0, "date", out.loc[values.index, "date"].tolist())
|
|
1072
|
+
return values.reset_index(drop=True)
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def _daily_source_history(code: str, dates: list[str]) -> pd.DataFrame:
|
|
1076
|
+
"""Unadjusted bars from Sina, with the previous close rebuilt from Tencent's qfq series.
|
|
1077
|
+
|
|
1078
|
+
The qfq/raw ratio changes only on an ex-rights date, where the reference
|
|
1079
|
+
price is the prior close scaled by that change. Both series are rounded to
|
|
1080
|
+
cents, so a change inside the rounding noise is treated as no event: a
|
|
1081
|
+
very small dividend on a low-priced stock is missed. Amount is unknown.
|
|
1082
|
+
"""
|
|
1083
|
+
count = (datetime.now(_CN_TZ).date() - date.fromisoformat(dates[0])).days + 10
|
|
1084
|
+
raw = _source_frame(code, count, "sina")
|
|
1085
|
+
known = raw.index.isin(dates)
|
|
1086
|
+
if _is_bse_code(code):
|
|
1087
|
+
pre_close = raw["close"].shift().fillna(raw["open"])
|
|
1088
|
+
else:
|
|
1089
|
+
adjusted = _source_frame(code, count, "tencent")["close"].reindex(raw.index)
|
|
1090
|
+
if adjusted[known].isna().any():
|
|
1091
|
+
raise PackError(f"Adjusted history does not cover the raw bars for {code}")
|
|
1092
|
+
close = raw["close"]
|
|
1093
|
+
factor = adjusted / close
|
|
1094
|
+
previous = close.shift()
|
|
1095
|
+
ratio = factor.shift() / factor
|
|
1096
|
+
noise = np.maximum(0.002, 0.012 / adjusted.clip(lower=0.01))
|
|
1097
|
+
pre_close = previous.where(~((ratio - 1).abs() > noise), (previous * ratio).round(2))
|
|
1098
|
+
bars = raw.assign(pre_close=pre_close.fillna(raw["open"]), amount=np.nan)
|
|
1099
|
+
bars = bars.loc[known & raw["volume"].gt(0)]
|
|
1100
|
+
values = _numeric_bars(bars)
|
|
1101
|
+
values.insert(0, "date", values.index)
|
|
1102
|
+
return values.reset_index(drop=True)
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def _check_baostock(result) -> None:
|
|
1106
|
+
if result.error_code != "0":
|
|
1107
|
+
raise PackError(f"Baostock error {result.error_code}: {result.error_msg}")
|
|
1108
|
+
|
|
1109
|
+
|
|
1110
|
+
def _baostock_rows(result) -> Iterator[list[str]]:
|
|
1111
|
+
_check_baostock(result)
|
|
1112
|
+
while result.next():
|
|
1113
|
+
yield result.get_row_data()
|
|
1114
|
+
_check_baostock(result)
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
def _baostock_dates(bs, start: str, end: str) -> list[str]:
|
|
1118
|
+
dates = [day for day, is_open in _baostock_rows(bs.query_trade_dates(start_date=start, end_date=end)) if is_open == "1"]
|
|
1119
|
+
_check_dates(dates)
|
|
1120
|
+
if dates and (dates[0] < start or dates[-1] > end):
|
|
1121
|
+
raise PackError("Baostock returned trading dates outside the requested range")
|
|
1122
|
+
return dates
|
|
1123
|
+
|
|
1124
|
+
|
|
1125
|
+
def _baostock_universe(bs, first: str, last: str) -> set[str]:
|
|
1126
|
+
result = bs.query_stock_basic()
|
|
1127
|
+
_check_baostock(result)
|
|
1128
|
+
cols = [result.fields.index(key) for key in ("code", "ipoDate", "outDate", "type")]
|
|
1129
|
+
codes = set()
|
|
1130
|
+
for row in _baostock_rows(result):
|
|
1131
|
+
symbol, listed, delisted, kind = (row[i] for i in cols)
|
|
1132
|
+
if kind == "1" and (not listed or listed <= last) and (not delisted or delisted >= first):
|
|
1133
|
+
code = _code(symbol)
|
|
1134
|
+
if code.startswith(_A_SHARE):
|
|
1135
|
+
codes.add(code)
|
|
1136
|
+
return codes
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _baostock_symbol(code: str) -> str:
|
|
1140
|
+
if code.startswith(("4", "8", "920")):
|
|
1141
|
+
return f"bj.{code}"
|
|
1142
|
+
return _to_baostock_code(code)
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
def _baostock_history(bs, code: str, first: str, last: str) -> pd.DataFrame:
|
|
1146
|
+
result = bs.query_history_k_data_plus(
|
|
1147
|
+
_baostock_symbol(code), ",".join(_BAOSTOCK_FIELDS),
|
|
1148
|
+
start_date=first, end_date=last, frequency="d", adjustflag="3",
|
|
1149
|
+
)
|
|
1150
|
+
rows = _baostock_rows(result)
|
|
1151
|
+
raw = pd.DataFrame.from_records(rows, columns=list(_BAOSTOCK_FIELDS)).rename(columns={"preclose": "pre_close"})
|
|
1152
|
+
_check_dates(raw["date"].tolist())
|
|
1153
|
+
raw = raw.loc[raw["tradestatus"] == "1"]
|
|
1154
|
+
bars = _numeric_bars(raw)
|
|
1155
|
+
bars.insert(0, "date", raw.loc[bars.index, "date"])
|
|
1156
|
+
return bars
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def _write_history_cache(cache: Path, code: str, bars: pd.DataFrame) -> None:
|
|
1160
|
+
dst = cache / f"{code}.csv"
|
|
1161
|
+
with TemporaryDirectory(prefix=".history-", dir=cache) as tmp:
|
|
1162
|
+
staged = Path(tmp) / dst.name
|
|
1163
|
+
bars.to_csv(staged, index=False)
|
|
1164
|
+
staged.replace(dst)
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def _resume_history(bs, cache: Path, code: str, dates: list[str]) -> pd.DataFrame:
|
|
1168
|
+
dst = cache / f"{code}.csv"
|
|
1169
|
+
if dst.exists():
|
|
1170
|
+
return pd.read_csv(dst, dtype={"date": str, **dict.fromkeys(FIELDS, np.float32)})
|
|
1171
|
+
bars = _baostock_history(bs, code, dates[0], dates[-1]) if bs is not None else _daily_source_history(code, dates)
|
|
1172
|
+
_history_positions(bars, dates)
|
|
1173
|
+
_write_history_cache(cache, code, bars)
|
|
1174
|
+
return bars
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def _history_positions(bars: pd.DataFrame, dates: list[str]) -> np.ndarray:
|
|
1178
|
+
days = bars["date"].to_numpy(dtype=str)
|
|
1179
|
+
positions = np.searchsorted(dates, days)
|
|
1180
|
+
if (positions >= len(dates)).any() or not np.array_equal(np.asarray(dates)[positions], days):
|
|
1181
|
+
raise PackError("Baostock history has bars outside the requested trading sessions")
|
|
1182
|
+
return positions
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _backfill_yfinance(
|
|
1186
|
+
cache: Path,
|
|
1187
|
+
dates: list[str],
|
|
1188
|
+
codes: list[str],
|
|
1189
|
+
*,
|
|
1190
|
+
batch_size: int = _YFINANCE_BATCH_SIZE,
|
|
1191
|
+
) -> tuple[dict[int, pd.DataFrame], list[str]]:
|
|
1192
|
+
results: dict[int, pd.DataFrame] = {}
|
|
1193
|
+
yf_failed: list[str] = []
|
|
1194
|
+
bse_failed: list[str] = []
|
|
1195
|
+
pending: list[tuple[int, str, str]] = []
|
|
1196
|
+
bse_pending: list[tuple[int, str]] = []
|
|
1197
|
+
|
|
1198
|
+
for col, code in enumerate(codes):
|
|
1199
|
+
dst = cache / f"{code}.csv"
|
|
1200
|
+
if dst.exists():
|
|
1201
|
+
results[col] = pd.read_csv(dst, dtype={"date": str, **dict.fromkeys(FIELDS, np.float32)})
|
|
1202
|
+
continue
|
|
1203
|
+
symbol = _to_yahoo_cn_symbol(code)
|
|
1204
|
+
if symbol is None:
|
|
1205
|
+
bse_pending.append((col, code))
|
|
1206
|
+
else:
|
|
1207
|
+
pending.append((col, code, symbol))
|
|
1208
|
+
|
|
1209
|
+
max_yf_failures = max(_MAX_FAILED_CODES * max(len(pending), 1), 1)
|
|
1210
|
+
start_pad = (date.fromisoformat(dates[0]) - timedelta(days=15)).isoformat()
|
|
1211
|
+
end_pad = (date.fromisoformat(dates[-1]) + timedelta(days=3)).isoformat()
|
|
1212
|
+
chunks = [pending[i:i + batch_size] for i in range(0, len(pending), batch_size)]
|
|
1213
|
+
|
|
1214
|
+
for chunk_idx, chunk in enumerate(chunks):
|
|
1215
|
+
if chunk_idx > 0 and _YFINANCE_CHUNK_DELAY_SEC > 0:
|
|
1216
|
+
time.sleep(_YFINANCE_CHUNK_DELAY_SEC)
|
|
1217
|
+
symbols = [sym for _, _, sym in chunk]
|
|
1218
|
+
raw = None
|
|
1219
|
+
last_exc: Exception | None = None
|
|
1220
|
+
for attempt in range(2):
|
|
1221
|
+
try:
|
|
1222
|
+
raw = _yf_download(symbols, start=start_pad, end=end_pad, actions=True)
|
|
1223
|
+
last_exc = None
|
|
1224
|
+
break
|
|
1225
|
+
except ValueError as exc:
|
|
1226
|
+
last_exc = exc
|
|
1227
|
+
break
|
|
1228
|
+
except Exception as exc:
|
|
1229
|
+
last_exc = exc
|
|
1230
|
+
if attempt == 0:
|
|
1231
|
+
time.sleep(2.0)
|
|
1232
|
+
if last_exc is not None:
|
|
1233
|
+
for _, code, _ in chunk:
|
|
1234
|
+
yf_failed.append(code)
|
|
1235
|
+
logger.warning("yfinance chunk download failed for %s: %s", code, last_exc)
|
|
1236
|
+
if len(yf_failed) > max_yf_failures:
|
|
1237
|
+
raise PackError(f"Daily history failed for {len(yf_failed)} codes, aborting") from None
|
|
1238
|
+
continue
|
|
1239
|
+
|
|
1240
|
+
for col, code, sym in chunk:
|
|
1241
|
+
try:
|
|
1242
|
+
sub = _extract_yf_frame(raw, sym, single=len(chunk) == 1)
|
|
1243
|
+
if sub.empty or "Close" not in sub.columns or sub["Close"].dropna().empty:
|
|
1244
|
+
raise PackError(f"yfinance returned no daily bars for {sym}")
|
|
1245
|
+
bars = _yfinance_bars_from_frame(sub, dates)
|
|
1246
|
+
_history_positions(bars, dates)
|
|
1247
|
+
_write_history_cache(cache, code, bars)
|
|
1248
|
+
results[col] = bars
|
|
1249
|
+
except Exception as exc:
|
|
1250
|
+
yf_failed.append(code)
|
|
1251
|
+
logger.warning("Daily history failed for %s: %s", code, exc)
|
|
1252
|
+
if len(yf_failed) > max_yf_failures:
|
|
1253
|
+
raise PackError(f"Daily history failed for {len(yf_failed)} codes, aborting") from None
|
|
1254
|
+
if (chunk_idx + 1) % 5 == 0 or chunk_idx + 1 == len(chunks):
|
|
1255
|
+
logger.info(
|
|
1256
|
+
"yfinance backfill chunk %d/%d: loaded=%d failed=%d",
|
|
1257
|
+
chunk_idx + 1,
|
|
1258
|
+
len(chunks),
|
|
1259
|
+
len(results),
|
|
1260
|
+
len(yf_failed),
|
|
1261
|
+
)
|
|
1262
|
+
|
|
1263
|
+
if bse_pending:
|
|
1264
|
+
def _fetch_bse(item: tuple[int, str]) -> tuple[int, str, pd.DataFrame | None, Exception | None]:
|
|
1265
|
+
col, code = item
|
|
1266
|
+
try:
|
|
1267
|
+
bars = _daily_source_history(code, dates)
|
|
1268
|
+
_history_positions(bars, dates)
|
|
1269
|
+
_write_history_cache(cache, code, bars)
|
|
1270
|
+
return col, code, bars, None
|
|
1271
|
+
except Exception as exc:
|
|
1272
|
+
return col, code, None, exc
|
|
1273
|
+
|
|
1274
|
+
bse_ok = 0
|
|
1275
|
+
with ThreadPoolExecutor(max_workers=min(6, len(bse_pending))) as executor:
|
|
1276
|
+
for col, code, bars, exc in executor.map(_fetch_bse, bse_pending):
|
|
1277
|
+
if exc is None and bars is not None:
|
|
1278
|
+
results[col] = bars
|
|
1279
|
+
bse_ok += 1
|
|
1280
|
+
else:
|
|
1281
|
+
bse_failed.append(code)
|
|
1282
|
+
logger.warning("BSE daily history failed for %s: %s", code, exc)
|
|
1283
|
+
logger.info("BSE daily-source backfill complete: ok=%d failed=%d", bse_ok, len(bse_failed))
|
|
1284
|
+
|
|
1285
|
+
return results, [*yf_failed, *bse_failed]
|
|
1286
|
+
|
|
1287
|
+
|
|
1288
|
+
def _backfill_range(
|
|
1289
|
+
bs,
|
|
1290
|
+
path: Path,
|
|
1291
|
+
dates: list[str],
|
|
1292
|
+
codes: list[str],
|
|
1293
|
+
meta: pd.DataFrame,
|
|
1294
|
+
*,
|
|
1295
|
+
previous: int = 0,
|
|
1296
|
+
mode: str | None = None,
|
|
1297
|
+
) -> DailyPack:
|
|
1298
|
+
resolved_mode = mode or ("baostock" if bs is not None else "daily")
|
|
1299
|
+
matrices = _empty_matrices(len(dates), len(codes))
|
|
1300
|
+
# Each file is a completed query for this exact date range (including empty results).
|
|
1301
|
+
cache = path / ".backfill" / f"{dates[0]}_{dates[-1]}"
|
|
1302
|
+
cache.mkdir(parents=True, exist_ok=True)
|
|
1303
|
+
failed: list[str] = []
|
|
1304
|
+
max_failures = max(_MAX_FAILED_CODES * len(codes), 1)
|
|
1305
|
+
|
|
1306
|
+
if resolved_mode == "yfinance" and bs is None:
|
|
1307
|
+
loaded, failed = _backfill_yfinance(cache, dates, codes)
|
|
1308
|
+
for col, bars in loaded.items():
|
|
1309
|
+
index = _history_positions(bars, dates)
|
|
1310
|
+
for key in FIELDS:
|
|
1311
|
+
matrices[key][index, col] = bars[key]
|
|
1312
|
+
else:
|
|
1313
|
+
for col, code in enumerate(codes):
|
|
1314
|
+
try:
|
|
1315
|
+
bars = _resume_history(bs, cache, code, dates)
|
|
1316
|
+
except Exception as exc:
|
|
1317
|
+
# One bad code must not abort a full-market build; it is retried on the next run.
|
|
1318
|
+
failed.append(code)
|
|
1319
|
+
logger.warning("Daily history failed for %s: %s", code, exc)
|
|
1320
|
+
if len(failed) > max_failures:
|
|
1321
|
+
raise PackError(f"Daily history failed for {len(failed)} codes, aborting") from None
|
|
1322
|
+
continue
|
|
1323
|
+
index = _history_positions(bars, dates)
|
|
1324
|
+
for key in FIELDS:
|
|
1325
|
+
matrices[key][index, col] = bars[key]
|
|
1326
|
+
if (col + 1) % 250 == 0 or col + 1 == len(codes):
|
|
1327
|
+
logger.info(
|
|
1328
|
+
"%s backfill progress: %d/%d codes (failed=%d)",
|
|
1329
|
+
resolved_mode,
|
|
1330
|
+
col + 1,
|
|
1331
|
+
len(codes),
|
|
1332
|
+
len(failed),
|
|
1333
|
+
)
|
|
1334
|
+
|
|
1335
|
+
close = matrices["close"]
|
|
1336
|
+
try:
|
|
1337
|
+
_check_coverage(dates, close, previous=previous)
|
|
1338
|
+
except _CoverageError as exc:
|
|
1339
|
+
# Never mark a provider's incomplete session as permanently fetched.
|
|
1340
|
+
missing = np.isnan(close[exc.bad]).any(axis=0)
|
|
1341
|
+
for code, retry in zip(codes, missing):
|
|
1342
|
+
if retry:
|
|
1343
|
+
(cache / f"{code}.csv").unlink(missing_ok=True)
|
|
1344
|
+
raise
|
|
1345
|
+
source_label = (
|
|
1346
|
+
"baostock"
|
|
1347
|
+
if resolved_mode == "baostock"
|
|
1348
|
+
else ("yfinance" if resolved_mode == "yfinance" else "sina+tencent")
|
|
1349
|
+
)
|
|
1350
|
+
return DailyPack(
|
|
1351
|
+
np.array(dates, dtype="U10"),
|
|
1352
|
+
np.array(codes, dtype="U6"),
|
|
1353
|
+
matrices,
|
|
1354
|
+
meta.reindex(codes).reset_index(),
|
|
1355
|
+
(source_label,),
|
|
1356
|
+
)
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
def _latest_snapshot(config: Config) -> pd.DataFrame:
|
|
1360
|
+
return fetch_snapshot_with_fallback(config.snapshot_source_priority, required_columns=["code"])
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def backfill(
|
|
1364
|
+
directory: str | Path | None = None, *, days: int = DEFAULT_DAYS,
|
|
1365
|
+
codes_limit: int | None = None, trade_date: str | date | None = None, config: Config | None = None,
|
|
1366
|
+
source: str = "auto",
|
|
1367
|
+
) -> dict:
|
|
1368
|
+
"""Build the last N CN sessions from resumable per-code daily history.
|
|
1369
|
+
|
|
1370
|
+
``source`` is ``baostock``, ``yfinance``, ``daily`` (Sina and Tencent
|
|
1371
|
+
daily sources) or ``auto``, which uses Baostock when reachable and batched
|
|
1372
|
+
yfinance otherwise.
|
|
1373
|
+
"""
|
|
1374
|
+
if days < 1 or (codes_limit is not None and codes_limit < 1):
|
|
1375
|
+
raise PackError("days and codes_limit must be positive")
|
|
1376
|
+
config = config or Config.from_env()
|
|
1377
|
+
path = Path(directory) if directory is not None else pack_dir(config)
|
|
1378
|
+
end = _iso_date(trade_date or expected_trade_date())
|
|
1379
|
+
start = (date.fromisoformat(end) - timedelta(days=max(2 * days, 30))).isoformat()
|
|
1380
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
1381
|
+
with _pack_lock(path, write=True):
|
|
1382
|
+
snapshot = _latest_snapshot(config)
|
|
1383
|
+
meta = _snapshot_meta(snapshot)
|
|
1384
|
+
with _history_session(source) as (bs, mode):
|
|
1385
|
+
dates = _session_dates(bs, start, end, mode=mode)[-days:]
|
|
1386
|
+
if len(dates) != days:
|
|
1387
|
+
raise PackError(f"Only {len(dates)} of {days} requested trading sessions are available")
|
|
1388
|
+
universe = _baostock_universe(bs, dates[0], dates[-1]) if bs is not None else set()
|
|
1389
|
+
codes = sorted(universe | {code for code in meta.index if code.startswith(_A_SHARE)})[:codes_limit]
|
|
1390
|
+
pack = _backfill_range(bs, path, dates, codes, meta, mode=mode)
|
|
1391
|
+
pack.sources += (_snapshot_source(snapshot),)
|
|
1392
|
+
return _save_pack(path, pack)
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
def update(
|
|
1396
|
+
directory: str | Path | None = None, *, trade_date: str | date | None = None,
|
|
1397
|
+
days: int = DEFAULT_DAYS, provider: IncrementalProvider | None = None, config: Config | None = None,
|
|
1398
|
+
source: str = "auto",
|
|
1399
|
+
) -> dict:
|
|
1400
|
+
"""Append the target session and fill earlier gaps from daily history.
|
|
1401
|
+
|
|
1402
|
+
The target session comes from ``provider``; by default TickPlus when
|
|
1403
|
+
TICKPLUS_API_KEY is set, then existing snapshot sources, then Tencent
|
|
1404
|
+
batch quotes. If none supplies it, the session is rebuilt from daily
|
|
1405
|
+
history like any gap.
|
|
1406
|
+
"""
|
|
1407
|
+
if days < 1:
|
|
1408
|
+
raise PackError("days must be positive")
|
|
1409
|
+
config = config or Config.from_env()
|
|
1410
|
+
path = Path(directory) if directory is not None else pack_dir(config)
|
|
1411
|
+
end = _iso_date(trade_date or expected_trade_date())
|
|
1412
|
+
with _pack_lock(path, write=True):
|
|
1413
|
+
pack = _load_pack(path)
|
|
1414
|
+
if end <= pack.trade_date:
|
|
1415
|
+
return pack.manifest
|
|
1416
|
+
last = date.fromisoformat(end)
|
|
1417
|
+
first = date.fromisoformat(pack.trade_date) + timedelta(days=1)
|
|
1418
|
+
while first.weekday() >= 5:
|
|
1419
|
+
first += timedelta(days=1)
|
|
1420
|
+
if first > last:
|
|
1421
|
+
return pack.manifest
|
|
1422
|
+
|
|
1423
|
+
incremental = None
|
|
1424
|
+
if provider is not None:
|
|
1425
|
+
providers = [provider]
|
|
1426
|
+
else:
|
|
1427
|
+
providers = [TickPlusProvider()] if os.getenv("TICKPLUS_API_KEY", "").strip() else []
|
|
1428
|
+
providers.append(SnapshotProvider(config))
|
|
1429
|
+
providers.append(TencentQuoteProvider(codes=sorted(pack.codes), config=config))
|
|
1430
|
+
for provider in providers if last.weekday() < 5 else []:
|
|
1431
|
+
try:
|
|
1432
|
+
incremental = _normalize_day(provider.fetch_day(end))
|
|
1433
|
+
except Exception:
|
|
1434
|
+
# Provider exception messages can include request credentials.
|
|
1435
|
+
logger.warning("%s could not supply %s, trying the next source", provider.name, end)
|
|
1436
|
+
continue
|
|
1437
|
+
if not incremental.empty:
|
|
1438
|
+
break
|
|
1439
|
+
incremental = None
|
|
1440
|
+
gap_end = last if incremental is None else last - timedelta(days=1)
|
|
1441
|
+
gap = None
|
|
1442
|
+
snapshot = None
|
|
1443
|
+
if first <= gap_end:
|
|
1444
|
+
with _history_session(source) as (bs, mode):
|
|
1445
|
+
dates = _session_dates(bs, first.isoformat(), gap_end.isoformat(), mode=mode)
|
|
1446
|
+
if dates:
|
|
1447
|
+
snapshot = _latest_snapshot(config)
|
|
1448
|
+
meta = _snapshot_meta(snapshot)
|
|
1449
|
+
codes = set(pack.codes) | {code for code in meta.index if code.startswith(_A_SHARE)}
|
|
1450
|
+
if bs is not None:
|
|
1451
|
+
codes |= _baostock_universe(bs, dates[0], dates[-1])
|
|
1452
|
+
if incremental is not None:
|
|
1453
|
+
codes.update(incremental["code"])
|
|
1454
|
+
previous = int(np.isfinite(pack.matrices["close"][-1]).sum())
|
|
1455
|
+
gap = _backfill_range(
|
|
1456
|
+
bs, path, dates, sorted(codes), meta,
|
|
1457
|
+
previous=previous, mode=mode,
|
|
1458
|
+
)
|
|
1459
|
+
if gap is None and incremental is None:
|
|
1460
|
+
return pack.manifest
|
|
1461
|
+
if snapshot is None:
|
|
1462
|
+
snapshot = _latest_snapshot(config)
|
|
1463
|
+
meta = _snapshot_meta(snapshot)
|
|
1464
|
+
if gap is not None:
|
|
1465
|
+
pack = _append(pack, gap, meta, days=days)
|
|
1466
|
+
if incremental is not None:
|
|
1467
|
+
row = _from_day(end, incremental, meta, provider.name)
|
|
1468
|
+
pack = _append(pack, row, meta, days=days)
|
|
1469
|
+
pack.sources = tuple(dict.fromkeys((*pack.sources, _snapshot_source(snapshot))))
|
|
1470
|
+
return _save_pack(path, pack)
|