"""从已核验的沪深日线构建市场特征,历史分位仅用当日前60个交易日。""" import argparse import csv import gzip import hashlib import json import math from pathlib import Path from statistics import mean, median HERE = Path(__file__).resolve().parent RESEARCH = HERE.parent RELIEF = RESEARCH / "liquidity_relief_20261120" MACRO = RESEARCH / "macro_grid_20261029" / "results" CODES = {"300": "000300.SH", "500": "000905.SH", "1000": "000852.SH", "2000": "932000.CSI"} BROAD = ("300", "500", "1000") START, LAST, WINDOW = "2024-01-02", "2026-10-23", 60 def read_csv(path): with path.open(encoding="utf-8-sig", newline="") as handle: return list(csv.DictReader(handle)) def index_rows(rows): days = [row["date"] for row in rows] if days != sorted(set(days)): raise ValueError("输入交易日重复或顺序有误") return dict(zip(days, rows)) def checked_hash(path, expected, fingerprints): digest = hashlib.sha256(path.read_bytes()).hexdigest() if digest != expected: raise ValueError(f"输入与已核验版本不符 {path.name}") fingerprints[str(path.relative_to(RESEARCH))] = digest def read_sources(): hashes = {} manifest = json.loads((RELIEF / "audit.json").read_text(encoding="utf-8"))["sha256"] tables = {} for name in ("market_states_155", "daily_panel", "index_data"): path = RELIEF / f"{name}.csv" checked_hash(path, manifest[path.name], hashes) tables[name] = index_rows(read_csv(path)) files = json.loads((RESEARCH / "liquidity_tail_20261120/summary.json").read_text(encoding="utf-8")) indices = {} for size, symbol in CODES.items(): path = MACRO / f"features_{symbol}.json.gz" checked_hash(path, files["source_sha256"][str(path.relative_to(RESEARCH))], hashes) with gzip.open(path, "rt", encoding="utf-8") as handle: records = json.load(handle)["data"] rows = [] for item in records: if item["price_z"] is not None: rows.append({ "date": item["timestamp"][:10], "close": item["anchor"] + item["price_z"] * item["atr"], "activity_rank": item["volume_rank"], }) indices[size] = index_rows(rows) return tables, indices, hashes def rank(current, history): if len(history) != WINDOW or not all(math.isfinite(v) for v in [current, *history]): raise ValueError("滚动参照缺少完整交易日") return (sum(v < current for v in history) + 0.5 * history.count(current)) / WINDOW def check_equal(day, field, got, expected, tolerance=1e-11): difference = abs(got - expected) if not math.isfinite(difference) or difference > tolerance: raise ValueError(f"{day} {field} 与独立记录不符,差值 {difference}") return difference def build(end_date): tables, indices, hashes = read_sources() states, panel, raw = (tables[k] for k in ("market_states_155", "daily_panel", "index_data")) if len(panel) != 678 or (min(panel), max(panel)) != (START, LAST): raise ValueError("上轮登记的678日区间有变") if end_date not in panel: raise ValueError("截止日须为评价期内的交易日") evaluation = [day for day in panel if day <= end_date] full_calendar = list(states) start_index = full_calendar.index(START) end_index = full_calendar.index(end_date) # 首个预热日的涨跌还需要一个前收盘。 calendar = full_calendar[start_index - WINDOW - 1:end_index + 1] if calendar[WINDOW + 1:] != evaluation: raise ValueError("同版沪深等权与上轮评价日历不一致") for size in CODES: if [d for d in indices[size] if calendar[0] <= d <= end_date] != calendar: raise ValueError(f"{size}交易日与评价或预热日历不一致") if [day for day in raw if calendar[1] <= day <= end_date] != calendar[1:]: raise ValueError("中证2000原始收盘在预热或评价期有缺日") audit_path = RELIEF / "market_state_audit.json" audit = json.loads(audit_path.read_text(encoding="utf-8"))["secondary_155"] if hashes[str((RELIEF / "market_states_155.csv").relative_to(RESEARCH))] != audit["csv_sha256"]: raise ValueError("沪深等权日线与训练阈值的输入版本有异") threshold = audit["thresholds"]["q95"] history = {"dd": [], "loss": [], "relative": []} max_close_difference = 0.0 max_dd_difference = 0.0 output = [] for i, day in enumerate(calendar[1:], start=1): previous = calendar[i - 1] r_broad = mean(indices[s][day]["close"] / indices[s][previous]["close"] - 1 for s in BROAD) close = float(raw[day]["close"]) err = check_equal(day, "中证2000收盘", close, indices["2000"][day]["close"], 1e-8) max_close_difference = max(err, max_close_difference) prev_close = float(raw[previous]["close"]) if previous in raw else indices["2000"][previous]["close"] r_micro = close / prev_close - 1 r_market = float(states[day]["ret_market"]) dd = float(states[day]["dd_market"]) tail = int(states[day]["tail_market"]) current = {"dd": dd, "loss": -r_market, "relative": r_broad - r_micro} if day >= START: archived = panel[day] ranks = {k: indices[k][day]["activity_rank"] for k in BROAD} for k in BROAD: check_equal(day, f"成交分位{k}", ranks[k], float(archived["pct" + k])) for key, value in (("dd_market155", dd), ("ret_market155", r_market), ("ret_proxy", r_broad)): check_equal(day, key, value, float(archived[key])) if tail != int(dd >= threshold) or tail != int(archived["tail_market155"]): raise ValueError(f"{day} 等权尾部状态与同版回撤或原面板不符") # 从当日与此前四日收益的后缀积独立复算相对过去五个收盘的回撤。 ratio, recomputed = 1.0, 0.0 for prior in reversed(calendar[i-4:i+1]): ratio *= 1 + float(states[prior]["ret_market"]) recomputed = max(recomputed, 1 - ratio) max_dd_difference = max(max_dd_difference, check_equal(day, "五日回撤", dd, recomputed)) row = { "date": day, "dd_rank": rank(dd, history["dd"][-WINDOW:]), "loss_rank": rank(-r_market, history["loss"][-WINDOW:]), "turnover_weak": 1 - median(ranks.values()), "relative_rank": rank(current["relative"], history["relative"][-WINDOW:]), "tail": tail, "dd": dd, "market_return": r_market, "relative_weak": current["relative"], "broad_return": r_broad, "micro_return": r_micro, **{"pct" + k: ranks[k] for k in BROAD}, } output.append(row) for key, value in current.items(): history[key].append(value) proof = { "first": output[0]["date"], "last": output[-1]["date"], "days": len(output), "warmup_first": calendar[1], "warmup_last": calendar[WINDOW], "warmup_days": WINDOW, "initial_previous_close_date": calendar[0], "initial_micro_close_source": "index_data.csv" if calendar[0] in raw else "features_932000.CSI.json.gz", "previous_tail_date": calendar[WINDOW], "previous_tail": int(states[calendar[WINDOW]]["tail_market"]), "index_daily_close_comparisons": len(calendar) - 1, "max_micro_close_difference": max_close_difference, "market_drawdown_recalculations": len(output), "max_market_drawdown_difference": max_dd_difference, "market_version": audit["source"], "market_training_thresholds": audit["thresholds"], "daily_panel_comparisons": ["dd_market155", "ret_market155", "tail_market155", "ret_proxy", "pct300", "pct500", "pct1000"], "rank_definition": "此前60个交易日中小于当日的天数加同值天数的一半,再除以60。回撤及收益为小数。", "turnover_weak": "1减沪深300、中证500和中证1000当日成交活跃分位的中位数。", "relative_weak": "三个宽基当日简单收益的等权均值减中证2000当日简单收益。", "input_sha256": hashes, } return output, proof def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output-dir", type=Path, default=HERE) parser.add_argument("--end-date", default=LAST, help="可截断到已归档的评价日复算当时特征") args = parser.parse_args() rows, proof = build(args.end_date) args.output_dir.mkdir(parents=True, exist_ok=True) path = args.output_dir / "market.csv" with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") writer.writeheader() writer.writerows(rows) proof["market_csv_sha256"] = hashlib.sha256(path.read_bytes()).hexdigest() (args.output_dir / "market_source.json").write_text( json.dumps(proof, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" ) if __name__ == "__main__": main()