stock-analysis-plugin 0.2.12 → 0.2.13

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,15 @@ 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
+ normalize_stock_code,
30
+ )
23
31
  from trading_calendar import _MARKET_TZ, market_now
24
32
 
25
33
  YF_MARKETS = ("US", "JP", "KR", "TW")
@@ -395,10 +403,7 @@ def hk_board_meetings(board):
395
403
 
396
404
 
397
405
  def earnings_calendar(args):
398
- import akshare as ak
399
-
400
406
  stamp = iso(args.report_date)
401
- suffix = {"03-31": "一季", "06-30": "半年报", "09-30": "三季", "12-31": "年报"}
402
407
  if not 1 <= args.top <= 500 or (args.report_date and not stamp):
403
408
  raise ValueError("report_date must be a valid date and top must be in 1..500")
404
409
  market = detect_market(args.symbol) if args.symbol else "A"
@@ -470,37 +475,38 @@ def earnings_calendar(args):
470
475
  + ["provider-only schedules have unverified fiscal periods and are not assigned to requested report_date"],
471
476
  "as_of": today,
472
477
  }
473
- if not stamp or stamp[5:] not in suffix:
478
+ if not stamp or stamp[5:] not in ("03-31", "06-30", "09-30", "12-31"):
474
479
  raise ValueError("report_date must be a quarter end for A-share earnings calendars")
475
480
  symbol = ""
476
481
  if args.symbol:
477
482
  market, symbol = stock_identity(args.symbol)
478
483
  if market != "A":
479
484
  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
- )
485
+ result = {"report_date": stamp, "source": "eastmoney"}
486
+ # Server-side filter + limit: one page holds the requested rows, `count` the full total.
487
+ condition = f"(REPORT_DATE='{stamp}')" + (f'(SECURITY_CODE="{symbol}")' if symbol else "")
488
+ totals = {}
489
+ queries = {
490
+ "disclosures": ("RPT_PUBLIC_BS_APPOIN", "APPOINT_PUBLISH_DATE,SECURITY_CODE", "1,1"),
491
+ "forecasts": ("RPT_PUBLIC_OP_NEWPREDICT", "NOTICE_DATE,SECURITY_CODE", "-1,-1"),
492
+ }
493
+ for key, (report, sort, order) in queries.items():
494
+
495
+ def fetch(report=report, sort=sort, order=order, key=key):
496
+ totals[key], rows = _em_datacenter(report, condition, sort, args.top, order)
497
+ return rows
498
+
499
+ capture(result, key, fetch)
492
500
  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
501
  output = []
497
- for row in rows:
498
- item = {"symbol": str(row.get("股票代码", "")).zfill(6), "name": row.get("股票简称")}
502
+ for row in result.get(key, []):
503
+ item = {"symbol": str(row.get("SECURITY_CODE", "")).zfill(6), "name": row.get("SECURITY_NAME_ABBR")}
499
504
  if key == "disclosures":
500
- revised = [iso(row.get(c)) for c in ("首次预约", "初次变更", "二次变更", "三次变更")]
505
+ columns = ("FIRST_APPOINT_DATE", "FIRST_CHANGE_DATE", "SECOND_CHANGE_DATE", "THIRD_CHANGE_DATE")
506
+ revised = [iso(row.get(c)) for c in columns]
501
507
  item.update(
502
508
  scheduled_date=next((d for d in reversed(revised) if d), None),
503
- actual_date=iso(row.get("实际披露")),
509
+ actual_date=iso(row.get("ACTUAL_PUBLISH_DATE")),
504
510
  original_scheduled_date=revised[0],
505
511
  scheduled_date_revisions=[
506
512
  {"revision": i, "scheduled_date": d} for i, d in enumerate(revised[1:], 1) if d
@@ -508,16 +514,16 @@ def earnings_calendar(args):
508
514
  )
509
515
  else:
510
516
  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("业绩变动原因"),
517
+ announcement_date=iso(row.get("NOTICE_DATE")),
518
+ forecast_type=row.get("PREDICT_TYPE"),
519
+ indicator=row.get("PREDICT_FINANCE"),
520
+ forecast_value=number(row.get("FORECAST_JZ")),
521
+ change_pct=number(row.get("INCREASE_JZ")),
522
+ reason=row.get("CHANGE_REASON_EXPLAIN"),
517
523
  )
518
524
  output.append(item)
519
- result[key + "_total"] = len(output)
520
- result[key] = output[: args.top]
525
+ result[key + "_total"] = totals.get(key, 0)
526
+ result[key] = output
521
527
  if result.get("warnings") and not result["disclosures"] and not result["forecasts"]:
522
528
  raise ValueError("earnings calendar sources unavailable")
523
529
  return result
@@ -840,9 +846,10 @@ def hk_dividend_ranking(report_date=""):
840
846
  return cached(f"hk-dividend-ranking:{stamp}", DAY, fetch)
841
847
 
842
848
 
843
- def dividend_ranking(report_date="", market="A"):
844
- import akshare as ak
849
+ def dividend_ranking(report_date="", market="A", top=500, codes=None):
850
+ """Implemented cash-dividend plans ranked by yield, sorted and limited server-side.
845
851
 
852
+ `codes` (A only) restricts the query to those stocks — the screener asks only for its candidates."""
846
853
  if market == "HK":
847
854
  return hk_dividend_ranking(report_date)
848
855
  if market != "A":
@@ -850,23 +857,32 @@ def dividend_ranking(report_date="", market="A"):
850
857
  stamp = iso(report_date) if report_date else f"{_cn_now().date().year - 1}-12-31"
851
858
  if not stamp or stamp[5:] not in ("03-31", "06-30", "09-30", "12-31"):
852
859
  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("-", "")))
860
+ base = f"(REPORT_DATE='{stamp}')(ASSIGN_PROGRESS=\"实施分配\")"
861
+ if codes is None:
862
+ queries = [(base, top)]
863
+ else:
864
+ codes = [c for c in codes if re.fullmatch(r"\d{6}", str(c))]
865
+ chunks = [codes[i : i + 200] for i in range(0, len(codes), 200)]
866
+ queries = [(base + "(SECURITY_CODE in (" + ",".join(f'"{c}"' for c in chunk) + "))", 500) for chunk in chunks]
867
+ rows = []
868
+ for condition, size in queries:
869
+ rows += _em_datacenter("RPT_SHAREBONUS_DET", condition, "DIVIDENT_RATIO", size)[1]
854
870
  return {
855
871
  "report_date": stamp,
856
872
  "source": "eastmoney",
857
873
  "yield_basis": "provider report-period cash dividend yield, percent",
858
874
  "items": [
859
875
  {
860
- "symbol": str(r.get("代码", "")).zfill(6),
861
- "name": r.get("名称"),
876
+ "symbol": str(r.get("SECURITY_CODE", "")).zfill(6),
877
+ "name": r.get("SECURITY_NAME_ABBR"),
862
878
  # 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("方案进度"),
879
+ "dividend_yield": round(number(r.get("DIVIDENT_RATIO")) * 100, 6),
880
+ "ex_date": iso(r.get("EX_DIVIDEND_DATE")),
881
+ "announcement_date": iso(r.get("NOTICE_DATE")),
882
+ "status": r.get("ASSIGN_PROGRESS"),
867
883
  }
868
884
  for r in rows
869
- if r.get("方案进度") == "实施分配" and number(r.get("现金分红-股息率")) is not None
885
+ if number(r.get("DIVIDENT_RATIO")) is not None
870
886
  ],
871
887
  }
872
888
 
@@ -877,7 +893,7 @@ def dividends(args):
877
893
  if args.mode == "ranking":
878
894
  if args.symbol:
879
895
  raise ValueError("ranking covers all A shares; omit symbol")
880
- result = dividend_ranking(args.report_date, getattr(args, "market", "A"))
896
+ result = dividend_ranking(args.report_date, getattr(args, "market", "A"), top=args.top)
881
897
  result["items"] = sorted(result["items"], key=lambda r: r["dividend_yield"], reverse=True)[: args.top]
882
898
  return result
883
899
  market = detect_market(args.symbol)