dsh-stock-analysis 0.2.12 → 0.2.14

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.
@@ -372,6 +372,36 @@
372
372
  ]
373
373
  }
374
374
  },
375
+ {
376
+ "name": "get_cds_index",
377
+ "description": "查询市场级CDS指数作为信用风险偏好背景(非个股CDS或交易信号)。source=cn返回中国货币网CFETS-SHCH高等级/民企/长三角/科创/碳中和在岸CDS指数最新期限曲线(bp)与窗口内各期限变化(percentile为窗口内≤最新值的百分比0..100);source=global取DTCC公开成交,按日汇总当前5Y系列CDX.NA.IG、iTraxx Europe/Crossover利差(bp)与CDX.NA.HY价格(价格下跌=信用走弱),只比较同一到期系列,是成交中位数而非官方收盘。用index/tenor只取需要的指数和期限,cn历史只为匹配到的指数分页拉取。",
378
+ "parameters": {
379
+ "type": "object",
380
+ "properties": {
381
+ "source": {
382
+ "type": "string",
383
+ "enum": [
384
+ "cn",
385
+ "global"
386
+ ],
387
+ "description": "cn=中国在岸CDS指数(默认),global=DTCC公开成交的CDX/iTraxx"
388
+ },
389
+ "days": {
390
+ "type": "number",
391
+ "description": "回看自然日1..90,默认30;global截止到DTCC最新已发布工作日文件"
392
+ },
393
+ "index": {
394
+ "type": "string",
395
+ "description": "指数名,精确匹配优先、否则包含匹配,如民企、科创、高等级、CDX.NA.HY、ITRAXX EUROPE;省略返回全部"
396
+ },
397
+ "tenor": {
398
+ "type": "string",
399
+ "description": "期限,如3M、1Y、5Y;cn按期限过滤,global仅5Y;省略返回全部期限"
400
+ }
401
+ },
402
+ "required": []
403
+ }
404
+ },
375
405
  {
376
406
  "name": "get_earnings_calendar",
377
407
  "description": "查询财报日历:A股report_date必填季度期末,返回预约/修订/实际披露与业绩预告;HK需symbol,优先HKEX已公告业绩审批董事会排期(不是实际披露日);US/JP需symbol并返回yfinance供应商预计日期(provider_only,非官方确认)。HK可按已知财政期末过滤,未知期次与US/JP请求report_date时另列unverified_schedules;KR/TW不可用。",
@@ -812,7 +842,7 @@
812
842
  },
813
843
  {
814
844
  "name": "get_market_stats",
815
- "description": "获取市场整体统计(涨跌家数、平均/中位涨幅、涨跌Top5、总成交额)。market=A(默认)含涨停跌停数;HK/US基于东方财富全市场快照,无涨跌停制度,涨跌停字段为null。用于衡量市场整体情绪与温度",
845
+ "description": "获取市场整体统计(涨跌家数、中位涨幅、涨跌Top5、总成交额)。market=A(默认)含涨停跌停数;HK/US基于东方财富涨跌排行计数,无涨跌停制度,涨跌停字段与总成交额为null。avg_change_pct恒为null。用于衡量市场整体情绪与温度",
816
846
  "parameters": {
817
847
  "type": "object",
818
848
  "properties": {
@@ -19,7 +19,16 @@ import pandas as pd
19
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
20
20
  from _cache import DAY, cached
21
21
  from _subproc import error_message, scrub_secrets, socket_timeout, utf8_stdio
22
- from stock_data import _A_INDEX_RE, _cn_code, _cn_now, _yf_hk_symbol, detect_market, normalize_stock_code
22
+ from stock_data import (
23
+ _A_INDEX_RE,
24
+ _cn_code,
25
+ _cn_now,
26
+ _em_datacenter,
27
+ _yf_hk_symbol,
28
+ detect_market,
29
+ fund_pingzhong_js,
30
+ normalize_stock_code,
31
+ )
23
32
  from trading_calendar import _MARKET_TZ, market_now
24
33
 
25
34
  YF_MARKETS = ("US", "JP", "KR", "TW")
@@ -395,10 +404,7 @@ def hk_board_meetings(board):
395
404
 
396
405
 
397
406
  def earnings_calendar(args):
398
- import akshare as ak
399
-
400
407
  stamp = iso(args.report_date)
401
- suffix = {"03-31": "一季", "06-30": "半年报", "09-30": "三季", "12-31": "年报"}
402
408
  if not 1 <= args.top <= 500 or (args.report_date and not stamp):
403
409
  raise ValueError("report_date must be a valid date and top must be in 1..500")
404
410
  market = detect_market(args.symbol) if args.symbol else "A"
@@ -470,37 +476,38 @@ def earnings_calendar(args):
470
476
  + ["provider-only schedules have unverified fiscal periods and are not assigned to requested report_date"],
471
477
  "as_of": today,
472
478
  }
473
- if not stamp or stamp[5:] not in suffix:
479
+ if not stamp or stamp[5:] not in ("03-31", "06-30", "09-30", "12-31"):
474
480
  raise ValueError("report_date must be a quarter end for A-share earnings calendars")
475
481
  symbol = ""
476
482
  if args.symbol:
477
483
  market, symbol = stock_identity(args.symbol)
478
484
  if market != "A":
479
485
  raise ValueError("earnings calendar covers A shares only")
480
- result = {"report_date": stamp, "source": "cninfo/eastmoney"}
481
- capture(
482
- result,
483
- "disclosures",
484
- lambda: dataset(
485
- f"disclosure:{stamp}",
486
- lambda: ak.stock_report_disclosure(market="沪深京", period=stamp[:4] + suffix[stamp[5:]]),
487
- ),
488
- )
489
- capture(
490
- result, "forecasts", lambda: dataset(f"forecast:{stamp}", lambda: ak.stock_yjyg_em(date=stamp.replace("-", "")))
491
- )
486
+ result = {"report_date": stamp, "source": "eastmoney"}
487
+ # Server-side filter + limit: one page holds the requested rows, `count` the full total.
488
+ condition = f"(REPORT_DATE='{stamp}')" + (f'(SECURITY_CODE="{symbol}")' if symbol else "")
489
+ totals = {}
490
+ queries = {
491
+ "disclosures": ("RPT_PUBLIC_BS_APPOIN", "APPOINT_PUBLISH_DATE,SECURITY_CODE", "1,1"),
492
+ "forecasts": ("RPT_PUBLIC_OP_NEWPREDICT", "NOTICE_DATE,SECURITY_CODE", "-1,-1"),
493
+ }
494
+ for key, (report, sort, order) in queries.items():
495
+
496
+ def fetch(report=report, sort=sort, order=order, key=key):
497
+ totals[key], rows = _em_datacenter(report, condition, sort, args.top, order)
498
+ return rows
499
+
500
+ capture(result, key, fetch)
492
501
  for key in ("disclosures", "forecasts"):
493
- rows = result.get(key, [])
494
- if symbol:
495
- rows = [r for r in rows if str(r.get("股票代码", "")).zfill(6) == symbol]
496
502
  output = []
497
- for row in rows:
498
- item = {"symbol": str(row.get("股票代码", "")).zfill(6), "name": row.get("股票简称")}
503
+ for row in result.get(key, []):
504
+ item = {"symbol": str(row.get("SECURITY_CODE", "")).zfill(6), "name": row.get("SECURITY_NAME_ABBR")}
499
505
  if key == "disclosures":
500
- revised = [iso(row.get(c)) for c in ("首次预约", "初次变更", "二次变更", "三次变更")]
506
+ columns = ("FIRST_APPOINT_DATE", "FIRST_CHANGE_DATE", "SECOND_CHANGE_DATE", "THIRD_CHANGE_DATE")
507
+ revised = [iso(row.get(c)) for c in columns]
501
508
  item.update(
502
509
  scheduled_date=next((d for d in reversed(revised) if d), None),
503
- actual_date=iso(row.get("实际披露")),
510
+ actual_date=iso(row.get("ACTUAL_PUBLISH_DATE")),
504
511
  original_scheduled_date=revised[0],
505
512
  scheduled_date_revisions=[
506
513
  {"revision": i, "scheduled_date": d} for i, d in enumerate(revised[1:], 1) if d
@@ -508,16 +515,16 @@ def earnings_calendar(args):
508
515
  )
509
516
  else:
510
517
  item.update(
511
- announcement_date=iso(row.get("公告日期")),
512
- forecast_type=row.get("预告类型"),
513
- indicator=row.get("预测指标"),
514
- forecast_value=number(row.get("预测数值")),
515
- change_pct=number(row.get("业绩变动幅度")),
516
- reason=row.get("业绩变动原因"),
518
+ announcement_date=iso(row.get("NOTICE_DATE")),
519
+ forecast_type=row.get("PREDICT_TYPE"),
520
+ indicator=row.get("PREDICT_FINANCE"),
521
+ forecast_value=number(row.get("FORECAST_JZ")),
522
+ change_pct=number(row.get("INCREASE_JZ")),
523
+ reason=row.get("CHANGE_REASON_EXPLAIN"),
517
524
  )
518
525
  output.append(item)
519
- result[key + "_total"] = len(output)
520
- result[key] = output[: args.top]
526
+ result[key + "_total"] = totals.get(key, 0)
527
+ result[key] = output
521
528
  if result.get("warnings") and not result["disclosures"] and not result["forecasts"]:
522
529
  raise ValueError("earnings calendar sources unavailable")
523
530
  return result
@@ -840,9 +847,10 @@ def hk_dividend_ranking(report_date=""):
840
847
  return cached(f"hk-dividend-ranking:{stamp}", DAY, fetch)
841
848
 
842
849
 
843
- def dividend_ranking(report_date="", market="A"):
844
- import akshare as ak
850
+ def dividend_ranking(report_date="", market="A", top=500, codes=None):
851
+ """Implemented cash-dividend plans ranked by yield, sorted and limited server-side.
845
852
 
853
+ `codes` (A only) restricts the query to those stocks — the screener asks only for its candidates."""
846
854
  if market == "HK":
847
855
  return hk_dividend_ranking(report_date)
848
856
  if market != "A":
@@ -850,23 +858,32 @@ def dividend_ranking(report_date="", market="A"):
850
858
  stamp = iso(report_date) if report_date else f"{_cn_now().date().year - 1}-12-31"
851
859
  if not stamp or stamp[5:] not in ("03-31", "06-30", "09-30", "12-31"):
852
860
  raise ValueError("dividend report_date must be a quarter end")
853
- rows = dataset(f"dividend-ranking:{stamp}", lambda: ak.stock_fhps_em(date=stamp.replace("-", "")))
861
+ base = f"(REPORT_DATE='{stamp}')(ASSIGN_PROGRESS=\"实施分配\")"
862
+ if codes is None:
863
+ queries = [(base, top)]
864
+ else:
865
+ codes = [c for c in codes if re.fullmatch(r"\d{6}", str(c))]
866
+ chunks = [codes[i : i + 200] for i in range(0, len(codes), 200)]
867
+ queries = [(base + "(SECURITY_CODE in (" + ",".join(f'"{c}"' for c in chunk) + "))", 500) for chunk in chunks]
868
+ rows = []
869
+ for condition, size in queries:
870
+ rows += _em_datacenter("RPT_SHAREBONUS_DET", condition, "DIVIDENT_RATIO", size)[1]
854
871
  return {
855
872
  "report_date": stamp,
856
873
  "source": "eastmoney",
857
874
  "yield_basis": "provider report-period cash dividend yield, percent",
858
875
  "items": [
859
876
  {
860
- "symbol": str(r.get("代码", "")).zfill(6),
861
- "name": r.get("名称"),
877
+ "symbol": str(r.get("SECURITY_CODE", "")).zfill(6),
878
+ "name": r.get("SECURITY_NAME_ABBR"),
862
879
  # Eastmoney reports this ratio as a fraction (0.0101 = 1.01%).
863
- "dividend_yield": round(number(r.get("现金分红-股息率")) * 100, 6),
864
- "ex_date": iso(r.get("除权除息日")),
865
- "announcement_date": iso(r.get("最新公告日期")),
866
- "status": r.get("方案进度"),
880
+ "dividend_yield": round(number(r.get("DIVIDENT_RATIO")) * 100, 6),
881
+ "ex_date": iso(r.get("EX_DIVIDEND_DATE")),
882
+ "announcement_date": iso(r.get("NOTICE_DATE")),
883
+ "status": r.get("ASSIGN_PROGRESS"),
867
884
  }
868
885
  for r in rows
869
- if r.get("方案进度") == "实施分配" and number(r.get("现金分红-股息率")) is not None
886
+ if number(r.get("DIVIDENT_RATIO")) is not None
870
887
  ],
871
888
  }
872
889
 
@@ -877,7 +894,7 @@ def dividends(args):
877
894
  if args.mode == "ranking":
878
895
  if args.symbol:
879
896
  raise ValueError("ranking covers all A shares; omit symbol")
880
- result = dividend_ranking(args.report_date, getattr(args, "market", "A"))
897
+ result = dividend_ranking(args.report_date, getattr(args, "market", "A"), top=args.top)
881
898
  result["items"] = sorted(result["items"], key=lambda r: r["dividend_yield"], reverse=True)[: args.top]
882
899
  return result
883
900
  market = detect_market(args.symbol)
@@ -1113,12 +1130,8 @@ def tracking_error(nav, benchmark):
1113
1130
 
1114
1131
 
1115
1132
  def fund_size_history(symbol):
1116
- import requests
1117
-
1118
1133
  def fetch():
1119
- response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15)
1120
- response.raise_for_status()
1121
- match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", response.text, re.S)
1134
+ match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", fund_pingzhong_js(symbol), re.S)
1122
1135
  if not match:
1123
1136
  raise ValueError("fund scale history unavailable")
1124
1137
  data = json.loads(match.group(1))