tradingSystem/research/liquidity_tail_20261120/market_data.py

191 lines
11 KiB
Python
Raw Normal View History

"""从本地逐股日线生成沪深交易股票等权收益。2020 年用于识别已有行情。"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pyarrow.compute as pc
import pyarrow.dataset as ds
HERE = Path(__file__).resolve().parent
SOURCE = HERE.parents[2] / "quant_factor_service/data/parquet_cache/gp_day_data"
CALENDAR = HERE.parent / "macro_grid_20261029/results/features_000300.SH.json.gz"
SYMBOL_RE = r"^(SH(600|601|603|605|688)|SZ(000|001|002|003|300|301|302))[0-9]{3}$"
COVERAGE_FRACTION = 0.90
REFERENCE_DAYS = 20
COLUMNS = ["stock_code", "trade_date", "close", "pre_close", "amount", "volume"]
GROUPS = ["SH", "SZ"]
EXTERNAL_AUDIT = (HERE.parents[2] / "quant_factor_service/backend/scripts/results"
/ "preparation_final_20261013")
SOURCE_COVERAGE = EXTERNAL_AUDIT.parent / "p14_p9_20260928/README.md"
def sha256(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def read_calendar():
with gzip.open(CALENDAR, "rt") as stream:
rows = json.load(stream)["data"]
return pd.DatetimeIndex([row["timestamp"][:10] for row in rows], name="date")
def read_year(path, calendar, seen, last_prices):
# 源符号已经带交易所前缀。过滤发生在逐年数据读取入口。
dataset = ds.dataset(path, format="parquet")
frame = dataset.to_table(
columns=COLUMNS,
filter=pc.match_substring_regex(ds.field("stock_code"), pattern=SYMBOL_RE),
).to_pandas()
frame["date"] = pd.to_datetime(frame.pop("trade_date"))
on_calendar = frame.date.isin(calendar)
audit = {"input": str(path), "sha256": sha256(path),
"off_calendar_rows": int((~on_calendar).sum())}
frame = frame.loc[on_calendar].copy()
frame = frame.drop_duplicates()
conflicts = frame.duplicated(["stock_code", "date"], keep=False)
audit["conflicting_price_or_volume_rows"] = int(conflicts.sum())
conflict_counts = frame.loc[conflicts, ["date", "stock_code"]].drop_duplicates().groupby("date").size()
frame = frame.loc[~conflicts].sort_values(["stock_code", "date"])
source_quotes = frame.groupby("date").size()
audit["asset_count_with_trading_records"] = int(frame.stock_code.nunique())
price_fields = frame[["close", "pre_close"]]
valid_prices = np.isfinite(price_fields).all(axis=1) & price_fields.gt(0).all(axis=1)
trade_fields = frame[["volume", "amount"]]
traded = np.isfinite(trade_fields).all(axis=1) & trade_fields.gt(0).all(axis=1)
# 首个有成交且收盘有效的观察建立身份,包括首日昨收无效者。
observed = traded & np.isfinite(frame.close) & frame.close.gt(0)
first = observed & ~frame.stock_code.isin(seen)
first_indices = frame.loc[first].groupby("stock_code", sort=False).head(1).index
seen.update(frame.loc[observed, "stock_code"].unique())
include = valid_prices & traded & ~frame.index.isin(first_indices)
used = frame.loc[include, ["date", "stock_code", "close", "pre_close"]].copy()
used["return"] = used.close.astype("float64") / used.pre_close.astype("float64") - 1
used["exchange"] = used.stock_code.str[:2]
# 诊断历年拼接处两种昨收是否一致;主口径始终用本行的昨收。
traded_prices = frame.loc[observed, ["stock_code", "date", "close", "pre_close"]]
year_first = traded_prices.groupby("stock_code", sort=False).head(1)
prior = year_first.stock_code.map(last_prices)
valid_bridge = prior.gt(0) & year_first.pre_close.gt(0)
diffs = (year_first.loc[valid_bridge, "pre_close"] / prior.loc[valid_bridge] - 1).abs()
last_prices.update(traded_prices.groupby("stock_code", sort=False).close.last().to_dict())
reference = json.loads((EXTERNAL_AUDIT / "daily_input_differences.json").read_text())
checked = []
for item in reference:
code, day = item["stock"], pd.Timestamp(item["date"])
if day.year != int(path.stem[-4:]):
continue
normalized = code[-2:] + code[:6]
if not item["price"] or item["price"].get("pct_chg") is None:
continue
match = used[(used.stock_code == normalized) & (used.date == day)]
if len(match) == 1:
reported = float(item["price"]["pct_chg"]) / 100
measured = float(match["return"].iloc[0])
checked.append({"stock": code, "date": day.strftime("%Y-%m-%d"),
"cache_return": measured, "independent_reported_return": reported,
"absolute_difference": abs(measured-reported)})
audit["selected_vendor_pct_chg_comparisons"] = checked
audit["year_boundary_prev_close_checks"] = int(len(diffs))
audit["year_boundary_prev_close_differences_over_one_percent"] = int((diffs > .01).sum())
audit["eligible_traded_rows_with_abs_return_gt_100pct"] = int((used["return"].abs() > 1).sum())
audit["example_largest_absolute_returns"] = [
{"date": row.date.strftime("%Y-%m-%d"), "stock": row.stock_code,
"close": float(row.close), "pre_close": float(row.pre_close), "return": float(row.daily_return)}
for row in used.loc[used["return"].abs().nlargest(3).index]
.rename(columns={"return": "daily_return"}).itertuples()
]
grouped = used.groupby("date")
daily = grouped["return"].agg(market_return="mean", stock_count="size")
split = used.groupby(["date", "exchange"]).size().unstack(fill_value=0)
daily = daily.join(split.rename(columns={g: "stocks_" + g for g in GROUPS}), how="outer")
daily["quote_count"] = source_quotes
daily["no_trade_or_invalid_amount_count"] = (~traded).groupby(frame.date).sum()
daily["invalid_price_on_traded_count"] = (traded & ~valid_prices).groupby(frame.date).sum()
daily["first_valid_print_count"] = frame.loc[frame.index.isin(first_indices)].groupby("date").size()
daily["conflicting_symbol_count"] = conflict_counts
return daily, audit, frame.date.max()
def build(source, output):
calendar = read_calendar()
all_days, years, seen, last_prices = [], {}, set(), {}
latest = None
for path in sorted(source.glob("year_*.parquet")):
year = int(path.stem[-4:])
if year < 2020:
continue
daily, audit, latest = read_year(path, calendar, seen, last_prices)
all_days.append(daily)
years[year] = audit
if not all_days or latest is None:
raise ValueError("股票行情缓存为空")
frame = pd.concat(all_days).reindex(calendar[(calendar.year >= 2020) & (calendar <= latest)])
count_columns = [col for col in frame if col != "market_return"]
frame[count_columns] = frame[count_columns].fillna(0).astype("int64")
for column in ["stock_count", "stocks_SH", "stocks_SZ"]:
baseline = frame[column].rolling(REFERENCE_DAYS, min_periods=REFERENCE_DAYS).median().shift(1)
frame["coverage_" + column] = frame[column].div(baseline.where(baseline > 0))
coverage_columns = ["coverage_" + c for c in ["stock_count", "stocks_SH", "stocks_SZ"]]
valid = frame[coverage_columns].ge(COVERAGE_FRACTION).all(axis=1) & frame.market_return.notna()
frame.loc[~valid, "market_return"] = np.nan
frame["coverage_valid"] = valid
# 每个连续有效段的第一行净值等于 1+该日收益;缺日后的新段不能和先前段相除。
blocks = (~valid).cumsum()
frame["market_nav"] = (1 + frame.market_return).groupby(blocks).cumprod()
frame["series_segment"] = (valid & ~valid.shift(fill_value=False)).cumsum().where(valid)
frame = frame.loc["2020-11-01":].copy() # 留训练开始前的5日路径及覆盖检查所需历史。
ordered = ["market_return", "market_nav", "stock_count", "coverage_valid", "series_segment"]
output.mkdir(exist_ok=True, parents=True)
file_path = output / "market_daily.csv"
frame[ordered + [c for c in frame if c not in ordered]].to_csv(file_path, float_format="%.13g")
missing = frame.loc[~frame.coverage_valid, ["stock_count", "stocks_SH", "stocks_SZ"]]
current = frame.iloc[-1]
delisted = json.loads((EXTERNAL_AUDIT / "delisted_by_stock.json").read_text())
relevant = [r for r in delisted if r["is_a_share"] and
r["endpoints"]["daily"]["last"] >= "20200101"]
delisting_audit = {
"scope": "上游冻结2014—2024年沪深退市股205只,本地仅核对独立数据源在2020年起仍有日线者。",
"securities_with_overlapping_history_in_independent_source": len(relevant),
"with_any_traded_quote_in_local_history": sum(r["code"] in seen for r in relevant),
"evidence": str(EXTERNAL_AUDIT / "delisted_by_stock.json"),
"evidence_sha256": sha256(EXTERNAL_AUDIT / "delisted_by_stock.json"),
"prior_full_universe_check": str(SOURCE_COVERAGE),
"comparison_price_fields": str(EXTERNAL_AUDIT / "daily_input_differences.json"),
"comparison_price_fields_sha256": sha256(EXTERNAL_AUDIT / "daily_input_differences.json"),
}
summary = {
"source_type": "本地同日撮合日线,前复权历史版本,缺失覆盖和停牌不补零",
"symbol_filter_at_read": SYMBOL_RE,
"population": "沪深普通A股含可交易ST。科创板存托凭证、B股、基金、北交所不计。以该日可观测成交且有先前成交的股票等权计算,不用当前存续名单。",
"returns": "同日close/pre_close-1,以提供方除权后昨收为参照,避免跨年份复权基准混用。不另乘复权因子,不插值、不缩尾。",
"observability": "相同股票日完全一致的资料去重;字段冲突则去除此股票日。非正或缺失量额视为未确认成交。首个有收盘的成交日为发行日或首次可见日,不计收益。停牌与未采集在无行时无法逐只区分。",
"history_limits": "独立源可见多只历史退市股在本地无价。上游名单审计也确认2021年部分在市老股的左截断。此等权序列代表资料可观测样本,无法覆盖所有历史在市沪深A股,尾部可能受幸存者偏差影响。历史复权为当前缓存版本。",
"delisted_overlap_audit": delisting_audit,
"calendar": str(CALENDAR), "calendar_sha256": sha256(CALENDAR),
"coverage_guard": "当日总计和沪深各自有效股票数不得低于此前20个交易日中位数的90%。不足或缺日时收益、净值留空,连续段编号重启,不跨段判定。",
"start": str(frame.index.min().date()), "last_observed_stock_date": str(latest.date()),
"last_coverage_valid_date": str(frame.index[frame.coverage_valid][-1].date()),
"last_stock_count": int(current.stock_count), "last_SH_count": int(current.stocks_SH),
"last_SZ_count": int(current.stocks_SZ),
"last_total_relative_coverage": float(current.coverage_stock_count),
"incomplete_calendar_dates": {str(k.date()): {c: int(v) for c, v in row.items()}
for k, row in missing.iterrows()},
"annual_sources": years, "market_daily_sha256": sha256(file_path),
}
(output / "market_coverage.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, default=SOURCE)
parser.add_argument("--output", type=Path, default=HERE)
args = parser.parse_args()
build(args.source, args.output)