tradingSystem/research/liquidity_relief_20261120/data_extract.py

444 lines
20 KiB
Python
Raw Normal View History

"""只读取155既有指数行情及正规Tushare接口,在本机生成收盘数据。"""
import argparse
import csv
import hashlib
import inspect
import json
import statistics
import subprocess
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
EPISODES = HERE.parent / "liquidity_tail_20261120/episodes.csv"
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "-p", "2280", "factor@192.168.16.155"]
INDEX_COLS = ["date", "open", "high", "low", "close", "amount_yuan"]
def remote_index():
import os
import json
import pymysql
from sqlalchemy.engine import make_url
from config.settings import settings
if settings.PMS_TABLE_PREFIX or os.environ.get("PMS_STACK_PREFIX", ""):
raise ValueError("实例必须为155模拟PMS")
u = make_url(settings.DB_MYSQL_URL)
with pymysql.connect(
host=u.host,
port=u.port or 3306,
user=u.username,
password=u.password,
database=u.database,
connect_timeout=5,
read_timeout=30,
) as cn:
with cn.cursor() as cursor:
cursor.execute(
"SELECT timestamp,open,high,low,close,amount FROM zs_day_data "
"WHERE symbol=%s AND timestamp >= %s AND timestamp < %s ORDER BY timestamp",
("932000.CSI", "2023-10-01", "2026-11-10"),
)
print(
json.dumps(
[
[str(d.date()), float(o), float(h), float(l), float(c), float(a) * 1000]
for d, o, h, l, c, a in cursor
],
allow_nan=False,
)
)
def remote_reference_index():
from app.core.config import settings
import tushare as ts
pro = ts.pro_api(settings.TUSHARE_TOKEN, timeout=20)
result = pro.index_daily(
ts_code="932000.CSI",
start_date="20231001",
end_date="20261109",
fields="trade_date,ts_code,close,amount",
)
print("DATA " + result.sort_values("trade_date").to_json(orient="records"), flush=True)
def remote_flow(dates):
import bisect
import calendar
import datetime
import hashlib
import json
import math
import re
import time
import pandas as pd
import tushare as ts
from app.core.config import settings
pro = ts.pro_api(settings.TUSHARE_TOKEN, timeout=20)
symbol = r"(?:60[0-9]{4}|68[0-9]{4})\.SH|(?:00[0-9]{4}|30[0-9]{4})\.SZ"
large = ["buy_lg_amount", "buy_elg_amount", "sell_lg_amount", "sell_elg_amount"]
flow_fields = large + ["net_mf_amount"]
def fetch(api, **params):
for attempt in range(4):
try:
return pro.query(api, **params)
except Exception as exc:
if attempt == 3:
raise RuntimeError(f"{api}失败,异常类型{type(exc).__name__}") from None
time.sleep(3 * (attempt + 1))
def safe_emit(kind, payload):
print("DATA " + json.dumps([kind, payload], allow_nan=False), flush=True)
months = set()
for day in dates:
current = datetime.date.fromisoformat(day).replace(day=1)
last = (current - datetime.timedelta(days=1)).replace(day=1)
months.update([last, current])
snapshots = {}
for start in sorted(months):
end = start.replace(day=calendar.monthrange(start.year, start.month)[1])
parts = []
for offset in range(0, 24000, 5000):
part = fetch(
"index_weight",
index_code="932000.CSI",
start_date=start.strftime("%Y%m%d"),
end_date=end.strftime("%Y%m%d"),
fields="index_code,trade_date,con_code",
offset=offset,
limit=5000,
)
parts.append(part)
if len(part) < 5000:
break
else:
raise ValueError("成分快照页数超出区间")
weights = pd.concat(parts, ignore_index=True)
if weights.empty:
continue
if not weights.index_code.eq("932000.CSI").all():
raise ValueError("指数成分来源错误")
for date, group in weights.groupby("trade_date"):
securities = group.loc[group.con_code.str.fullmatch(symbol), "con_code"]
names = set(securities)
source_count = int(group.con_code.nunique())
valid = bool(names) and source_count == 2000
snapshots[date] = names if valid else None
safe_emit(
"snapshot",
{
"date": date,
"count": len(names),
"source_count": source_count,
"complete_source": valid,
"all_members_in_scope": len(names) == source_count,
"repeated_member_rows": int(securities.duplicated().sum()),
"sha256": hashlib.sha256("\n".join(sorted(names)).encode()).hexdigest(),
},
)
history = sorted(snapshots)
for date_iso in dates:
day = date_iso.replace("-", "")
i = bisect.bisect_right(history, day) - 1
if i < 0 or not snapshots[history[i]]:
safe_emit("day", {"date": date_iso, "status": "无完整的历史成分快照"})
continue
stamp, basket = history[i], snapshots[history[i]]
calendar_age = (
datetime.date.fromisoformat(date_iso) - datetime.datetime.strptime(stamp, "%Y%m%d").date()
).days
if calendar_age > 45:
safe_emit("day", {"date": date_iso, "status": "已有成分快照超过45个自然日"})
continue
funds = fetch(
"moneyflow", trade_date=day, fields="ts_code,trade_date," + ",".join(flow_fields), limit=6000
)
prices = fetch("daily", trade_date=day, fields="ts_code,trade_date,amount", limit=6000)
if len(funds) >= 6000 or len(prices) >= 6000 or funds.empty or prices.empty:
raise ValueError(f"{day}资金或行情截面为空或达到接口上限")
# 只保留已知月末沪深2000成分;无关证券不会导出或补查。
fp = funds[funds.ts_code.isin(basket)].set_index("ts_code", verify_integrity=True)
px = prices[prices.ts_code.isin(basket)].set_index("ts_code", verify_integrity=True)
if not (fp.trade_date.eq(day).all() and px.trade_date.eq(day).all()):
raise ValueError("源日期错误")
turnover = pd.to_numeric(px.amount, errors="coerce") * 1000
if not turnover.map(math.isfinite).all() or turnover.lt(0).any():
raise ValueError("个股成交额不可用")
traded = turnover[turnover.gt(0)]
funds_only = fp.index.difference(traded.index)
extra_flow = fp.loc[funds_only, flow_fields].fillna(0).abs().sum(axis=1).gt(0)
# 若有资金记录却无成交行情,不能把该日缺失额当作零界。
amount_unknown = bool(extra_flow.any())
ob = fp.reindex(traded.index)[flow_fields].apply(pd.to_numeric, errors="coerce")
main_valid = ob[large].notna().all(axis=1)
active_valid = ob.net_mf_amount.notna()
row = {
"date": date_iso,
"member_snapshot_date": datetime.datetime.strptime(stamp, "%Y%m%d").date().isoformat(),
"member_count": len(basket),
"source_member_count": 2000,
"traded_members": len(traded),
"flow_observed_members": int(main_valid.sum()),
"active_flow_observed_members": int(active_valid.sum()),
"members_without_daily_quote": len(basket) - len(px),
"funds_nonzero_without_traded_quote": int(extra_flow.sum()),
"member_turnover_yuan": round(float(traded.sum()), 2),
"snapshot_exact": day == stamp,
"status": "月末成分实测" if day == stamp else "最近已知月末成分",
}
for label, valid, series in (
("main", main_valid, ob[large[0]] + ob[large[1]] - ob[large[2]] - ob[large[3]]),
("active", active_valid, ob.net_mf_amount),
):
missing = round(float(traded[~valid].sum()), 2)
observed = round(float(series[valid].sum()) * 10000, 2) if valid.any() else None
row["missing_turnover_yuan" if label == "main" else "active_missing_turnover_yuan"] = (
None if amount_unknown else missing
)
row[label + "_net_observed_yuan"] = observed
row[label + "_net_yuan"] = observed if missing == 0 and not amount_unknown else None
row[label + "_net_lower_yuan"] = (
None if amount_unknown or observed is None else round(observed - missing, 2)
)
row[label + "_net_upper_yuan"] = (
None if amount_unknown or observed is None else round(observed + missing, 2)
)
safe_emit("day", row)
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def target_dates(index, episodes):
days = [r[0] for r in index]
targets = set()
for event in episodes:
left, right = days.index(event["start"]), days.index(event["end"])
targets.update(days[max(0, left - 20) : right + 6])
return sorted(targets)
def acquire(cache, dates):
temp = cache / "flow_records.jsonl"
existing = [json.loads(line) for line in temp.read_text().splitlines()] if temp.exists() else []
done = {value["date"] for tag, value in existing if tag == "day" and value.get("member_count")}
needed = sorted(set(dates) - done)
if not needed:
return
code = inspect.getsource(remote_flow) + "\nremote_flow(" + repr(needed) + ")\n"
with tempfile.TemporaryFile(mode="w+") as program:
program.write(code)
program.seek(0)
process = subprocess.Popen(
SSH + ["docker exec -i quant_api python -B -"], stdin=program, stdout=subprocess.PIPE, text=True
)
with temp.open("a") as out:
for line in process.stdout:
if line.startswith("DATA "):
json.loads(line[5:])
out.write(line[5:])
out.flush()
if process.wait():
raise RuntimeError("既有资金接口只读查询未完成,可用原缓存重试")
def turnover_diagnostic(rows):
observations = [r for r in rows if r.get("member_turnover_yuan") is not None]
groups = {
"all": observations,
"june_and_december": [r for r in observations if r["date"][5:7] in ("06", "12")],
"other_months": [r for r in observations if r["date"][5:7] not in ("06", "12")],
"exact_snapshot_dates": [r for r in observations if r["snapshot_exact"]],
"2024": [r for r in observations if r["date"].startswith("2024")],
"2026": [r for r in observations if r["date"].startswith("2026")],
}
results = {}
for name, sample in groups.items():
if not sample:
results[name] = {"days": 0}
continue
gaps = [abs(r["turnover_gap_fraction"]) for r in sample]
results[name] = {
"days": len(sample),
"inside_rounding_bound": sum(
abs(r["member_turnover_yuan"] - r["amount_yuan"]) <= 1000 + r["traded_members"]
for r in sample
),
"within_one_basis_point": sum(x <= 0.0001 for x in gaps),
"within_one_tenth_percent": sum(x <= 0.001 for x in gaps),
"within_one_percent": sum(x <= 0.01 for x in gaps),
"median_absolute_relative_gap": statistics.median(gaps),
"max_absolute_relative_gap": max(gaps),
"max_gap_date": sample[gaps.index(max(gaps))]["date"],
"median_absolute_gap_yuan": statistics.median(
abs(r["member_turnover_yuan"] - r["amount_yuan"]) for r in sample
),
}
return {
"adjustment_months_actually_observed": sorted({r["date"][:7] for r in groups["june_and_december"]}),
"rounding_bound_yuan": "1000元指数库原始整数千元+每只有成交成员1元(个股接口千元保留三位小数)。近似一致可作经济覆盖对照,同额也不证明成分逐只相同。",
"comparisons": results,
}
def verify_index(cache, index):
path = cache / "index_comparison.txt"
source_rows = json.loads(next(line[5:] for line in path.open() if line.startswith("DATA ")))
compare = {item["trade_date"]: item for item in source_rows}
if len(source_rows) != len(compare) or any(r["ts_code"] != "932000.CSI" for r in source_rows):
raise ValueError("指数供应商复核出现重复日期或错误证券")
deltas, prices = [], []
for d, o, h, l, c, amount in index:
other = compare[d.replace("-", "")]
deltas.append(abs(amount - 1000 * other["amount"]))
prices.append(abs(c - other["close"]))
report = {
"source": "Tushare index_daily 932000.CSI,与项目zs_day_data同日收盘及原始成交额两条取数路径核对",
"matched_dates": len(deltas),
"provider_dates": len(compare),
"max_close_difference": max(prices),
"max_amount_difference_yuan": max(deltas),
"median_amount_difference_yuan": statistics.median(deltas),
"within_half_thousand_yuan": sum(d <= 500.001 for d in deltas),
}
if len(index) != len(compare) or max(prices) > 0.0001 or max(deltas) > 500.001:
raise ValueError("两条指数取数路径超出整数千元取整边界")
return report
def assemble(cache, index, targets):
lines = cache / "flow_records.jsonl"
records = [json.loads(s) for s in lines.read_text().splitlines()] if lines.exists() else []
addenda = {r["date"]: r for tag, r in records if tag == "day"}
snapshots = {r["date"]: r for tag, r in records if tag == "snapshot"}
for record in snapshots.values():
if record.get("complete") and "source_count" not in record:
record["source_count"] = record["count"]
record["complete_source"] = True
record["all_members_in_scope"] = True
record.pop("complete", None)
rows = []
columns = INDEX_COLS + [
"member_snapshot_date",
"member_count",
"traded_members",
"flow_observed_members",
"source_member_count",
"active_flow_observed_members",
"members_without_daily_quote",
"funds_nonzero_without_traded_quote",
"member_turnover_yuan",
"missing_turnover_yuan",
"active_missing_turnover_yuan",
"main_net_yuan",
"active_net_yuan",
"main_net_observed_yuan",
"active_net_observed_yuan",
"main_net_lower_yuan",
"main_net_upper_yuan",
"active_net_lower_yuan",
"active_net_upper_yuan",
"snapshot_exact",
"universe_complete",
"turnover_gap_fraction",
"status",
]
for values in index:
r = dict(zip(INDEX_COLS, values))
r.update(addenda.get(r["date"], {}))
if r.get("member_count") and not r.get("source_member_count"):
r["source_member_count"] = 2000
if r.get("member_count"):
r["universe_complete"] = r["member_count"] == r["source_member_count"]
if not r["universe_complete"]:
r["status"] = "同日快照的沪深成分" if r["snapshot_exact"] else "最近月末已知沪深成分"
if r.get("member_turnover_yuan") is not None:
r["turnover_gap_fraction"] = r["member_turnover_yuan"] / r["amount_yuan"] - 1
rows.append(r)
path = HERE / "index_data.csv"
with path.open("w") as stream:
writer = csv.DictWriter(stream, fieldnames=columns, lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
source = {
"index": "155模拟PMS的DB_MYSQL_URL只读单表zs_day_data,symbol=932000.CSI。成交额源字段amount为千元,本表乘1000。2024-02-05与供应商index_daily抽查为183742353及183742353.42千元。",
"constituents": "Tushare index_weight,每月逐次读取2000只历史成分。仅用观察日当时最近已知的月末成分,原始样本数量须为2000;逐股数据仅使用快照中可识别沪深成分,实际数量见member_count。两者数量有差异时,资金汇总只代表沪深子集。超过45个自然日不使用。snapshot_exact为当日有实际快照。其他日期跟踪已知篮子,未取得逐日官方增删名录。快照可用时点按记录经济日期处理,未逐条核实供应商当日入库时刻。",
"flow": "Tushare moneyflow,主动买卖单的大单(20万至100万元)与特大单(不低于100万元)买入减卖出为main;active直接用供应商全档net_mf_amount。万元换元,不加权按股求和。ETF、申购以及历史价格走势不参与推算。",
"coverage": "逐日与Tushare daily的成员成交额交叉核对,仅有成交者有资金要求。无成交行情和无资金行的成员可能停牌,也可能源同时漏数,不直接认定已证实停牌。若存在非零资金却无成交行情,则不公布完整净额和上下界。缺失成交额的上下界只覆盖有价、缺资金者;范围外证券、可能的月内调样和两源同时漏数不包含在此上下界。",
"docs": [
"https://tushare.pro/document/2?doc_id=170",
"https://tushare.pro/document/2?doc_id=96",
"https://tushare.pro/document/2?doc_id=95",
],
"daily_rows": len(rows),
"first": rows[0]["date"],
"last": rows[-1]["date"],
"target_dates": len(targets),
"obtained_target_dates": len(set(targets) & addenda.keys()),
"funds_valid": sum(r.get("main_net_yuan") is not None for r in rows),
"active_valid": sum(r.get("active_net_yuan") is not None for r in rows),
"exact_snapshot_dates": sum(r.get("snapshot_exact", False) for r in rows),
"turnover_crosscheck": turnover_diagnostic(rows),
"index_rounding_crosscheck": verify_index(cache, index),
"requested_window": "既有9个低位段,每段前20个交易日到其结束后第5个交易日。",
"snapshots": sorted(snapshots.values(), key=lambda r: r["date"]),
"index_sha256": sha(cache / "index.json"),
"index_data_sha256": sha(path),
"episodes_sha256": sha(EPISODES),
}
(HERE / "data_coverage.json").write_text(json.dumps(source, ensure_ascii=False, indent=2) + "\n")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cache", type=Path, required=True)
parser.add_argument("--assemble-only", action="store_true")
args = parser.parse_args()
args.cache.mkdir(parents=True, exist_ok=True)
file = args.cache / "index.json"
if not file.exists() and not args.assemble_only:
result = subprocess.run(
SSH + ["docker exec -i pms-web python -B -"],
input=inspect.getsource(remote_index) + "\nremote_index()\n",
capture_output=True,
check=True,
text=True,
)
json.loads(result.stdout)
file.write_text(result.stdout)
index = json.loads(file.read_text())
if len(set(row[0] for row in index)) != len(index) or sorted(index) != index:
raise ValueError("指数日线日期不唯一或次序错误")
for d, o, h, l, c, a in index:
if not (0 < l <= min(o, c) <= max(o, c) <= h and a > 0):
raise ValueError("指数日线无效:" + d)
with EPISODES.open(encoding="utf-8-sig") as f:
episodes = list(csv.DictReader(f))
targets = target_dates(index, episodes)
reference = args.cache / "index_comparison.txt"
if not reference.exists() and not args.assemble_only:
result = subprocess.run(
SSH + ["docker exec -i quant_api python -B -"],
input=inspect.getsource(remote_reference_index) + "\nremote_reference_index()\n",
capture_output=True,
check=True,
text=True,
)
reference.write_text(result.stdout)
if not args.assemble_only:
acquire(args.cache, targets)
assemble(args.cache, index, targets)
if __name__ == "__main__":
main()