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/daily.py
ADDED
|
@@ -0,0 +1,1256 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Lightweight daily K-line enrichment for narrowed candidate pools."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from datetime import date, datetime, timedelta, timezone
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
import pandas as pd
|
|
17
|
+
import requests
|
|
18
|
+
|
|
19
|
+
from alphasift.markets import has_foreign_yahoo_suffix
|
|
20
|
+
from alphasift.source_guard import call_with_timeout, parse_source_timeout_seconds
|
|
21
|
+
|
|
22
|
+
_DAILY_FEATURE_DEFAULTS = {
|
|
23
|
+
"daily_data_points": pd.NA,
|
|
24
|
+
"change_60d": pd.NA,
|
|
25
|
+
"ma5": pd.NA,
|
|
26
|
+
"ma20": pd.NA,
|
|
27
|
+
"ma60": pd.NA,
|
|
28
|
+
"ma_bullish": pd.NA,
|
|
29
|
+
"price_above_ma20": pd.NA,
|
|
30
|
+
"macd_status": "",
|
|
31
|
+
"rsi_status": "",
|
|
32
|
+
"rsi14": pd.NA,
|
|
33
|
+
"signal_score": pd.NA,
|
|
34
|
+
"prev_high_20d": pd.NA,
|
|
35
|
+
"range_20d_pct": pd.NA,
|
|
36
|
+
"breakout_20d_pct": pd.NA,
|
|
37
|
+
"volume_ratio_20d": pd.NA,
|
|
38
|
+
"body_pct": pd.NA,
|
|
39
|
+
"pullback_to_ma20_pct": pd.NA,
|
|
40
|
+
"consolidation_days_20d": pd.NA,
|
|
41
|
+
"volatility_20d_pct": pd.NA,
|
|
42
|
+
"max_drawdown_20d_pct": pd.NA,
|
|
43
|
+
"atr_20_pct": pd.NA,
|
|
44
|
+
"daily_quality_score": pd.NA,
|
|
45
|
+
"daily_quality_flags": "",
|
|
46
|
+
"daily_source": "",
|
|
47
|
+
}
|
|
48
|
+
_DAILY_ENRICH_MAX_WORKERS = 1
|
|
49
|
+
_DAILY_HISTORY_CACHE_VERSION = 1
|
|
50
|
+
_DAILY_HISTORY_CACHE_TTL_SECONDS = 24 * 60 * 60
|
|
51
|
+
_SOURCE_HEALTH_FAILURE_THRESHOLD = 3
|
|
52
|
+
_SOURCE_HEALTH_COOLDOWN_SECONDS = 5 * 60
|
|
53
|
+
_DAILY_CALL_TIMEOUT_SECONDS = 20.0
|
|
54
|
+
_DEFAULT_TUSHARE_HTTP_URL = "http://api.waditu.com"
|
|
55
|
+
_BAOSTOCK_LOCK = threading.Lock()
|
|
56
|
+
_BAOSTOCK_OUTAGE_ERROR: str | None = None
|
|
57
|
+
_SOURCE_HEALTH: dict[str, dict[str, object]] = {}
|
|
58
|
+
_SOURCE_HEALTH_LOCK = threading.Lock()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def enrich_daily_features(
|
|
62
|
+
df: pd.DataFrame,
|
|
63
|
+
*,
|
|
64
|
+
max_rows: int = 100,
|
|
65
|
+
lookback_days: int = 120,
|
|
66
|
+
source: str = "akshare",
|
|
67
|
+
fetch_retries: int = 2,
|
|
68
|
+
cache_dir: str | Path | None = None,
|
|
69
|
+
cache_ttl_seconds: float | None = None,
|
|
70
|
+
max_workers: int | None = None,
|
|
71
|
+
cache_min_last_date: date | None = None,
|
|
72
|
+
cache_policy: Callable[[], dict[str, object]] | None = None,
|
|
73
|
+
) -> pd.DataFrame:
|
|
74
|
+
"""Attach daily technical features to the first ``max_rows`` candidates.
|
|
75
|
+
|
|
76
|
+
This intentionally runs after broad snapshot filtering; it is not a full
|
|
77
|
+
market historical-data pass.
|
|
78
|
+
"""
|
|
79
|
+
if df.empty or max_rows <= 0:
|
|
80
|
+
return df.copy()
|
|
81
|
+
|
|
82
|
+
result = df.copy()
|
|
83
|
+
daily_errors: list[str] = []
|
|
84
|
+
daily_source_counts: dict[str, int] = {}
|
|
85
|
+
daily_quality_flag_counts: dict[str, int] = {}
|
|
86
|
+
daily_source_order_notes: list[str] = []
|
|
87
|
+
daily_source_health: dict[str, object] = {}
|
|
88
|
+
success_count = 0
|
|
89
|
+
selected_index = list(result.index[:max_rows])
|
|
90
|
+
fetch_requests: list[tuple[object, str]] = []
|
|
91
|
+
for idx in selected_index:
|
|
92
|
+
raw_code = str(result.at[idx, "code"] if "code" in result.columns else "").strip()
|
|
93
|
+
if not raw_code:
|
|
94
|
+
continue
|
|
95
|
+
code = raw_code.zfill(6) if raw_code.isdigit() else raw_code
|
|
96
|
+
fetch_requests.append((idx, code))
|
|
97
|
+
|
|
98
|
+
def fetch_one(request: tuple[object, str]) -> tuple[object, dict[str, object], str | None, dict[str, object]]:
|
|
99
|
+
idx, code = request
|
|
100
|
+
try:
|
|
101
|
+
hist = fetch_daily_history(
|
|
102
|
+
code,
|
|
103
|
+
lookback_days=lookback_days,
|
|
104
|
+
source=source,
|
|
105
|
+
retries=fetch_retries,
|
|
106
|
+
**(
|
|
107
|
+
# Re-evaluated per fetch: a batch can run across the open.
|
|
108
|
+
cache_policy()
|
|
109
|
+
if cache_policy is not None
|
|
110
|
+
else {
|
|
111
|
+
"cache_dir": cache_dir,
|
|
112
|
+
"cache_ttl_seconds": cache_ttl_seconds,
|
|
113
|
+
"cache_min_last_date": cache_min_last_date,
|
|
114
|
+
}
|
|
115
|
+
),
|
|
116
|
+
)
|
|
117
|
+
features = compute_daily_features(hist)
|
|
118
|
+
features["daily_source"] = str(hist.attrs.get("daily_source", ""))
|
|
119
|
+
metadata = {
|
|
120
|
+
"daily_source": features["daily_source"],
|
|
121
|
+
"daily_quality_flags": features.get("daily_quality_flags", ""),
|
|
122
|
+
"daily_source_order_notes": list(hist.attrs.get("daily_source_order_notes", []) or []),
|
|
123
|
+
"daily_source_health": dict(hist.attrs.get("daily_source_health", {}) or {}),
|
|
124
|
+
}
|
|
125
|
+
return idx, features, None, metadata
|
|
126
|
+
except Exception as exc:
|
|
127
|
+
features = dict(_DAILY_FEATURE_DEFAULTS)
|
|
128
|
+
features["daily_quality_score"] = 0.0
|
|
129
|
+
features["daily_quality_flags"] = "fetch_failed"
|
|
130
|
+
return idx, features, f"{code}: {exc}", {"daily_quality_flags": "fetch_failed"}
|
|
131
|
+
|
|
132
|
+
if len(fetch_requests) <= 1:
|
|
133
|
+
fetched_rows = [fetch_one(request) for request in fetch_requests]
|
|
134
|
+
else:
|
|
135
|
+
worker_limit = min(_normalize_max_workers(max_workers), len(fetch_requests))
|
|
136
|
+
with ThreadPoolExecutor(max_workers=worker_limit) as executor:
|
|
137
|
+
fetched_rows = list(executor.map(fetch_one, fetch_requests))
|
|
138
|
+
|
|
139
|
+
for idx, features, error, metadata in fetched_rows:
|
|
140
|
+
for flag in str(metadata.get("daily_quality_flags") or "").split(";"):
|
|
141
|
+
if flag:
|
|
142
|
+
daily_quality_flag_counts[flag] = daily_quality_flag_counts.get(flag, 0) + 1
|
|
143
|
+
if error:
|
|
144
|
+
daily_errors.append(error)
|
|
145
|
+
else:
|
|
146
|
+
success_count += 1
|
|
147
|
+
source_name = str(metadata.get("daily_source") or "unknown")
|
|
148
|
+
daily_source_counts[source_name] = daily_source_counts.get(source_name, 0) + 1
|
|
149
|
+
order_notes = metadata.get("daily_source_order_notes", [])
|
|
150
|
+
if not isinstance(order_notes, list):
|
|
151
|
+
order_notes = []
|
|
152
|
+
for note in order_notes:
|
|
153
|
+
note_text = str(note)
|
|
154
|
+
if note_text and note_text not in daily_source_order_notes:
|
|
155
|
+
daily_source_order_notes.append(note_text)
|
|
156
|
+
source_health = metadata.get("daily_source_health")
|
|
157
|
+
if isinstance(source_health, dict):
|
|
158
|
+
daily_source_health.update(source_health)
|
|
159
|
+
for key, value in features.items():
|
|
160
|
+
result.loc[idx, key] = value # .at cannot add columns in pandas 4
|
|
161
|
+
|
|
162
|
+
result.attrs["daily_errors"] = daily_errors
|
|
163
|
+
result.attrs["daily_success_count"] = success_count
|
|
164
|
+
result.attrs["daily_source_counts"] = daily_source_counts
|
|
165
|
+
result.attrs["daily_quality_flag_counts"] = daily_quality_flag_counts
|
|
166
|
+
result.attrs["daily_source_order_notes"] = daily_source_order_notes
|
|
167
|
+
result.attrs["daily_source_health"] = daily_source_health
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def fetch_daily_history(
|
|
172
|
+
code: str,
|
|
173
|
+
*,
|
|
174
|
+
lookback_days: int = 120,
|
|
175
|
+
source: str = "akshare",
|
|
176
|
+
retries: int = 2,
|
|
177
|
+
cache_dir: str | Path | None = None,
|
|
178
|
+
cache_ttl_seconds: float | None = None,
|
|
179
|
+
cache_min_last_date: date | None = None,
|
|
180
|
+
cache_write: bool = True,
|
|
181
|
+
) -> pd.DataFrame:
|
|
182
|
+
"""Fetch daily history for one stock code.
|
|
183
|
+
|
|
184
|
+
``cache_min_last_date`` rejects a fresh cache entry whose last bar is
|
|
185
|
+
older than that session (e.g. fetched before the vendor published it).
|
|
186
|
+
``cache_write=False`` still allows the flagged stale fallback when every
|
|
187
|
+
source fails, but never stores the result (e.g. a partial-day bar).
|
|
188
|
+
|
|
189
|
+
``source`` accepts ``tencent``, ``sina``, ``akshare``, ``baostock``, ``tushare``,
|
|
190
|
+
``yfinance`` or ``auto``. ``auto`` prefers Tushare when a token is
|
|
191
|
+
configured, then Tencent's direct HTTP K-line endpoint before wrapper-based
|
|
192
|
+
free sources. Without a token it starts with Tencent. Sina is a second
|
|
193
|
+
direct HTTP K-line source before wrapper-based fallbacks. ``yfinance`` is
|
|
194
|
+
explicit-only (never part of ``auto``) and expects a US ticker rather than
|
|
195
|
+
an A-share code.
|
|
196
|
+
"""
|
|
197
|
+
normalized_code = _normalize_daily_code(code)
|
|
198
|
+
normalized_lookback_days = int(lookback_days)
|
|
199
|
+
src = _normalize_daily_source(source)
|
|
200
|
+
if src == "auto":
|
|
201
|
+
sources: tuple[str, ...] = (
|
|
202
|
+
("tushare", "tencent", "sina", "akshare", "baostock")
|
|
203
|
+
if _has_tushare_token()
|
|
204
|
+
else ("tencent", "sina", "akshare", "baostock")
|
|
205
|
+
)
|
|
206
|
+
sources, source_order_notes = _rank_daily_sources_by_health(sources)
|
|
207
|
+
elif src in ("akshare", "baostock", "tushare", "tencent", "sina", "yfinance"):
|
|
208
|
+
sources = (src,)
|
|
209
|
+
source_order_notes = []
|
|
210
|
+
else:
|
|
211
|
+
raise ValueError(f"Unsupported daily source: {source}")
|
|
212
|
+
|
|
213
|
+
cache_path = None
|
|
214
|
+
if cache_dir is not None:
|
|
215
|
+
cache_path = _daily_history_cache_path(
|
|
216
|
+
cache_dir,
|
|
217
|
+
code=normalized_code,
|
|
218
|
+
source=src,
|
|
219
|
+
lookback_days=normalized_lookback_days,
|
|
220
|
+
)
|
|
221
|
+
cached = _read_daily_history_cache(cache_path, ttl_seconds=cache_ttl_seconds)
|
|
222
|
+
if cached is not None and _history_reaches(cached, cache_min_last_date):
|
|
223
|
+
return cached
|
|
224
|
+
|
|
225
|
+
attempts = max(int(retries), 0) + 1
|
|
226
|
+
errors: list[str] = []
|
|
227
|
+
for current in sources:
|
|
228
|
+
disabled_reason = _source_disabled_reason(current)
|
|
229
|
+
if disabled_reason:
|
|
230
|
+
errors.append(f"{current}: {disabled_reason}")
|
|
231
|
+
continue
|
|
232
|
+
last_error: Exception | None = None
|
|
233
|
+
for attempt in range(attempts):
|
|
234
|
+
try:
|
|
235
|
+
if current == "yfinance":
|
|
236
|
+
from alphasift.snapshot_us import fetch_daily_history_yfinance
|
|
237
|
+
result = _call_daily_wrapper(
|
|
238
|
+
fetch_daily_history_yfinance,
|
|
239
|
+
current,
|
|
240
|
+
code,
|
|
241
|
+
lookback_days=lookback_days,
|
|
242
|
+
)
|
|
243
|
+
elif current == "tencent":
|
|
244
|
+
result = _fetch_daily_tencent(
|
|
245
|
+
normalized_code,
|
|
246
|
+
lookback_days=normalized_lookback_days,
|
|
247
|
+
)
|
|
248
|
+
elif current == "sina":
|
|
249
|
+
result = _fetch_daily_sina(
|
|
250
|
+
normalized_code,
|
|
251
|
+
lookback_days=normalized_lookback_days,
|
|
252
|
+
)
|
|
253
|
+
elif current == "akshare":
|
|
254
|
+
result = _call_daily_wrapper(
|
|
255
|
+
_fetch_daily_akshare,
|
|
256
|
+
current,
|
|
257
|
+
normalized_code,
|
|
258
|
+
lookback_days=normalized_lookback_days,
|
|
259
|
+
)
|
|
260
|
+
elif current == "tushare":
|
|
261
|
+
result = _call_daily_wrapper(
|
|
262
|
+
_fetch_daily_tushare,
|
|
263
|
+
current,
|
|
264
|
+
normalized_code,
|
|
265
|
+
lookback_days=normalized_lookback_days,
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
result = _call_daily_wrapper(
|
|
269
|
+
_fetch_daily_baostock,
|
|
270
|
+
current,
|
|
271
|
+
normalized_code,
|
|
272
|
+
lookback_days=normalized_lookback_days,
|
|
273
|
+
)
|
|
274
|
+
_record_source_success(current, rows=len(result))
|
|
275
|
+
result.attrs["daily_source"] = current
|
|
276
|
+
result.attrs["daily_requested_source"] = src
|
|
277
|
+
result.attrs["daily_source_order"] = list(sources)
|
|
278
|
+
result.attrs["daily_source_order_notes"] = list(source_order_notes)
|
|
279
|
+
result.attrs["source_errors"] = list(errors)
|
|
280
|
+
result.attrs["daily_source_health"] = _daily_source_health_snapshot(sources)
|
|
281
|
+
# When the bars were captured: evaluation must not treat a
|
|
282
|
+
# mid-session bar as that session's close.
|
|
283
|
+
result.attrs["fetched_at"] = datetime.now(timezone.utc).isoformat()
|
|
284
|
+
if cache_path is not None and cache_write:
|
|
285
|
+
_write_daily_history_cache(
|
|
286
|
+
cache_path,
|
|
287
|
+
result,
|
|
288
|
+
code=normalized_code,
|
|
289
|
+
source=src,
|
|
290
|
+
lookback_days=normalized_lookback_days,
|
|
291
|
+
)
|
|
292
|
+
return result
|
|
293
|
+
except Exception as exc: # noqa: BLE001 - aggregated below
|
|
294
|
+
last_error = exc
|
|
295
|
+
if attempt >= attempts - 1:
|
|
296
|
+
break
|
|
297
|
+
time.sleep(min(0.5 * (attempt + 1), 2.0))
|
|
298
|
+
errors.append(f"{current} after {attempts} attempts: {last_error}")
|
|
299
|
+
_record_source_failure(current, last_error)
|
|
300
|
+
|
|
301
|
+
if cache_path is not None:
|
|
302
|
+
stale = _read_daily_history_cache(
|
|
303
|
+
cache_path,
|
|
304
|
+
ttl_seconds=cache_ttl_seconds,
|
|
305
|
+
allow_stale=True,
|
|
306
|
+
)
|
|
307
|
+
if stale is not None:
|
|
308
|
+
stale.attrs["daily_stale"] = True
|
|
309
|
+
stale.attrs["daily_source_order"] = list(sources)
|
|
310
|
+
stale.attrs["daily_source_order_notes"] = list(source_order_notes)
|
|
311
|
+
stale.attrs["source_errors"] = list(errors)
|
|
312
|
+
stale.attrs["daily_source_health"] = _daily_source_health_snapshot(sources)
|
|
313
|
+
return stale
|
|
314
|
+
|
|
315
|
+
raise RuntimeError(
|
|
316
|
+
f"daily history fetch failed for {normalized_code}: {'; '.join(errors)}"
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _normalize_daily_code(value: object) -> str:
|
|
321
|
+
text = "" if value is None else str(value).strip()
|
|
322
|
+
if not text or text.lower() in {"nan", "none", "<na>"}:
|
|
323
|
+
return ""
|
|
324
|
+
if text.endswith(".0") and text[:-2].isdigit():
|
|
325
|
+
text = text[:-2]
|
|
326
|
+
if text.isdigit():
|
|
327
|
+
return text.zfill(6)[-6:]
|
|
328
|
+
if has_foreign_yahoo_suffix(text):
|
|
329
|
+
return text.upper()
|
|
330
|
+
digits = "".join(ch for ch in text if ch.isdigit())
|
|
331
|
+
return digits.zfill(6)[-6:] if digits else text
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _normalize_daily_source(source: str | None) -> str:
|
|
335
|
+
return (source or "akshare").strip().lower()
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _normalize_max_workers(value: int | None) -> int:
|
|
339
|
+
if value is None:
|
|
340
|
+
return _DAILY_ENRICH_MAX_WORKERS
|
|
341
|
+
return max(1, int(value))
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _call_daily_wrapper(fetcher, source: str, *args, **kwargs) -> pd.DataFrame:
|
|
345
|
+
return call_with_timeout(
|
|
346
|
+
fetcher,
|
|
347
|
+
*args,
|
|
348
|
+
timeout_sec=_daily_call_timeout_seconds(),
|
|
349
|
+
label=f"daily source {source}",
|
|
350
|
+
**kwargs,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _daily_call_timeout_seconds() -> float | None:
|
|
355
|
+
return parse_source_timeout_seconds(
|
|
356
|
+
"ALPHASIFT_DAILY_CALL_TIMEOUT_SEC",
|
|
357
|
+
default=_DAILY_CALL_TIMEOUT_SECONDS,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _rank_daily_sources_by_health(sources: tuple[str, ...]) -> tuple[tuple[str, ...], list[str]]:
|
|
362
|
+
"""Move unhealthy daily sources later while preserving default order ties."""
|
|
363
|
+
now = time.monotonic()
|
|
364
|
+
with _SOURCE_HEALTH_LOCK:
|
|
365
|
+
health = {source: dict(_SOURCE_HEALTH.get(source, {})) for source in sources}
|
|
366
|
+
default_rank = {source: idx for idx, source in enumerate(sources)}
|
|
367
|
+
|
|
368
|
+
def rank_key(source: str) -> tuple[int, float, int]:
|
|
369
|
+
state = health.get(source, {})
|
|
370
|
+
disabled_until = float(state.get("disabled_until", 0.0))
|
|
371
|
+
disabled = disabled_until > now
|
|
372
|
+
failures = float(state.get("failures", 0.0))
|
|
373
|
+
return (1 if disabled else 0, failures, default_rank[source])
|
|
374
|
+
|
|
375
|
+
ranked = tuple(sorted(sources, key=rank_key))
|
|
376
|
+
if ranked == sources:
|
|
377
|
+
return sources, []
|
|
378
|
+
return ranked, [f"daily source order adjusted by health: {','.join(ranked)}"]
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _source_disabled_reason(source: str) -> str | None:
|
|
382
|
+
now = time.monotonic()
|
|
383
|
+
with _SOURCE_HEALTH_LOCK:
|
|
384
|
+
state = _SOURCE_HEALTH.get(source)
|
|
385
|
+
if not state:
|
|
386
|
+
return None
|
|
387
|
+
disabled_until = float(state.get("disabled_until", 0.0))
|
|
388
|
+
if disabled_until <= now:
|
|
389
|
+
if disabled_until:
|
|
390
|
+
state["disabled_until"] = 0.0
|
|
391
|
+
return None
|
|
392
|
+
return f"temporarily disabled for {disabled_until - now:.1f}s after repeated failures"
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _record_source_success(source: str, *, rows: int | None = None) -> None:
|
|
396
|
+
with _SOURCE_HEALTH_LOCK:
|
|
397
|
+
state = _SOURCE_HEALTH.setdefault(source, {"failures": 0.0, "disabled_until": 0.0})
|
|
398
|
+
successes = float(state.get("successes", 0.0)) + 1.0
|
|
399
|
+
state["successes"] = successes
|
|
400
|
+
state["failures"] = 0.0
|
|
401
|
+
state["disabled_until"] = 0.0
|
|
402
|
+
state["last_success_at"] = time.time()
|
|
403
|
+
if rows is not None:
|
|
404
|
+
state["last_rows"] = float(rows)
|
|
405
|
+
previous_avg = float(state.get("avg_rows", rows))
|
|
406
|
+
state["avg_rows"] = previous_avg + (float(rows) - previous_avg) / successes
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _record_source_failure(source: str, error: object | None = None) -> None:
|
|
410
|
+
now = time.monotonic()
|
|
411
|
+
with _SOURCE_HEALTH_LOCK:
|
|
412
|
+
state = _SOURCE_HEALTH.setdefault(source, {"failures": 0.0, "disabled_until": 0.0})
|
|
413
|
+
failures = float(state.get("failures", 0.0)) + 1.0
|
|
414
|
+
state["failures"] = failures
|
|
415
|
+
state["total_failures"] = float(state.get("total_failures", 0.0)) + 1.0
|
|
416
|
+
state["last_failure_at"] = time.time()
|
|
417
|
+
if error is not None:
|
|
418
|
+
state["last_error"] = " ".join(str(error).split())
|
|
419
|
+
if failures >= _SOURCE_HEALTH_FAILURE_THRESHOLD:
|
|
420
|
+
state["disabled_until"] = now + _SOURCE_HEALTH_COOLDOWN_SECONDS
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def daily_source_health_snapshot() -> dict[str, dict[str, float | bool | str]]:
|
|
424
|
+
"""Return a copy of in-process daily-source health statistics."""
|
|
425
|
+
return _daily_source_health_snapshot(tuple(_SOURCE_HEALTH))
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _daily_source_health_snapshot(sources: tuple[str, ...]) -> dict[str, dict[str, float | bool | str]]:
|
|
429
|
+
now = time.monotonic()
|
|
430
|
+
snapshot: dict[str, dict[str, float | bool | str]] = {}
|
|
431
|
+
with _SOURCE_HEALTH_LOCK:
|
|
432
|
+
for source in sources:
|
|
433
|
+
state = dict(_SOURCE_HEALTH.get(source, {}))
|
|
434
|
+
disabled_until = float(state.get("disabled_until", 0.0))
|
|
435
|
+
cooldown_remaining = max(disabled_until - now, 0.0)
|
|
436
|
+
snapshot[source] = {
|
|
437
|
+
"successes": float(state.get("successes", 0.0)),
|
|
438
|
+
"failures": float(state.get("failures", 0.0)),
|
|
439
|
+
"total_failures": float(state.get("total_failures", 0.0)),
|
|
440
|
+
"last_rows": float(state.get("last_rows", 0.0)),
|
|
441
|
+
"avg_rows": float(state.get("avg_rows", 0.0)),
|
|
442
|
+
"disabled": disabled_until > now,
|
|
443
|
+
"cooldown_remaining_seconds": round(cooldown_remaining, 4),
|
|
444
|
+
"last_success_at": float(state.get("last_success_at", 0.0)),
|
|
445
|
+
"last_failure_at": float(state.get("last_failure_at", 0.0)),
|
|
446
|
+
"last_error": str(state.get("last_error", "")),
|
|
447
|
+
}
|
|
448
|
+
return snapshot
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _daily_history_cache_path(
|
|
452
|
+
cache_dir: str | Path,
|
|
453
|
+
*,
|
|
454
|
+
code: str,
|
|
455
|
+
source: str,
|
|
456
|
+
lookback_days: int,
|
|
457
|
+
) -> Path:
|
|
458
|
+
key = f"{code}|{source}|{int(lookback_days)}"
|
|
459
|
+
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
|
|
460
|
+
safe_source = "".join(ch if ch.isalnum() else "-" for ch in source).strip("-") or "source"
|
|
461
|
+
safe_code = "".join(ch if ch.isalnum() else "-" for ch in code).strip("-") or "code"
|
|
462
|
+
return Path(cache_dir) / f"{safe_code}_{safe_source}_{int(lookback_days)}_{digest}.json"
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _history_reaches(df: pd.DataFrame, min_last_date: date | None) -> bool:
|
|
466
|
+
if min_last_date is None:
|
|
467
|
+
return True
|
|
468
|
+
try:
|
|
469
|
+
normalized = _normalize_daily_history(df)
|
|
470
|
+
dates = pd.to_datetime(normalized["date"], errors="coerce").dropna()
|
|
471
|
+
except Exception: # noqa: BLE001 - an unreadable cache is just a miss
|
|
472
|
+
return False
|
|
473
|
+
return not dates.empty and dates.max().date() >= min_last_date
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _read_daily_history_cache(
|
|
477
|
+
path: Path,
|
|
478
|
+
*,
|
|
479
|
+
ttl_seconds: float | None,
|
|
480
|
+
allow_stale: bool = False,
|
|
481
|
+
) -> pd.DataFrame | None:
|
|
482
|
+
try:
|
|
483
|
+
stat = path.stat()
|
|
484
|
+
except FileNotFoundError:
|
|
485
|
+
return None
|
|
486
|
+
|
|
487
|
+
ttl = _DAILY_HISTORY_CACHE_TTL_SECONDS if ttl_seconds is None else float(ttl_seconds)
|
|
488
|
+
is_stale = ttl <= 0 or time.time() - stat.st_mtime > ttl
|
|
489
|
+
if is_stale and not allow_stale:
|
|
490
|
+
return None
|
|
491
|
+
|
|
492
|
+
try:
|
|
493
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
494
|
+
if payload.get("version") != _DAILY_HISTORY_CACHE_VERSION:
|
|
495
|
+
return None
|
|
496
|
+
frame = payload.get("frame")
|
|
497
|
+
if not isinstance(frame, dict):
|
|
498
|
+
return None
|
|
499
|
+
columns = frame.get("columns")
|
|
500
|
+
data = frame.get("data")
|
|
501
|
+
if not isinstance(columns, list) or not isinstance(data, list):
|
|
502
|
+
return None
|
|
503
|
+
df = pd.DataFrame(data, columns=columns)
|
|
504
|
+
metadata = payload.get("metadata")
|
|
505
|
+
if isinstance(metadata, dict):
|
|
506
|
+
for key in ("daily_source", "daily_requested_source", "daily_source_order", "daily_source_order_notes", "source_errors", "daily_source_health"):
|
|
507
|
+
if key in metadata:
|
|
508
|
+
df.attrs[key] = metadata[key]
|
|
509
|
+
if is_stale:
|
|
510
|
+
df.attrs["daily_stale"] = True
|
|
511
|
+
df.attrs["fetched_at"] = datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
|
|
512
|
+
return df
|
|
513
|
+
except Exception:
|
|
514
|
+
return None
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _write_daily_history_cache(
|
|
518
|
+
path: Path,
|
|
519
|
+
df: pd.DataFrame,
|
|
520
|
+
*,
|
|
521
|
+
code: str,
|
|
522
|
+
source: str,
|
|
523
|
+
lookback_days: int,
|
|
524
|
+
) -> None:
|
|
525
|
+
try:
|
|
526
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
527
|
+
payload = {
|
|
528
|
+
"version": _DAILY_HISTORY_CACHE_VERSION,
|
|
529
|
+
"key": {
|
|
530
|
+
"code": code,
|
|
531
|
+
"source": source,
|
|
532
|
+
"lookback_days": int(lookback_days),
|
|
533
|
+
},
|
|
534
|
+
"metadata": {
|
|
535
|
+
"daily_source": df.attrs.get("daily_source", source),
|
|
536
|
+
"daily_requested_source": df.attrs.get("daily_requested_source", source),
|
|
537
|
+
"daily_source_order": list(df.attrs.get("daily_source_order", [])),
|
|
538
|
+
"daily_source_order_notes": list(df.attrs.get("daily_source_order_notes", [])),
|
|
539
|
+
"source_errors": list(df.attrs.get("source_errors", [])),
|
|
540
|
+
"daily_source_health": df.attrs.get("daily_source_health", {}),
|
|
541
|
+
},
|
|
542
|
+
"created_at": datetime.now().isoformat(),
|
|
543
|
+
"frame": json.loads(df.to_json(orient="split", date_format="iso", force_ascii=False)),
|
|
544
|
+
}
|
|
545
|
+
tmp_path = path.with_name(f".{path.name}.{time.time_ns()}.tmp")
|
|
546
|
+
tmp_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
|
547
|
+
tmp_path.replace(path)
|
|
548
|
+
except Exception:
|
|
549
|
+
return
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _fetch_daily_akshare(code: str, *, lookback_days: int) -> pd.DataFrame:
|
|
553
|
+
import akshare as ak
|
|
554
|
+
|
|
555
|
+
start_date = (datetime.now() - timedelta(days=max(lookback_days * 2, 90))).strftime("%Y%m%d")
|
|
556
|
+
end_date = datetime.now().strftime("%Y%m%d")
|
|
557
|
+
df = ak.stock_zh_a_hist(
|
|
558
|
+
symbol=str(code).zfill(6),
|
|
559
|
+
period="daily",
|
|
560
|
+
start_date=start_date,
|
|
561
|
+
end_date=end_date,
|
|
562
|
+
adjust="qfq",
|
|
563
|
+
)
|
|
564
|
+
if df is None or df.empty:
|
|
565
|
+
raise RuntimeError(f"akshare daily history empty for {code}")
|
|
566
|
+
return df.tail(max(lookback_days, 30)).copy()
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _fetch_daily_tencent(code: str, *, lookback_days: int) -> pd.DataFrame:
|
|
570
|
+
"""Fetch forward-adjusted daily history from Tencent's direct HTTP API.
|
|
571
|
+
|
|
572
|
+
The endpoint is the same low-friction source recommended by a-stock-data for
|
|
573
|
+
stable A-share market data access: no wrapper dependency, browser-like HTTP,
|
|
574
|
+
and much lower IP-ban risk than Eastmoney-heavy endpoints. Tencent returns
|
|
575
|
+
daily K-lines as rows shaped like ``date, open, close, high, low, volume``;
|
|
576
|
+
amount is not always present, so it is exposed as ``NA`` when absent to keep
|
|
577
|
+
the common daily schema stable.
|
|
578
|
+
"""
|
|
579
|
+
symbol = _to_tencent_code(code)
|
|
580
|
+
count = max(int(lookback_days), 30)
|
|
581
|
+
response = requests.get(
|
|
582
|
+
"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get",
|
|
583
|
+
params={"param": f"{symbol},day,,,{count},qfq"},
|
|
584
|
+
headers={"User-Agent": "Mozilla/5.0"},
|
|
585
|
+
timeout=10,
|
|
586
|
+
)
|
|
587
|
+
response.raise_for_status()
|
|
588
|
+
payload = response.json()
|
|
589
|
+
if not isinstance(payload, dict) or payload.get("code") not in (0, "0", None):
|
|
590
|
+
message = payload.get("msg") if isinstance(payload, dict) else payload
|
|
591
|
+
raise RuntimeError(f"tencent daily API error for {code}: {message}")
|
|
592
|
+
data = payload.get("data") if isinstance(payload, dict) else None
|
|
593
|
+
stock_data = data.get(symbol) if isinstance(data, dict) else None
|
|
594
|
+
if not isinstance(stock_data, dict):
|
|
595
|
+
raise RuntimeError(f"tencent daily history missing payload for {code}")
|
|
596
|
+
rows = stock_data.get("qfqday") or stock_data.get("day") or []
|
|
597
|
+
if not isinstance(rows, list) or not rows:
|
|
598
|
+
raise RuntimeError(f"tencent daily history empty for {code}")
|
|
599
|
+
|
|
600
|
+
normalized_rows: list[dict[str, object]] = []
|
|
601
|
+
for row in rows:
|
|
602
|
+
if not isinstance(row, list) or len(row) < 6:
|
|
603
|
+
continue
|
|
604
|
+
normalized_rows.append({
|
|
605
|
+
"date": row[0],
|
|
606
|
+
"open": row[1],
|
|
607
|
+
"close": row[2],
|
|
608
|
+
"high": row[3],
|
|
609
|
+
"low": row[4],
|
|
610
|
+
"volume": row[5],
|
|
611
|
+
"amount": row[6] if len(row) > 6 else pd.NA,
|
|
612
|
+
})
|
|
613
|
+
if not normalized_rows:
|
|
614
|
+
raise RuntimeError(f"tencent daily history malformed for {code}")
|
|
615
|
+
df = pd.DataFrame(
|
|
616
|
+
normalized_rows,
|
|
617
|
+
columns=["date", "open", "close", "high", "low", "volume", "amount"],
|
|
618
|
+
)
|
|
619
|
+
for col in ("open", "close", "high", "low", "volume", "amount"):
|
|
620
|
+
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
621
|
+
return df.tail(count).copy()
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _fetch_daily_sina(code: str, *, lookback_days: int) -> pd.DataFrame:
|
|
625
|
+
"""Fetch unadjusted daily history from Sina's direct K-line API.
|
|
626
|
+
|
|
627
|
+
Sina provides a lightweight non-Eastmoney HTTP fallback for A-share daily
|
|
628
|
+
bars. It does not expose forward-adjusted prices on this endpoint, so it is
|
|
629
|
+
deliberately placed behind Tencent in ``auto`` but ahead of wrapper-heavy
|
|
630
|
+
sources that are more prone to dependency/API drift.
|
|
631
|
+
"""
|
|
632
|
+
symbol = _to_tencent_code(code)
|
|
633
|
+
count = max(int(lookback_days), 30)
|
|
634
|
+
response = requests.get(
|
|
635
|
+
"https://quotes.sina.cn/cn/api/openapi.php/CN_MarketDataService.getKLineData",
|
|
636
|
+
params={"symbol": symbol, "scale": 240, "ma": "no", "datalen": count},
|
|
637
|
+
headers={"User-Agent": "Mozilla/5.0"},
|
|
638
|
+
timeout=10,
|
|
639
|
+
)
|
|
640
|
+
response.raise_for_status()
|
|
641
|
+
payload = response.json()
|
|
642
|
+
data = payload.get("result", {}).get("data") if isinstance(payload, dict) else None
|
|
643
|
+
if not isinstance(data, list) or not data:
|
|
644
|
+
raise RuntimeError(f"sina daily history empty for {code}")
|
|
645
|
+
|
|
646
|
+
rows: list[dict[str, object]] = []
|
|
647
|
+
for row in data:
|
|
648
|
+
if not isinstance(row, dict):
|
|
649
|
+
continue
|
|
650
|
+
rows.append({
|
|
651
|
+
"date": row.get("day") or row.get("date"),
|
|
652
|
+
"open": row.get("open"),
|
|
653
|
+
"close": row.get("close"),
|
|
654
|
+
"high": row.get("high"),
|
|
655
|
+
"low": row.get("low"),
|
|
656
|
+
"volume": row.get("volume"),
|
|
657
|
+
"amount": row.get("amount", pd.NA),
|
|
658
|
+
})
|
|
659
|
+
if not rows:
|
|
660
|
+
raise RuntimeError(f"sina daily history malformed for {code}")
|
|
661
|
+
|
|
662
|
+
df = pd.DataFrame(rows, columns=["date", "open", "close", "high", "low", "volume", "amount"])
|
|
663
|
+
if "date" in df.columns:
|
|
664
|
+
df = df.sort_values("date")
|
|
665
|
+
for col in ("open", "close", "high", "low", "volume", "amount"):
|
|
666
|
+
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
667
|
+
return df.tail(count).copy()
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _fetch_daily_tushare(code: str, *, lookback_days: int) -> pd.DataFrame:
|
|
671
|
+
"""Fetch forward-adjusted daily history via Tushare Pro."""
|
|
672
|
+
token = _tushare_token()
|
|
673
|
+
if not token:
|
|
674
|
+
raise RuntimeError("tushare requires TUSHARE_TOKEN")
|
|
675
|
+
|
|
676
|
+
import tushare as ts
|
|
677
|
+
|
|
678
|
+
pro = ts.pro_api(token)
|
|
679
|
+
_configure_tushare_client(pro, token=token)
|
|
680
|
+
|
|
681
|
+
start_date = (datetime.now() - timedelta(days=max(lookback_days * 2, 90))).strftime("%Y%m%d")
|
|
682
|
+
end_date = datetime.now().strftime("%Y%m%d")
|
|
683
|
+
adj = _normalize_tushare_adj(os.getenv("TUSHARE_DAILY_ADJ", "qfq"))
|
|
684
|
+
ts_code = _to_tushare_code(code)
|
|
685
|
+
df = pro.daily(
|
|
686
|
+
ts_code=ts_code,
|
|
687
|
+
start_date=start_date,
|
|
688
|
+
end_date=end_date,
|
|
689
|
+
fields="ts_code,trade_date,open,high,low,close,vol,amount",
|
|
690
|
+
)
|
|
691
|
+
if df is None or df.empty:
|
|
692
|
+
raise RuntimeError(f"tushare daily history empty for {code}")
|
|
693
|
+
if adj is not None:
|
|
694
|
+
df = _apply_tushare_adjustment(
|
|
695
|
+
df,
|
|
696
|
+
pro=pro,
|
|
697
|
+
ts_code=ts_code,
|
|
698
|
+
start_date=start_date,
|
|
699
|
+
end_date=end_date,
|
|
700
|
+
adj=adj,
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
normalized = _normalize_tushare_daily_frame(df)
|
|
704
|
+
return normalized.tail(max(lookback_days, 30)).copy()
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _tushare_token() -> str:
|
|
708
|
+
return (
|
|
709
|
+
os.getenv("TUSHARE_TOKEN", "").strip()
|
|
710
|
+
or os.getenv("TUSHARE_API_TOKEN", "").strip()
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _has_tushare_token() -> bool:
|
|
715
|
+
return bool(_tushare_token())
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _configure_tushare_client(pro: object, *, token: str) -> None:
|
|
719
|
+
try:
|
|
720
|
+
setattr(pro, "_DataApi__token", token)
|
|
721
|
+
except Exception:
|
|
722
|
+
pass
|
|
723
|
+
|
|
724
|
+
http_url = (
|
|
725
|
+
os.getenv("TUSHARE_API_URL", "").strip()
|
|
726
|
+
or os.getenv("TUSHARE_HTTP_URL", "").strip()
|
|
727
|
+
or _DEFAULT_TUSHARE_HTTP_URL
|
|
728
|
+
)
|
|
729
|
+
try:
|
|
730
|
+
setattr(pro, "_DataApi__http_url", http_url)
|
|
731
|
+
except Exception:
|
|
732
|
+
pass
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _normalize_tushare_daily_frame(df: pd.DataFrame) -> pd.DataFrame:
|
|
736
|
+
rename_map = {
|
|
737
|
+
"trade_date": "date",
|
|
738
|
+
"vol": "volume",
|
|
739
|
+
}
|
|
740
|
+
normalized = df.rename(columns=rename_map).copy()
|
|
741
|
+
if "date" in normalized.columns:
|
|
742
|
+
normalized["date"] = normalized["date"].astype(str)
|
|
743
|
+
normalized = normalized.sort_values("date")
|
|
744
|
+
return normalized
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def _apply_tushare_adjustment(
|
|
748
|
+
df: pd.DataFrame,
|
|
749
|
+
*,
|
|
750
|
+
pro: object,
|
|
751
|
+
ts_code: str,
|
|
752
|
+
start_date: str,
|
|
753
|
+
end_date: str,
|
|
754
|
+
adj: str,
|
|
755
|
+
) -> pd.DataFrame:
|
|
756
|
+
factors = pro.adj_factor(
|
|
757
|
+
ts_code=ts_code,
|
|
758
|
+
start_date=start_date,
|
|
759
|
+
end_date=end_date,
|
|
760
|
+
fields="trade_date,adj_factor",
|
|
761
|
+
)
|
|
762
|
+
if factors is None or factors.empty:
|
|
763
|
+
raise RuntimeError(f"tushare adj_factor empty for {ts_code}")
|
|
764
|
+
|
|
765
|
+
merged = df.merge(factors, on="trade_date", how="left")
|
|
766
|
+
merged = merged.sort_values("trade_date")
|
|
767
|
+
merged["adj_factor"] = pd.to_numeric(merged["adj_factor"], errors="coerce").bfill()
|
|
768
|
+
valid_factors = pd.to_numeric(factors["adj_factor"], errors="coerce").dropna()
|
|
769
|
+
if valid_factors.empty:
|
|
770
|
+
raise RuntimeError(f"tushare adj_factor invalid for {ts_code}")
|
|
771
|
+
latest_factor = float(valid_factors.iloc[0])
|
|
772
|
+
for col in ("open", "high", "low", "close"):
|
|
773
|
+
merged[col] = pd.to_numeric(merged[col], errors="coerce")
|
|
774
|
+
if adj == "hfq":
|
|
775
|
+
merged[col] = merged[col] * merged["adj_factor"]
|
|
776
|
+
else:
|
|
777
|
+
merged[col] = merged[col] * merged["adj_factor"] / latest_factor
|
|
778
|
+
return merged.drop(columns=["adj_factor"])
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _normalize_tushare_adj(value: str | None) -> str | None:
|
|
782
|
+
text = (value or "").strip().lower()
|
|
783
|
+
if text in {"", "none", "null", "no", "false", "0"}:
|
|
784
|
+
return None
|
|
785
|
+
if text not in {"qfq", "hfq"}:
|
|
786
|
+
raise RuntimeError(f"unsupported TUSHARE_DAILY_ADJ: {value}")
|
|
787
|
+
return text
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def _fetch_daily_baostock(code: str, *, lookback_days: int) -> pd.DataFrame:
|
|
791
|
+
"""Fetch daily history via Baostock as a free fallback source.
|
|
792
|
+
|
|
793
|
+
Baostock uses ``sh.600519`` / ``sz.000001`` style codes and exposes
|
|
794
|
+
forward-adjusted prices via ``adjustflag='2'``.
|
|
795
|
+
"""
|
|
796
|
+
try:
|
|
797
|
+
import baostock as bs
|
|
798
|
+
except ImportError as exc:
|
|
799
|
+
raise RuntimeError("baostock not installed; pip install baostock") from exc
|
|
800
|
+
|
|
801
|
+
global _BAOSTOCK_OUTAGE_ERROR
|
|
802
|
+
if _BAOSTOCK_OUTAGE_ERROR is not None:
|
|
803
|
+
raise RuntimeError(_BAOSTOCK_OUTAGE_ERROR)
|
|
804
|
+
|
|
805
|
+
bs_code = _to_baostock_code(code)
|
|
806
|
+
start_date = (datetime.now() - timedelta(days=max(lookback_days * 2, 90))).strftime("%Y-%m-%d")
|
|
807
|
+
end_date = datetime.now().strftime("%Y-%m-%d")
|
|
808
|
+
|
|
809
|
+
with _BAOSTOCK_LOCK:
|
|
810
|
+
if _BAOSTOCK_OUTAGE_ERROR is not None:
|
|
811
|
+
raise RuntimeError(_BAOSTOCK_OUTAGE_ERROR)
|
|
812
|
+
|
|
813
|
+
login_result = bs.login()
|
|
814
|
+
try:
|
|
815
|
+
login_error_code = str(getattr(login_result, "error_code", "0"))
|
|
816
|
+
if login_error_code not in {"", "0"}:
|
|
817
|
+
login_error_msg = getattr(login_result, "error_msg", "")
|
|
818
|
+
raise RuntimeError(f"baostock login error {login_error_code}: {login_error_msg}")
|
|
819
|
+
|
|
820
|
+
rs = bs.query_history_k_data_plus(
|
|
821
|
+
bs_code,
|
|
822
|
+
"date,open,high,low,close,volume,amount",
|
|
823
|
+
start_date=start_date,
|
|
824
|
+
end_date=end_date,
|
|
825
|
+
frequency="d",
|
|
826
|
+
adjustflag="2",
|
|
827
|
+
)
|
|
828
|
+
if rs.error_code != "0":
|
|
829
|
+
message = f"baostock error {rs.error_code}: {rs.error_msg}"
|
|
830
|
+
if _is_baostock_network_outage(rs.error_code, rs.error_msg):
|
|
831
|
+
_BAOSTOCK_OUTAGE_ERROR = message
|
|
832
|
+
raise RuntimeError(message)
|
|
833
|
+
rows = []
|
|
834
|
+
while rs.next():
|
|
835
|
+
rows.append(rs.get_row_data())
|
|
836
|
+
finally:
|
|
837
|
+
try:
|
|
838
|
+
bs.logout()
|
|
839
|
+
except Exception:
|
|
840
|
+
pass
|
|
841
|
+
|
|
842
|
+
if not rows:
|
|
843
|
+
raise RuntimeError(f"baostock daily history empty for {code}")
|
|
844
|
+
|
|
845
|
+
df = pd.DataFrame(rows, columns=["date", "open", "high", "low", "close", "volume", "amount"])
|
|
846
|
+
return df.tail(max(lookback_days, 30)).copy()
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def _to_baostock_code(code: str) -> str:
|
|
850
|
+
text = str(code).strip().lower()
|
|
851
|
+
if len(text) == 8 and text[:2] in {"sh", "sz", "bj"} and text[2:].isdigit():
|
|
852
|
+
return f"{text[:2]}.{text[2:]}"
|
|
853
|
+
raw = str(code).strip().zfill(6)
|
|
854
|
+
if raw.startswith(("6", "9", "5")):
|
|
855
|
+
return f"sh.{raw}"
|
|
856
|
+
return f"sz.{raw}"
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def _to_tushare_code(code: str) -> str:
|
|
860
|
+
text = str(code).strip().lower()
|
|
861
|
+
if len(text) == 8 and text[:2] in {"sh", "sz", "bj"} and text[2:].isdigit():
|
|
862
|
+
return f"{text[2:]}.{text[:2].upper()}"
|
|
863
|
+
raw = str(code).strip().zfill(6)
|
|
864
|
+
if raw.startswith(("4", "8", "920")):
|
|
865
|
+
return f"{raw}.BJ"
|
|
866
|
+
if raw.startswith(("6", "9", "5")):
|
|
867
|
+
return f"{raw}.SH"
|
|
868
|
+
return f"{raw}.SZ"
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def _to_tencent_code(code: str) -> str:
|
|
872
|
+
text = str(code).strip().lower()
|
|
873
|
+
# Already-prefixed symbols (e.g. the sh000300 index) pass through; a bare
|
|
874
|
+
# 000300 would otherwise be routed to Shenzhen.
|
|
875
|
+
if len(text) == 8 and text[:2] in {"sh", "sz", "bj"} and text[2:].isdigit():
|
|
876
|
+
return text
|
|
877
|
+
raw = str(code).strip().zfill(6)
|
|
878
|
+
if raw.startswith(("4", "8", "920")):
|
|
879
|
+
return f"bj{raw}"
|
|
880
|
+
if raw.startswith(("6", "9", "5")):
|
|
881
|
+
return f"sh{raw}"
|
|
882
|
+
return f"sz{raw}"
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def _is_baostock_network_outage(error_code: object, error_msg: object) -> bool:
|
|
886
|
+
code = str(error_code)
|
|
887
|
+
message = str(error_msg)
|
|
888
|
+
return code in {"10002007"} or "网络" in message or "接收" in message
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def compute_daily_features(hist: pd.DataFrame) -> dict[str, object]:
|
|
892
|
+
"""Compute compact trend/reversal features from a daily K-line DataFrame."""
|
|
893
|
+
df = _normalize_daily_history(hist)
|
|
894
|
+
if df.empty:
|
|
895
|
+
raise RuntimeError("daily history is empty after normalization")
|
|
896
|
+
|
|
897
|
+
close = pd.to_numeric(df["close"], errors="coerce").dropna()
|
|
898
|
+
if close.empty:
|
|
899
|
+
raise RuntimeError("daily history has no valid close price")
|
|
900
|
+
|
|
901
|
+
ma5 = close.rolling(5).mean()
|
|
902
|
+
ma20 = close.rolling(20).mean()
|
|
903
|
+
ma60 = close.rolling(60).mean()
|
|
904
|
+
last_close = float(close.iloc[-1])
|
|
905
|
+
last_ma5 = _last_float(ma5)
|
|
906
|
+
last_ma20 = _last_float(ma20)
|
|
907
|
+
last_ma60 = _last_float(ma60)
|
|
908
|
+
shape = _compute_shape_features(df, last_close=last_close, last_ma20=last_ma20)
|
|
909
|
+
quality = _compute_daily_quality(hist, df)
|
|
910
|
+
|
|
911
|
+
lookback_idx = max(0, len(close) - 61)
|
|
912
|
+
base_close = float(close.iloc[lookback_idx])
|
|
913
|
+
change_60d = (last_close / base_close - 1.0) * 100 if base_close > 0 else None
|
|
914
|
+
|
|
915
|
+
macd_status = _compute_macd_status(close)
|
|
916
|
+
rsi_value = _compute_rsi(close)
|
|
917
|
+
rsi_status = _classify_rsi(rsi_value)
|
|
918
|
+
ma_bullish = _is_true(last_ma5 is not None and last_ma20 is not None and last_ma60 is not None
|
|
919
|
+
and last_ma5 >= last_ma20 >= last_ma60)
|
|
920
|
+
price_above_ma20 = _is_true(last_ma20 is not None and last_close >= last_ma20)
|
|
921
|
+
signal_score = _compute_signal_score(
|
|
922
|
+
change_60d=change_60d,
|
|
923
|
+
ma_bullish=ma_bullish,
|
|
924
|
+
price_above_ma20=price_above_ma20,
|
|
925
|
+
macd_status=macd_status,
|
|
926
|
+
rsi_status=rsi_status,
|
|
927
|
+
)
|
|
928
|
+
|
|
929
|
+
return {
|
|
930
|
+
"daily_data_points": int(len(close)),
|
|
931
|
+
"change_60d": None if change_60d is None else round(float(change_60d), 4),
|
|
932
|
+
"ma5": last_ma5,
|
|
933
|
+
"ma20": last_ma20,
|
|
934
|
+
"ma60": last_ma60,
|
|
935
|
+
"ma_bullish": ma_bullish,
|
|
936
|
+
"price_above_ma20": price_above_ma20,
|
|
937
|
+
"macd_status": macd_status,
|
|
938
|
+
"rsi_status": rsi_status,
|
|
939
|
+
"rsi14": None if rsi_value is None else round(float(rsi_value), 4),
|
|
940
|
+
"signal_score": round(float(signal_score), 4),
|
|
941
|
+
**shape,
|
|
942
|
+
**quality,
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _normalize_daily_history(hist: pd.DataFrame) -> pd.DataFrame:
|
|
947
|
+
rename_map = {
|
|
948
|
+
"日期": "date",
|
|
949
|
+
"收盘": "close",
|
|
950
|
+
"开盘": "open",
|
|
951
|
+
"最高": "high",
|
|
952
|
+
"最低": "low",
|
|
953
|
+
"成交量": "volume",
|
|
954
|
+
"成交额": "amount",
|
|
955
|
+
}
|
|
956
|
+
df = hist.rename(columns=rename_map).copy()
|
|
957
|
+
if "date" in df.columns:
|
|
958
|
+
df = df.sort_values("date")
|
|
959
|
+
if "close" not in df.columns:
|
|
960
|
+
raise RuntimeError("daily history has no close column")
|
|
961
|
+
for col in ("open", "high", "low", "close", "volume"):
|
|
962
|
+
if col in df.columns:
|
|
963
|
+
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
964
|
+
df = df.dropna(subset=["close"]).copy()
|
|
965
|
+
for col in ("open", "high", "low"):
|
|
966
|
+
if col not in df.columns:
|
|
967
|
+
df[col] = df["close"]
|
|
968
|
+
else:
|
|
969
|
+
df[col] = df[col].fillna(df["close"])
|
|
970
|
+
return df
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def _compute_daily_quality(raw: pd.DataFrame, normalized: pd.DataFrame) -> dict[str, object]:
|
|
974
|
+
"""Score daily-history quality and expose compact audit flags."""
|
|
975
|
+
score = 100.0
|
|
976
|
+
flags: list[str] = []
|
|
977
|
+
points = len(normalized)
|
|
978
|
+
if points < 30:
|
|
979
|
+
score -= 35
|
|
980
|
+
flags.append("short_history_lt30")
|
|
981
|
+
elif points < 60:
|
|
982
|
+
score -= 15
|
|
983
|
+
flags.append("short_history_lt60")
|
|
984
|
+
|
|
985
|
+
for col in ("open", "high", "low", "close"):
|
|
986
|
+
if col not in normalized.columns:
|
|
987
|
+
score -= 20
|
|
988
|
+
flags.append(f"missing_{col}")
|
|
989
|
+
continue
|
|
990
|
+
missing_ratio = float(pd.to_numeric(normalized[col], errors="coerce").isna().mean())
|
|
991
|
+
if missing_ratio > 0:
|
|
992
|
+
score -= min(missing_ratio * 40, 20)
|
|
993
|
+
flags.append(f"incomplete_{col}")
|
|
994
|
+
|
|
995
|
+
if "volume" not in normalized.columns:
|
|
996
|
+
score -= 12
|
|
997
|
+
flags.append("missing_volume")
|
|
998
|
+
else:
|
|
999
|
+
volume = pd.to_numeric(normalized["volume"], errors="coerce")
|
|
1000
|
+
missing_volume_ratio = float(volume.isna().mean())
|
|
1001
|
+
if missing_volume_ratio > 0:
|
|
1002
|
+
score -= min(missing_volume_ratio * 20, 10)
|
|
1003
|
+
flags.append("incomplete_volume")
|
|
1004
|
+
if (volume.dropna() < 0).any():
|
|
1005
|
+
score -= 20
|
|
1006
|
+
flags.append("negative_volume")
|
|
1007
|
+
|
|
1008
|
+
if {"open", "high", "low", "close"}.issubset(normalized.columns):
|
|
1009
|
+
open_ = pd.to_numeric(normalized["open"], errors="coerce")
|
|
1010
|
+
high = pd.to_numeric(normalized["high"], errors="coerce")
|
|
1011
|
+
low = pd.to_numeric(normalized["low"], errors="coerce")
|
|
1012
|
+
close = pd.to_numeric(normalized["close"], errors="coerce")
|
|
1013
|
+
invalid_ohlc = (high < low) | (high < open_) | (high < close) | (low > open_) | (low > close)
|
|
1014
|
+
if invalid_ohlc.fillna(False).any():
|
|
1015
|
+
score -= 30
|
|
1016
|
+
flags.append("invalid_ohlc")
|
|
1017
|
+
if ((open_ <= 0) | (high <= 0) | (low <= 0) | (close <= 0)).fillna(False).any():
|
|
1018
|
+
score -= 35
|
|
1019
|
+
flags.append("non_positive_price")
|
|
1020
|
+
|
|
1021
|
+
if bool(raw.attrs.get("daily_stale")):
|
|
1022
|
+
score -= 25
|
|
1023
|
+
flags.append("stale_cache")
|
|
1024
|
+
|
|
1025
|
+
source_errors = list(raw.attrs.get("source_errors", []) or [])
|
|
1026
|
+
if source_errors:
|
|
1027
|
+
score -= min(len(source_errors) * 5, 20)
|
|
1028
|
+
flags.append("fallback_errors")
|
|
1029
|
+
|
|
1030
|
+
return {
|
|
1031
|
+
"daily_quality_score": round(max(score, 0.0), 4),
|
|
1032
|
+
"daily_quality_flags": ";".join(flags),
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
def _compute_shape_features(
|
|
1037
|
+
df: pd.DataFrame,
|
|
1038
|
+
*,
|
|
1039
|
+
last_close: float,
|
|
1040
|
+
last_ma20: float | None,
|
|
1041
|
+
) -> dict[str, object]:
|
|
1042
|
+
previous = df.iloc[:-1].tail(20)
|
|
1043
|
+
recent = df.tail(20)
|
|
1044
|
+
last = df.iloc[-1]
|
|
1045
|
+
|
|
1046
|
+
prev_high_20d = _series_max(previous["high"]) if "high" in previous.columns else None
|
|
1047
|
+
range_20d_pct = _range_pct(recent)
|
|
1048
|
+
breakout_20d_pct = (
|
|
1049
|
+
(last_close / prev_high_20d - 1.0) * 100
|
|
1050
|
+
if prev_high_20d is not None and prev_high_20d > 0
|
|
1051
|
+
else None
|
|
1052
|
+
)
|
|
1053
|
+
volume_ratio_20d = _volume_ratio_20d(df)
|
|
1054
|
+
body_pct = _body_pct(last)
|
|
1055
|
+
pullback_to_ma20_pct = (
|
|
1056
|
+
(last_close / last_ma20 - 1.0) * 100
|
|
1057
|
+
if last_ma20 is not None and last_ma20 > 0
|
|
1058
|
+
else None
|
|
1059
|
+
)
|
|
1060
|
+
volatility_20d_pct = _volatility_20d_pct(recent["close"])
|
|
1061
|
+
max_drawdown_20d_pct = _max_drawdown_pct(recent["close"])
|
|
1062
|
+
atr_20_pct = _atr_20_pct(df)
|
|
1063
|
+
|
|
1064
|
+
return {
|
|
1065
|
+
"prev_high_20d": _round_or_none(prev_high_20d),
|
|
1066
|
+
"range_20d_pct": _round_or_none(range_20d_pct),
|
|
1067
|
+
"breakout_20d_pct": _round_or_none(breakout_20d_pct),
|
|
1068
|
+
"volume_ratio_20d": _round_or_none(volume_ratio_20d),
|
|
1069
|
+
"body_pct": _round_or_none(body_pct),
|
|
1070
|
+
"pullback_to_ma20_pct": _round_or_none(pullback_to_ma20_pct),
|
|
1071
|
+
"consolidation_days_20d": _consolidation_days(previous),
|
|
1072
|
+
"volatility_20d_pct": _round_or_none(volatility_20d_pct),
|
|
1073
|
+
"max_drawdown_20d_pct": _round_or_none(max_drawdown_20d_pct),
|
|
1074
|
+
"atr_20_pct": _round_or_none(atr_20_pct),
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def _series_max(series: pd.Series) -> float | None:
|
|
1079
|
+
values = pd.to_numeric(series, errors="coerce").dropna()
|
|
1080
|
+
if values.empty:
|
|
1081
|
+
return None
|
|
1082
|
+
return float(values.max())
|
|
1083
|
+
|
|
1084
|
+
|
|
1085
|
+
def _range_pct(df: pd.DataFrame) -> float | None:
|
|
1086
|
+
if "high" not in df.columns or "low" not in df.columns:
|
|
1087
|
+
return None
|
|
1088
|
+
high = pd.to_numeric(df["high"], errors="coerce").dropna()
|
|
1089
|
+
low = pd.to_numeric(df["low"], errors="coerce").dropna()
|
|
1090
|
+
if high.empty or low.empty:
|
|
1091
|
+
return None
|
|
1092
|
+
low_min = float(low.min())
|
|
1093
|
+
if low_min <= 0:
|
|
1094
|
+
return None
|
|
1095
|
+
return (float(high.max()) / low_min - 1.0) * 100
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _volume_ratio_20d(df: pd.DataFrame) -> float | None:
|
|
1099
|
+
if "volume" not in df.columns:
|
|
1100
|
+
return None
|
|
1101
|
+
volume = pd.to_numeric(df["volume"], errors="coerce")
|
|
1102
|
+
if len(volume) < 2 or pd.isna(volume.iloc[-1]):
|
|
1103
|
+
return None
|
|
1104
|
+
previous = volume.iloc[:-1].tail(20).dropna()
|
|
1105
|
+
if previous.empty:
|
|
1106
|
+
return None
|
|
1107
|
+
base = float(previous.mean())
|
|
1108
|
+
if base <= 0:
|
|
1109
|
+
return None
|
|
1110
|
+
return float(volume.iloc[-1]) / base
|
|
1111
|
+
|
|
1112
|
+
|
|
1113
|
+
def _volatility_20d_pct(close: pd.Series) -> float | None:
|
|
1114
|
+
values = pd.to_numeric(close, errors="coerce").dropna()
|
|
1115
|
+
returns = values.pct_change().dropna()
|
|
1116
|
+
if len(returns) < 2:
|
|
1117
|
+
return None
|
|
1118
|
+
return float(returns.std()) * (252 ** 0.5) * 100
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _max_drawdown_pct(close: pd.Series) -> float | None:
|
|
1122
|
+
values = pd.to_numeric(close, errors="coerce").dropna()
|
|
1123
|
+
if values.empty:
|
|
1124
|
+
return None
|
|
1125
|
+
running_high = values.cummax()
|
|
1126
|
+
drawdowns = values / running_high - 1.0
|
|
1127
|
+
return min(float(drawdowns.min()) * 100, 0.0)
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _atr_20_pct(df: pd.DataFrame) -> float | None:
|
|
1131
|
+
if not {"high", "low", "close"}.issubset(df.columns):
|
|
1132
|
+
return None
|
|
1133
|
+
high = pd.to_numeric(df["high"], errors="coerce")
|
|
1134
|
+
low = pd.to_numeric(df["low"], errors="coerce")
|
|
1135
|
+
close = pd.to_numeric(df["close"], errors="coerce")
|
|
1136
|
+
previous_close = close.shift(1)
|
|
1137
|
+
true_range = pd.concat([
|
|
1138
|
+
high - low,
|
|
1139
|
+
(high - previous_close).abs(),
|
|
1140
|
+
(low - previous_close).abs(),
|
|
1141
|
+
], axis=1).max(axis=1)
|
|
1142
|
+
atr = true_range.tail(20).dropna().mean()
|
|
1143
|
+
valid_close = close.dropna()
|
|
1144
|
+
if valid_close.empty:
|
|
1145
|
+
return None
|
|
1146
|
+
last_close = float(valid_close.iloc[-1])
|
|
1147
|
+
if pd.isna(atr) or last_close <= 0:
|
|
1148
|
+
return None
|
|
1149
|
+
return float(atr) / last_close * 100
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
def _consolidation_days(previous: pd.DataFrame, *, max_range_pct: float = 12.0) -> int | None:
|
|
1153
|
+
if previous.empty or "high" not in previous.columns or "low" not in previous.columns:
|
|
1154
|
+
return None
|
|
1155
|
+
for days in range(min(len(previous), 20), 1, -1):
|
|
1156
|
+
window = previous.tail(days)
|
|
1157
|
+
range_pct = _range_pct(window)
|
|
1158
|
+
if range_pct is not None and range_pct <= max_range_pct:
|
|
1159
|
+
return int(days)
|
|
1160
|
+
return 0
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def _body_pct(row: pd.Series) -> float | None:
|
|
1164
|
+
open_price = row.get("open")
|
|
1165
|
+
close_price = row.get("close")
|
|
1166
|
+
if pd.isna(open_price) or pd.isna(close_price) or float(open_price) <= 0:
|
|
1167
|
+
return None
|
|
1168
|
+
return (float(close_price) / float(open_price) - 1.0) * 100
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _round_or_none(value: float | None) -> float | None:
|
|
1172
|
+
if value is None or pd.isna(value):
|
|
1173
|
+
return None
|
|
1174
|
+
return round(float(value), 4)
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def _compute_macd_status(close: pd.Series) -> str:
|
|
1178
|
+
if len(close) < 35:
|
|
1179
|
+
return "neutral"
|
|
1180
|
+
ema12 = close.ewm(span=12, adjust=False).mean()
|
|
1181
|
+
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
1182
|
+
diff = ema12 - ema26
|
|
1183
|
+
dea = diff.ewm(span=9, adjust=False).mean()
|
|
1184
|
+
last_diff = float(diff.iloc[-1])
|
|
1185
|
+
last_dea = float(dea.iloc[-1])
|
|
1186
|
+
if last_diff > last_dea and last_diff > 0:
|
|
1187
|
+
return "bullish"
|
|
1188
|
+
if last_diff < last_dea and last_diff < 0:
|
|
1189
|
+
return "bearish"
|
|
1190
|
+
return "neutral"
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
def _compute_rsi(close: pd.Series, period: int = 14) -> float | None:
|
|
1194
|
+
if len(close) <= period:
|
|
1195
|
+
return None
|
|
1196
|
+
delta = close.diff()
|
|
1197
|
+
gain = delta.clip(lower=0).rolling(period).mean()
|
|
1198
|
+
loss = (-delta.clip(upper=0)).rolling(period).mean()
|
|
1199
|
+
rs = gain / loss.replace(0, pd.NA)
|
|
1200
|
+
rsi = 100 - (100 / (1 + rs))
|
|
1201
|
+
value = rsi.iloc[-1]
|
|
1202
|
+
if pd.isna(value):
|
|
1203
|
+
return None
|
|
1204
|
+
return float(value)
|
|
1205
|
+
|
|
1206
|
+
|
|
1207
|
+
def _classify_rsi(value: float | None) -> str:
|
|
1208
|
+
if value is None:
|
|
1209
|
+
return "neutral"
|
|
1210
|
+
if value <= 35:
|
|
1211
|
+
return "oversold"
|
|
1212
|
+
if value >= 70:
|
|
1213
|
+
return "overbought"
|
|
1214
|
+
return "neutral"
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
def _compute_signal_score(
|
|
1218
|
+
*,
|
|
1219
|
+
change_60d: float | None,
|
|
1220
|
+
ma_bullish: bool,
|
|
1221
|
+
price_above_ma20: bool,
|
|
1222
|
+
macd_status: str,
|
|
1223
|
+
rsi_status: str,
|
|
1224
|
+
) -> float:
|
|
1225
|
+
score = 50.0
|
|
1226
|
+
if ma_bullish:
|
|
1227
|
+
score += 14
|
|
1228
|
+
if price_above_ma20:
|
|
1229
|
+
score += 10
|
|
1230
|
+
if macd_status == "bullish":
|
|
1231
|
+
score += 12
|
|
1232
|
+
elif macd_status == "bearish":
|
|
1233
|
+
score -= 12
|
|
1234
|
+
if change_60d is not None:
|
|
1235
|
+
if 0 <= change_60d <= 35:
|
|
1236
|
+
score += min(change_60d * 0.35, 12)
|
|
1237
|
+
elif change_60d > 60:
|
|
1238
|
+
score -= min((change_60d - 60) * 0.20, 12)
|
|
1239
|
+
elif change_60d < -25:
|
|
1240
|
+
score -= min(abs(change_60d + 25) * 0.25, 10)
|
|
1241
|
+
if rsi_status == "oversold":
|
|
1242
|
+
score += 4
|
|
1243
|
+
elif rsi_status == "overbought":
|
|
1244
|
+
score -= 6
|
|
1245
|
+
return max(0.0, min(score, 100.0))
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
def _last_float(series: pd.Series) -> float | None:
|
|
1249
|
+
value = series.iloc[-1]
|
|
1250
|
+
if pd.isna(value):
|
|
1251
|
+
return None
|
|
1252
|
+
return round(float(value), 4)
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
def _is_true(value: bool) -> bool:
|
|
1256
|
+
return bool(value)
|