stock-analysis-plugin 0.2.9 → 0.2.11
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.
- package/README.md +36 -25
- package/package.json +16 -12
- package/pi/index.ts +251 -11
- package/scripts/profile-offline.py +127 -0
- package/scripts/profile-workflows.py +87 -0
- package/skills/growth-quality/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +14 -3
- package/skills/stock-analysis/references/stateless-analysis.md +16 -2
- package/skills/stock-screener/SKILL.md +4 -0
- package/skills/strategy-backtest/SKILL.md +8 -3
- package/tools/_cache.py +93 -21
- package/tools/_subproc.py +43 -8
- package/tools/alert_rules.py +63 -14
- package/tools/anomaly_detect.py +11 -6
- package/tools/backtest.py +225 -70
- package/tools/capabilities.py +1 -0
- package/tools/gather.py +63 -8
- package/tools/market_regime.py +26 -15
- package/tools/market_review.py +2 -2
- package/tools/name_resolver.py +16 -14
- package/tools/position_context.py +5 -2
- package/tools/requirements.txt +4 -4
- package/tools/risk_screening.py +40 -15
- package/tools/screener.py +44 -18
- package/tools/search_intel.py +95 -33
- package/tools/sec_holders.py +27 -25
- package/tools/signal_tracker.py +106 -54
- package/tools/stateless_analysis.py +600 -33
- package/tools/stock_data.py +366 -50
- package/tools/technical.py +42 -40
- package/tools/tiaa_disclosures.py +263 -0
- package/tools/trading_calendar.py +26 -21
- package/tools/value_data.py +6 -2
- package/tools/watchlist.py +24 -15
- package/tools/watchlist_context.py +63 -49
package/tools/stock_data.py
CHANGED
|
@@ -16,7 +16,7 @@ from pathlib import Path
|
|
|
16
16
|
from zoneinfo import ZoneInfo
|
|
17
17
|
|
|
18
18
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
19
|
-
from _cache import DAY, WEEK, cached # noqa: E402
|
|
19
|
+
from _cache import DAY, WEEK, atomic_write, cached # noqa: E402
|
|
20
20
|
from _subproc import run_tool, scrub_secrets, socket_timeout, utf8_stdio # noqa: E402
|
|
21
21
|
|
|
22
22
|
# Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
|
|
@@ -71,11 +71,12 @@ def normalize_stock_code(symbol: str) -> dict:
|
|
|
71
71
|
|
|
72
72
|
|
|
73
73
|
def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
|
|
74
|
-
"""Calculate limit-up or limit-down price with
|
|
75
|
-
import
|
|
74
|
+
"""Calculate limit-up or limit-down price with decimal round-half-up."""
|
|
75
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
76
76
|
|
|
77
77
|
sign = 1 if direction == "up" else -1
|
|
78
|
-
|
|
78
|
+
price = Decimal(str(pre_close)) * (1 + sign * Decimal(str(ratio)))
|
|
79
|
+
return float(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
|
|
79
80
|
|
|
80
81
|
|
|
81
82
|
# Chains that get sticky ordering: the CN free-source chains, where failures are
|
|
@@ -145,8 +146,37 @@ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
|
|
|
145
146
|
for attempt in range(retries + 1):
|
|
146
147
|
try:
|
|
147
148
|
return fn(*args, **kwargs)
|
|
148
|
-
except Exception:
|
|
149
|
-
|
|
149
|
+
except Exception as exc:
|
|
150
|
+
from requests.exceptions import ChunkedEncodingError, HTTPError, Timeout
|
|
151
|
+
from requests.exceptions import ConnectionError as RequestsConnectionError
|
|
152
|
+
from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
|
|
153
|
+
|
|
154
|
+
transport_errors = (
|
|
155
|
+
ConnectionError,
|
|
156
|
+
TimeoutError,
|
|
157
|
+
RequestsConnectionError,
|
|
158
|
+
Timeout,
|
|
159
|
+
ChunkedEncodingError,
|
|
160
|
+
RequestsJSONDecodeError,
|
|
161
|
+
json.JSONDecodeError,
|
|
162
|
+
)
|
|
163
|
+
http_errors = (HTTPError,)
|
|
164
|
+
if type(exc).__module__.startswith("curl_cffi."):
|
|
165
|
+
from curl_cffi.requests.exceptions import ConnectionError as CurlConnectionError
|
|
166
|
+
from curl_cffi.requests.exceptions import HTTPError as CurlHTTPError
|
|
167
|
+
from curl_cffi.requests.exceptions import Timeout as CurlTimeout
|
|
168
|
+
|
|
169
|
+
transport_errors += (CurlConnectionError, CurlTimeout)
|
|
170
|
+
http_errors += (CurlHTTPError,)
|
|
171
|
+
transient = isinstance(exc, transport_errors)
|
|
172
|
+
if isinstance(exc, http_errors):
|
|
173
|
+
status = getattr(exc.response, "status_code", None)
|
|
174
|
+
transient = status in (408, 429) or isinstance(status, int) and 500 <= status < 600
|
|
175
|
+
if type(exc).__module__.startswith("yfinance."):
|
|
176
|
+
from yfinance import exceptions as yf_errors
|
|
177
|
+
|
|
178
|
+
transient = isinstance(exc, getattr(yf_errors, "YFRateLimitError", ()))
|
|
179
|
+
if not transient or attempt == retries:
|
|
150
180
|
raise
|
|
151
181
|
time.sleep(delay)
|
|
152
182
|
|
|
@@ -260,6 +290,7 @@ def _quote_efinance(symbol: str) -> dict:
|
|
|
260
290
|
with contextlib.suppress(ValueError, TypeError):
|
|
261
291
|
val = float(val) if en_key not in ("symbol", "name") else val
|
|
262
292
|
result[en_key] = val
|
|
293
|
+
result["pe_basis"] = "dynamic"
|
|
263
294
|
return _clean_row(result)
|
|
264
295
|
|
|
265
296
|
|
|
@@ -328,6 +359,7 @@ def _tencent_payload_row(f: list, symbol: str) -> dict:
|
|
|
328
359
|
"prev_close": _parse_float(f[4]),
|
|
329
360
|
"market_cap": market_cap * 1e8 if market_cap is not None else None,
|
|
330
361
|
"pe": _parse_float(f[39]),
|
|
362
|
+
"pe_basis": "unknown",
|
|
331
363
|
# Tencent's HK map labels f[47] DY and f[49] WK52_Low; neither is an A-share ratio.
|
|
332
364
|
"pb": None if hk else _parse_float(f[46]),
|
|
333
365
|
"turnover_rate": None if hk else _parse_float(f[38]),
|
|
@@ -626,6 +658,9 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
|
|
|
626
658
|
df = df.rename(columns={f"{c}_qfq": c for c in prices})
|
|
627
659
|
if not df[prices].abs().lt(float("inf")).all().all():
|
|
628
660
|
raise ValueError("tushare returned invalid adjusted prices")
|
|
661
|
+
df["trade_date"] = pd.to_datetime(df["trade_date"], format="%Y%m%d")
|
|
662
|
+
if "amount" in df.columns:
|
|
663
|
+
df["amount"] = pd.to_numeric(df["amount"], errors="coerce") * 1000
|
|
629
664
|
col_map = {"trade_date": "date", "vol": "volume", "amount": "turnover", "pct_chg": "change_pct"}
|
|
630
665
|
df = df.rename(columns=col_map)
|
|
631
666
|
df = df.sort_values("date")
|
|
@@ -798,7 +833,7 @@ def _kline_finnhub(symbol: str, period: str, count: int) -> list:
|
|
|
798
833
|
rows.append(
|
|
799
834
|
_clean_row(
|
|
800
835
|
{
|
|
801
|
-
"date": datetime.fromtimestamp(candles["t"][i]).strftime("%Y-%m-%d"),
|
|
836
|
+
"date": datetime.fromtimestamp(candles["t"][i], timezone.utc).strftime("%Y-%m-%d"),
|
|
802
837
|
"open": candles["o"][i],
|
|
803
838
|
"high": candles["h"][i],
|
|
804
839
|
"low": candles["l"][i],
|
|
@@ -1130,6 +1165,7 @@ def _quote_akshare(symbol: str) -> dict:
|
|
|
1130
1165
|
"prev_close": r.get("昨收"),
|
|
1131
1166
|
"market_cap": r.get("总市值"),
|
|
1132
1167
|
"pe": r.get("市盈率-动态"),
|
|
1168
|
+
"pe_basis": "dynamic",
|
|
1133
1169
|
"pb": r.get("市净率"),
|
|
1134
1170
|
"turnover_rate": r.get("换手率"),
|
|
1135
1171
|
"volume_ratio": r.get("量比"),
|
|
@@ -1161,6 +1197,7 @@ def _quote_yfinance(symbol: str) -> dict:
|
|
|
1161
1197
|
"prev_close": info.get("regularMarketPreviousClose"),
|
|
1162
1198
|
"market_cap": info.get("marketCap"),
|
|
1163
1199
|
"pe": info.get("trailingPE"),
|
|
1200
|
+
"pe_basis": "trailing",
|
|
1164
1201
|
"pb": info.get("priceToBook"),
|
|
1165
1202
|
}
|
|
1166
1203
|
)
|
|
@@ -1249,12 +1286,128 @@ def _quote_stale_marker(market: str):
|
|
|
1249
1286
|
}
|
|
1250
1287
|
|
|
1251
1288
|
|
|
1289
|
+
_YOUZHIYOUXING_TIAA = {
|
|
1290
|
+
"TIAA001001": "长钱账户",
|
|
1291
|
+
"TIAA001002": "海外长钱",
|
|
1292
|
+
"TIAA001004": "稳钱账户",
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
def _quote_tiaa(symbol: str) -> dict:
|
|
1297
|
+
import requests
|
|
1298
|
+
|
|
1299
|
+
disclosure_name = _YOUZHIYOUXING_TIAA.get(symbol)
|
|
1300
|
+
result = {
|
|
1301
|
+
"symbol": symbol,
|
|
1302
|
+
"name": None,
|
|
1303
|
+
"asset_type": "investment_advisory_portfolio",
|
|
1304
|
+
"type_description": "雪球投顾组合,无统一单位净值",
|
|
1305
|
+
"manager": None,
|
|
1306
|
+
"advisor_code": f"A{symbol[4:7]}",
|
|
1307
|
+
"advisor_org": None,
|
|
1308
|
+
"advisor_mapping_basis": "tiaa_prefix_best_effort",
|
|
1309
|
+
"advisor_source_url": None,
|
|
1310
|
+
"advisor_retrieved_at": None,
|
|
1311
|
+
"nav": None,
|
|
1312
|
+
"example_account_performance": None,
|
|
1313
|
+
"quote_type": None,
|
|
1314
|
+
"exchange": None,
|
|
1315
|
+
"source": None,
|
|
1316
|
+
"source_url": f"https://xueqiu.com/S/{symbol}",
|
|
1317
|
+
"data_as_of": None,
|
|
1318
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
1319
|
+
"official_disclosures": [],
|
|
1320
|
+
"public_search_results": [],
|
|
1321
|
+
"disclosure_provider": "youzhiyouxing" if disclosure_name else None,
|
|
1322
|
+
"disclosure_status": "unavailable" if disclosure_name else "unsupported_provider",
|
|
1323
|
+
"disclosures_partial": True,
|
|
1324
|
+
"disclosures_as_of": None,
|
|
1325
|
+
"note": (
|
|
1326
|
+
"投顾组合无统一净值;主理人及完整业绩/持仓需在对应投顾平台登录后查询;"
|
|
1327
|
+
"官方公开披露仅为部分历史信息,持有人收益随买入时点和调仓跟进不同"
|
|
1328
|
+
),
|
|
1329
|
+
}
|
|
1330
|
+
try:
|
|
1331
|
+
with requests.Session() as session:
|
|
1332
|
+
session.get(
|
|
1333
|
+
"https://xueqiu.com/",
|
|
1334
|
+
headers={"User-Agent": "Mozilla/5.0"},
|
|
1335
|
+
timeout=10,
|
|
1336
|
+
allow_redirects=True,
|
|
1337
|
+
).raise_for_status()
|
|
1338
|
+
response = session.get(
|
|
1339
|
+
"https://stock.xueqiu.com/v5/stock/quote.json",
|
|
1340
|
+
params={"symbol": symbol, "extend": "detail"},
|
|
1341
|
+
headers={"User-Agent": "Mozilla/5.0", "Referer": "https://xueqiu.com/"},
|
|
1342
|
+
timeout=10,
|
|
1343
|
+
)
|
|
1344
|
+
response.raise_for_status()
|
|
1345
|
+
payload = response.json()
|
|
1346
|
+
if payload.get("error_code") not in (None, 0):
|
|
1347
|
+
raise ValueError("xueqiu portfolio metadata unavailable")
|
|
1348
|
+
quote = (payload.get("data") or {}).get("quote") or {}
|
|
1349
|
+
if quote.get("symbol") != symbol:
|
|
1350
|
+
raise ValueError("xueqiu returned different portfolio metadata")
|
|
1351
|
+
result.update(
|
|
1352
|
+
name=quote.get("name"),
|
|
1353
|
+
quote_type=quote.get("type"),
|
|
1354
|
+
exchange=quote.get("exchange"),
|
|
1355
|
+
source="xueqiu",
|
|
1356
|
+
data_as_of=_unix_quote_time(quote.get("timestamp")),
|
|
1357
|
+
)
|
|
1358
|
+
except Exception:
|
|
1359
|
+
result["warnings"] = ["xueqiu portfolio name unavailable; type guidance remains available"]
|
|
1360
|
+
if disclosure_name and result["name"] in (None, disclosure_name):
|
|
1361
|
+
try:
|
|
1362
|
+
from tiaa_disclosures import public_disclosures
|
|
1363
|
+
|
|
1364
|
+
disclosure = public_disclosures(symbol, disclosure_name)
|
|
1365
|
+
result["official_disclosures"] = disclosure["items"]
|
|
1366
|
+
result["disclosures_as_of"] = disclosure["as_of"]
|
|
1367
|
+
if disclosure["items"]:
|
|
1368
|
+
result["disclosure_status"] = "partial_public"
|
|
1369
|
+
except Exception:
|
|
1370
|
+
result.setdefault("warnings", []).append(
|
|
1371
|
+
"official public disclosures unavailable; type guidance remains available"
|
|
1372
|
+
)
|
|
1373
|
+
elif disclosure_name and result["name"]:
|
|
1374
|
+
result["disclosure_status"] = "unsupported_provider"
|
|
1375
|
+
result.setdefault("warnings", []).append("portfolio name does not match the registered disclosure source")
|
|
1376
|
+
else:
|
|
1377
|
+
from tiaa_disclosures import search_public
|
|
1378
|
+
|
|
1379
|
+
result["public_search_results"] = search_public(symbol, result["name"])
|
|
1380
|
+
if result["public_search_results"]:
|
|
1381
|
+
result["disclosure_provider"] = "web_search"
|
|
1382
|
+
result["disclosure_status"] = "search_partial"
|
|
1383
|
+
try:
|
|
1384
|
+
from tiaa_disclosures import advisor_metadata
|
|
1385
|
+
|
|
1386
|
+
result.update(advisor_metadata(symbol))
|
|
1387
|
+
except Exception:
|
|
1388
|
+
result.setdefault("warnings", []).append("advisor organization metadata unavailable")
|
|
1389
|
+
return result
|
|
1390
|
+
|
|
1391
|
+
|
|
1252
1392
|
def cmd_quote(args):
|
|
1393
|
+
if re.fullmatch(r"TIAA\d{6}", args.symbol, re.IGNORECASE):
|
|
1394
|
+
return _quote_tiaa(args.symbol.upper())
|
|
1253
1395
|
market = detect_market(args.symbol)
|
|
1254
1396
|
try:
|
|
1255
1397
|
result = quote_a(args.symbol, evidence=True) if market == "A" else quote_yf(args.symbol, evidence=True)
|
|
1256
1398
|
except Exception as e:
|
|
1257
|
-
|
|
1399
|
+
result = {"error": str(e)}
|
|
1400
|
+
# Exchange quotes cannot see open-end funds. Stock-only prefixes (SH 60/68, ChiNext 30, BSE) keep the bare error.
|
|
1401
|
+
if (
|
|
1402
|
+
isinstance(result, dict)
|
|
1403
|
+
and "error" in result
|
|
1404
|
+
and re.fullmatch(r"\d{6}", args.symbol)
|
|
1405
|
+
and not re.match(r"(?:60|68|30|43|83|87|92)", args.symbol)
|
|
1406
|
+
):
|
|
1407
|
+
result["hint"] = (
|
|
1408
|
+
f"{args.symbol} 若为场外公募基金,请改用 get_fund_quote(stock_data.py fund_quote {args.symbol})"
|
|
1409
|
+
)
|
|
1410
|
+
return result
|
|
1258
1411
|
if isinstance(result, dict) and "error" not in result:
|
|
1259
1412
|
marker = _quote_stale_marker(market)
|
|
1260
1413
|
if marker:
|
|
@@ -1285,6 +1438,109 @@ def cmd_quote(args):
|
|
|
1285
1438
|
return result
|
|
1286
1439
|
|
|
1287
1440
|
|
|
1441
|
+
# --------------- open-end fund quote ---------------
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def _fund_js_value(text: str, name: str):
|
|
1445
|
+
match = re.search(rf"\b{re.escape(name)}\s*=\s*", text)
|
|
1446
|
+
if not match:
|
|
1447
|
+
raise ValueError(f"eastmoney fund data missing {name}")
|
|
1448
|
+
try:
|
|
1449
|
+
return json.JSONDecoder().raw_decode(text[match.end() :])[0]
|
|
1450
|
+
except json.JSONDecodeError as exc:
|
|
1451
|
+
raise ValueError(f"eastmoney fund data has invalid {name}") from exc
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def _fund_nav_date(stamp) -> str:
|
|
1455
|
+
return datetime.fromtimestamp(stamp / 1000, timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
1456
|
+
|
|
1457
|
+
|
|
1458
|
+
def _fund_estimate(symbol: str) -> dict:
|
|
1459
|
+
import akshare as ak
|
|
1460
|
+
|
|
1461
|
+
with socket_timeout(25):
|
|
1462
|
+
df = ak.fund_value_estimation_em()
|
|
1463
|
+
if df is None or df.empty or "基金代码" not in df.columns:
|
|
1464
|
+
return {}
|
|
1465
|
+
rows = df[df["基金代码"] == symbol]
|
|
1466
|
+
value_col = next((c for c in df.columns if c.endswith("-估算数据-估算值")), None)
|
|
1467
|
+
change_col = next((c for c in df.columns if c.endswith("-估算数据-估算增长率")), None)
|
|
1468
|
+
if rows.empty or not value_col:
|
|
1469
|
+
return {}
|
|
1470
|
+
row = rows.iloc[0]
|
|
1471
|
+
estimated_nav = _parse_float(row.get(value_col))
|
|
1472
|
+
if estimated_nav is None:
|
|
1473
|
+
return {}
|
|
1474
|
+
return {
|
|
1475
|
+
"estimated_nav": estimated_nav,
|
|
1476
|
+
"estimated_change_pct": _parse_float(str(row.get(change_col)).rstrip("%")) if change_col else None,
|
|
1477
|
+
"estimated_at": value_col.split("-估算数据-", 1)[0],
|
|
1478
|
+
"estimate_status": "available",
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
def cmd_fund_quote(args):
|
|
1483
|
+
symbol = args.symbol
|
|
1484
|
+
if not re.fullmatch(r"\d{6}", symbol):
|
|
1485
|
+
return {"error": "open-end fund symbol must be exactly 6 digits"}
|
|
1486
|
+
try:
|
|
1487
|
+
import requests
|
|
1488
|
+
|
|
1489
|
+
response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15)
|
|
1490
|
+
response.raise_for_status()
|
|
1491
|
+
text = response.text
|
|
1492
|
+
if _fund_js_value(text, "fS_code") != symbol:
|
|
1493
|
+
raise ValueError(f"eastmoney returned a different fund for {symbol}")
|
|
1494
|
+
name = _fund_js_value(text, "fS_name")
|
|
1495
|
+
nav_rows = _fund_js_value(text, "Data_netWorthTrend")
|
|
1496
|
+
accumulated_rows = _fund_js_value(text, "Data_ACWorthTrend")
|
|
1497
|
+
if not nav_rows:
|
|
1498
|
+
raise ValueError(f"eastmoney returned no NAV for {symbol}")
|
|
1499
|
+
latest = nav_rows[-1]
|
|
1500
|
+
nav_date = _fund_nav_date(latest["x"])
|
|
1501
|
+
accumulated_by_date = {_fund_nav_date(row[0]): row[1] for row in accumulated_rows}
|
|
1502
|
+
today = datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
1503
|
+
estimate = {
|
|
1504
|
+
"estimated_nav": None,
|
|
1505
|
+
"estimated_change_pct": None,
|
|
1506
|
+
"estimated_at": None,
|
|
1507
|
+
"estimate_status": "unavailable",
|
|
1508
|
+
}
|
|
1509
|
+
warnings = []
|
|
1510
|
+
try:
|
|
1511
|
+
estimate.update(_fund_estimate(symbol))
|
|
1512
|
+
except Exception:
|
|
1513
|
+
warnings.append("estimated NAV provider request failed; published NAV remains available")
|
|
1514
|
+
result = _clean_row(
|
|
1515
|
+
{
|
|
1516
|
+
"symbol": symbol,
|
|
1517
|
+
"name": name,
|
|
1518
|
+
"asset_type": "open_end_fund",
|
|
1519
|
+
"nav": latest.get("y"),
|
|
1520
|
+
"accumulated_nav": accumulated_by_date.get(nav_date),
|
|
1521
|
+
"change_pct": latest.get("equityReturn"),
|
|
1522
|
+
"nav_date": nav_date,
|
|
1523
|
+
"data_as_of": nav_date,
|
|
1524
|
+
"as_of": nav_date,
|
|
1525
|
+
"as_of_basis": "provider",
|
|
1526
|
+
"stale": nav_date < today,
|
|
1527
|
+
"source": "eastmoney",
|
|
1528
|
+
"source_url": f"https://fund.eastmoney.com/{symbol}.html",
|
|
1529
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
1530
|
+
"note": (
|
|
1531
|
+
"nav is published end-of-day NAV, not a real-time price; QDII disclosure may lag "
|
|
1532
|
+
"1-2 trading days; estimated_nav is separate and may be unavailable"
|
|
1533
|
+
),
|
|
1534
|
+
**estimate,
|
|
1535
|
+
}
|
|
1536
|
+
)
|
|
1537
|
+
if warnings:
|
|
1538
|
+
result["warnings"] = warnings
|
|
1539
|
+
return result
|
|
1540
|
+
except Exception as e:
|
|
1541
|
+
return {"error": str(e)}
|
|
1542
|
+
|
|
1543
|
+
|
|
1288
1544
|
# --------------- capital_flow ---------------
|
|
1289
1545
|
|
|
1290
1546
|
|
|
@@ -1370,8 +1626,10 @@ def cmd_capital_flow(args):
|
|
|
1370
1626
|
summary = {"symbol": args.symbol}
|
|
1371
1627
|
for days, label in [(5, "5d"), (10, "10d"), (20, "20d")]:
|
|
1372
1628
|
tail = df_all.tail(days)
|
|
1373
|
-
summary[f"main_net_{label}"] = _sanitize(tail.get("main_net_inflow", pd.Series()).sum())
|
|
1374
|
-
summary[f"super_large_net_{label}"] = _sanitize(
|
|
1629
|
+
summary[f"main_net_{label}"] = _sanitize(tail.get("main_net_inflow", pd.Series()).sum(min_count=days))
|
|
1630
|
+
summary[f"super_large_net_{label}"] = _sanitize(
|
|
1631
|
+
tail.get("super_large_net", pd.Series()).sum(min_count=days)
|
|
1632
|
+
)
|
|
1375
1633
|
recent = df_all["main_net_inflow"].tail(5) if "main_net_inflow" in df_all.columns else pd.Series()
|
|
1376
1634
|
if len(recent) >= 3:
|
|
1377
1635
|
pos_count = (recent > 0).sum()
|
|
@@ -1566,6 +1824,13 @@ def financials_yf(symbol: str, periods: int = 1, annual: bool = False) -> dict:
|
|
|
1566
1824
|
"roe": info.get("returnOnEquity"),
|
|
1567
1825
|
"debt_to_equity": info.get("debtToEquity"),
|
|
1568
1826
|
"dividend_yield": info.get("dividendYield"),
|
|
1827
|
+
"snapshot_units": {
|
|
1828
|
+
"pe": "trailing",
|
|
1829
|
+
"roe": "ratio",
|
|
1830
|
+
"profit_margin": "ratio",
|
|
1831
|
+
"debt_to_equity": "percent",
|
|
1832
|
+
"dividend_yield": "ratio",
|
|
1833
|
+
},
|
|
1569
1834
|
}
|
|
1570
1835
|
)
|
|
1571
1836
|
if warnings:
|
|
@@ -1703,7 +1968,8 @@ def _snapshot_efinance() -> list:
|
|
|
1703
1968
|
"昨收": "prev_close",
|
|
1704
1969
|
}
|
|
1705
1970
|
df = df.rename(columns=col_map)
|
|
1706
|
-
|
|
1971
|
+
df["pe_basis"] = "dynamic"
|
|
1972
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1707
1973
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1708
1974
|
|
|
1709
1975
|
|
|
@@ -1815,7 +2081,8 @@ def _snapshot_akshare() -> list:
|
|
|
1815
2081
|
"60日涨跌幅": "change_pct_60d",
|
|
1816
2082
|
}
|
|
1817
2083
|
df = df.rename(columns=col_map)
|
|
1818
|
-
|
|
2084
|
+
df["pe_basis"] = "dynamic"
|
|
2085
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1819
2086
|
df = df[keep]
|
|
1820
2087
|
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1821
2088
|
|
|
@@ -1824,7 +2091,8 @@ def snapshot_hk() -> list:
|
|
|
1824
2091
|
try:
|
|
1825
2092
|
import akshare as ak
|
|
1826
2093
|
|
|
1827
|
-
|
|
2094
|
+
with socket_timeout(25):
|
|
2095
|
+
df = _akshare_retry(ak.stock_hk_spot_em)
|
|
1828
2096
|
col_map = {
|
|
1829
2097
|
"代码": "symbol",
|
|
1830
2098
|
"名称": "name",
|
|
@@ -1837,7 +2105,11 @@ def snapshot_hk() -> list:
|
|
|
1837
2105
|
"总市值": "market_cap",
|
|
1838
2106
|
}
|
|
1839
2107
|
df = df.rename(columns=col_map)
|
|
1840
|
-
|
|
2108
|
+
if "symbol" in df.columns:
|
|
2109
|
+
symbols = df["symbol"].astype(str).str.upper()
|
|
2110
|
+
df["symbol"] = symbols.map(lambda s: s if s.endswith(".HK") else f"{s}.HK")
|
|
2111
|
+
df["pe_basis"] = "unknown"
|
|
2112
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1841
2113
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1842
2114
|
except Exception as e:
|
|
1843
2115
|
# summary only (type + short message) — never a stack trace or response body
|
|
@@ -1848,7 +2120,8 @@ def snapshot_us() -> list:
|
|
|
1848
2120
|
try:
|
|
1849
2121
|
import akshare as ak
|
|
1850
2122
|
|
|
1851
|
-
|
|
2123
|
+
with socket_timeout(25):
|
|
2124
|
+
df = _akshare_retry(ak.stock_us_spot_em)
|
|
1852
2125
|
col_map = {
|
|
1853
2126
|
"代码": "symbol",
|
|
1854
2127
|
"名称": "name",
|
|
@@ -1860,7 +2133,11 @@ def snapshot_us() -> list:
|
|
|
1860
2133
|
"总市值": "market_cap",
|
|
1861
2134
|
}
|
|
1862
2135
|
df = df.rename(columns=col_map)
|
|
1863
|
-
|
|
2136
|
+
if "symbol" in df.columns:
|
|
2137
|
+
symbols = df["symbol"].astype(str).str.upper().str.replace(r"\.(?:OQ|N|A)$", "", regex=True)
|
|
2138
|
+
df["symbol"] = symbols.str.replace(".", "-", regex=False)
|
|
2139
|
+
df["pe_basis"] = "unknown"
|
|
2140
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1864
2141
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1865
2142
|
except Exception as e:
|
|
1866
2143
|
return [{"error": f"US snapshot unavailable: {type(e).__name__}: {scrub_secrets(str(e))}"[:200]}]
|
|
@@ -1940,33 +2217,39 @@ def cmd_market_indices(args):
|
|
|
1940
2217
|
)
|
|
1941
2218
|
return results
|
|
1942
2219
|
elif region in _REGION_INDEX_SYMBOLS:
|
|
2220
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
2221
|
+
|
|
1943
2222
|
import yfinance as yf
|
|
1944
2223
|
|
|
1945
2224
|
symbols = _REGION_INDEX_SYMBOLS[region]
|
|
1946
|
-
|
|
1947
|
-
|
|
2225
|
+
|
|
2226
|
+
def fetch_index(item):
|
|
2227
|
+
sym, name = item
|
|
1948
2228
|
try:
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
2229
|
+
info = yf.Ticker(sym).info
|
|
2230
|
+
return _clean_row(
|
|
2231
|
+
{
|
|
2232
|
+
"code": sym,
|
|
2233
|
+
"name": name,
|
|
2234
|
+
"price": info.get("regularMarketPrice"),
|
|
2235
|
+
"change": info.get("regularMarketChange"),
|
|
2236
|
+
"change_pct": info.get("regularMarketChangePercent"),
|
|
2237
|
+
"volume": info.get("regularMarketVolume"),
|
|
2238
|
+
"high": info.get("regularMarketDayHigh"),
|
|
2239
|
+
"low": info.get("regularMarketDayLow"),
|
|
2240
|
+
"open": info.get("regularMarketOpen"),
|
|
2241
|
+
"prev_close": info.get("regularMarketPreviousClose"),
|
|
2242
|
+
"source": "yfinance",
|
|
2243
|
+
"data_as_of": _unix_quote_time(info.get("regularMarketTime")),
|
|
2244
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
2245
|
+
}
|
|
1966
2246
|
)
|
|
1967
2247
|
except Exception:
|
|
1968
|
-
|
|
1969
|
-
|
|
2248
|
+
return {"code": sym, "name": name, "note": "data unavailable"}
|
|
2249
|
+
|
|
2250
|
+
# Preserve provider order while overlapping independent quote requests.
|
|
2251
|
+
with ThreadPoolExecutor(max_workers=min(4, len(symbols))) as pool:
|
|
2252
|
+
return list(pool.map(fetch_index, symbols.items()))
|
|
1970
2253
|
return {"error": f"Unknown region: {region}"}
|
|
1971
2254
|
except Exception as e:
|
|
1972
2255
|
return {"error": str(e)}
|
|
@@ -2154,8 +2437,8 @@ def _disk_cache_get(key: str):
|
|
|
2154
2437
|
|
|
2155
2438
|
def _disk_cache_set(key: str, data):
|
|
2156
2439
|
try:
|
|
2157
|
-
_DATA_CACHE_DIR.
|
|
2158
|
-
|
|
2440
|
+
with atomic_write(_DATA_CACHE_DIR / f"{key}.json") as stream:
|
|
2441
|
+
json.dump(data, stream, ensure_ascii=False, allow_nan=False)
|
|
2159
2442
|
except Exception:
|
|
2160
2443
|
pass
|
|
2161
2444
|
|
|
@@ -2711,6 +2994,9 @@ def compute_market_stats(data: list) -> dict:
|
|
|
2711
2994
|
code_info = normalize_stock_code(sym)
|
|
2712
2995
|
lp = code_info.get("limit_pct")
|
|
2713
2996
|
if lp:
|
|
2997
|
+
name = s.get("name", "")
|
|
2998
|
+
if name and "ST" in name.upper() and code_info["board"] == "main":
|
|
2999
|
+
lp = 0.05
|
|
2714
3000
|
limit_up = calc_limit_price(float(prev), lp, "up")
|
|
2715
3001
|
limit_down = calc_limit_price(float(prev), lp, "down")
|
|
2716
3002
|
if abs(float(price) - limit_up) < 0.01:
|
|
@@ -2775,6 +3061,7 @@ def cmd_fundamental_context(args):
|
|
|
2775
3061
|
quote = quote_a(args.symbol)
|
|
2776
3062
|
result["valuation"] = {
|
|
2777
3063
|
"pe": quote.get("pe"),
|
|
3064
|
+
"pe_basis": quote.get("pe_basis"),
|
|
2778
3065
|
"pb": quote.get("pb"),
|
|
2779
3066
|
"market_cap": quote.get("market_cap"),
|
|
2780
3067
|
}
|
|
@@ -3149,15 +3436,12 @@ def cmd_margin_trading(args):
|
|
|
3149
3436
|
try:
|
|
3150
3437
|
import concurrent.futures
|
|
3151
3438
|
|
|
3152
|
-
import akshare as ak
|
|
3153
3439
|
from trading_calendar import prev_trading_days
|
|
3154
3440
|
|
|
3155
3441
|
if exchange == "sh":
|
|
3156
3442
|
col_map = _MARGIN_DETAIL_SSE_COLS
|
|
3157
|
-
detail_fn = ak.stock_margin_detail_sse
|
|
3158
3443
|
elif exchange == "sz":
|
|
3159
3444
|
col_map = _MARGIN_DETAIL_SZSE_COLS
|
|
3160
|
-
detail_fn = ak.stock_margin_detail_szse
|
|
3161
3445
|
else:
|
|
3162
3446
|
return {"error": f"margin_trading: {args.symbol} is a BSE code; only SSE/SZSE margin detail is available"}
|
|
3163
3447
|
trade_days = prev_trading_days("CN", days)
|
|
@@ -3165,17 +3449,45 @@ def cmd_margin_trading(args):
|
|
|
3165
3449
|
return {"error": "margin_trading: trading calendar unavailable"}
|
|
3166
3450
|
|
|
3167
3451
|
def fetch_day(date_iso):
|
|
3168
|
-
"""
|
|
3169
|
-
|
|
3452
|
+
"""Cache the published exchange-day table, then select this stock."""
|
|
3453
|
+
|
|
3454
|
+
def fetch_table():
|
|
3455
|
+
import akshare as ak
|
|
3456
|
+
|
|
3457
|
+
detail_fn = ak.stock_margin_detail_sse if exchange == "sh" else ak.stock_margin_detail_szse
|
|
3170
3458
|
df = _akshare_retry(detail_fn, date=date_iso.replace("-", ""))
|
|
3459
|
+
if df is None or df.empty:
|
|
3460
|
+
return []
|
|
3461
|
+
df = df.rename(columns=col_map)
|
|
3462
|
+
required = {"symbol", "margin_buy", "margin_balance"}
|
|
3463
|
+
if not required.issubset(df.columns):
|
|
3464
|
+
raise ValueError("margin detail table missing financial columns")
|
|
3465
|
+
df = df[df["symbol"].astype(str).str.fullmatch(r"\d{6}")]
|
|
3466
|
+
if "信用交易日期" in df.columns:
|
|
3467
|
+
source_days = df["信用交易日期"].map(lambda v: re.sub(r"\D", "", str(v))[:8])
|
|
3468
|
+
if not (source_days == date_iso.replace("-", "")).all():
|
|
3469
|
+
raise ValueError("margin detail table date does not match requested day")
|
|
3470
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
3471
|
+
table = [{"date": date_iso, **_clean_row(r)} for r in df[keep].to_dict("records")]
|
|
3472
|
+
for row in table:
|
|
3473
|
+
values = [_parse_float(row.get(field)) for field in ("margin_buy", "margin_balance")]
|
|
3474
|
+
if any(value is None or not math.isfinite(value) for value in values):
|
|
3475
|
+
# Keep usable stocks without persisting an incomplete exchange snapshot.
|
|
3476
|
+
return {"rows": table, "warnings": ["incomplete financial values"]}
|
|
3477
|
+
return table
|
|
3478
|
+
|
|
3479
|
+
try:
|
|
3480
|
+
today = datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
3481
|
+
table = (
|
|
3482
|
+
cached(f"margin-table:{exchange}:{date_iso}", DAY, fetch_table)
|
|
3483
|
+
if date_iso < today
|
|
3484
|
+
else fetch_table()
|
|
3485
|
+
)
|
|
3486
|
+
if isinstance(table, dict):
|
|
3487
|
+
table = table["rows"]
|
|
3488
|
+
return date_iso, [r for r in table if str(r.get("symbol")) == bare], None
|
|
3171
3489
|
except Exception as e:
|
|
3172
3490
|
return date_iso, [], f"{date_iso}: {type(e).__name__}: {scrub_secrets(str(e))}"
|
|
3173
|
-
if df is None or df.empty:
|
|
3174
|
-
return date_iso, [], None
|
|
3175
|
-
df = df.rename(columns=col_map)
|
|
3176
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
3177
|
-
hit = df[df["symbol"].astype(str) == bare] if "symbol" in df.columns else df.iloc[0:0]
|
|
3178
|
-
return date_iso, [{"date": date_iso, **_clean_row(r)} for r in hit[keep].to_dict("records")], None
|
|
3179
3491
|
|
|
3180
3492
|
rows = []
|
|
3181
3493
|
failures = []
|
|
@@ -3297,6 +3609,9 @@ def main():
|
|
|
3297
3609
|
p_quote = sub.add_parser("quote")
|
|
3298
3610
|
p_quote.add_argument("symbol")
|
|
3299
3611
|
|
|
3612
|
+
p_fund_quote = sub.add_parser("fund_quote")
|
|
3613
|
+
p_fund_quote.add_argument("symbol")
|
|
3614
|
+
|
|
3300
3615
|
p_cf = sub.add_parser("capital_flow")
|
|
3301
3616
|
p_cf.add_argument("symbol", nargs="?", default="")
|
|
3302
3617
|
p_cf.add_argument("--mode", default="detail", choices=["detail", "summary", "sector_flow"])
|
|
@@ -3366,6 +3681,7 @@ def main():
|
|
|
3366
3681
|
dispatch = {
|
|
3367
3682
|
"kline": cmd_kline,
|
|
3368
3683
|
"quote": cmd_quote,
|
|
3684
|
+
"fund_quote": cmd_fund_quote,
|
|
3369
3685
|
"capital_flow": cmd_capital_flow,
|
|
3370
3686
|
"news": cmd_news,
|
|
3371
3687
|
"financials": cmd_financials,
|