"""使用另一份同源行情拷贝,逐股逐日重算受压广度。""" import csv import gzip import hashlib import json import math from collections import defaultdict from datetime import date from pathlib import Path import pyarrow.compute as pc import pyarrow.dataset as ds HERE = Path(__file__).resolve().parent PROJECTS = HERE.parents[2] CALENDAR = HERE.parent / "macro_grid_20261029/results/features_000300.SH.json.gz" MAIN_CACHE = PROJECTS / "quant_factor_service/data/parquet_cache/gp_day_data" OTHER_CACHE = PROJECTS / "factor_sys/data_lake/market_data" CODE = r"^(SH(600|601|603|605|688)|SZ(000|001|002|003|300|301|302))[0-9]{3}$" RAW_FIELDS = ["close", "pre_close", "volume", "amount", "high", "low"] COUNT_FIELDS = [ "fixed_d0_count", "initially_stressed_count", "initially_unpressured_count", "unpressured_valid_today", "first_shock_today", "first_observed_after_gap_count", "initially_stressed_valid_today", "initially_stressed_shock_today", "all_fixed_valid_quote_today", "all_fixed_decliners", ] RATIOS = { "first_shock_fraction_of_initially_unpressured": ("first_shock_today", "initially_unpressured_count"), "initially_stressed_shock_fraction_of_valid": ("initially_stressed_shock_today", "initially_stressed_valid_today"), "initially_stressed_shock_fraction_of_fixed": ("initially_stressed_shock_today", "initially_stressed_count"), "all_fixed_declining_fraction": ("all_fixed_decliners", "all_fixed_valid_quote_today"), } def digest(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def file_rows(name): with (HERE / name).open(encoding="utf-8-sig") as stream: return list(csv.DictReader(stream)) def other_file(year): return OTHER_CACHE / f"year={year}" / f"market_{year}.parquet" def stock_history(dates): values = defaultdict(dict) conflicting_keys = set() for year in sorted({day.year for day in dates}): scope = ds.field("trade_date").isin([day for day in dates if day.year == year]) scope &= pc.match_substring_regex(ds.field("symbol"), pattern=CODE) table = ds.dataset(other_file(year)).to_table(columns=["trade_date", "symbol", *RAW_FIELDS], filter=scope) for row in table.to_pylist(): name, day = row["symbol"], row["trade_date"] entry = tuple(row[col] for col in RAW_FIELDS) if day in values[name] and values[name][day] != entry: conflicting_keys.add((name, day)) else: values[name][day] = entry for name, day in conflicting_keys: values[name].pop(day, None) return values def normalized_values(fields): close, prev, vol, amount, high, low = fields if any(v is None or not math.isfinite(v) or v <= 0 for v in (close, prev, vol, amount)): return None, None daily_return = (close-prev)/prev if any(v is None or not math.isfinite(v) or v <= 0 for v in (high, low)) or not low <= close <= high: return daily_return, None true_range = max(high-low, abs(high-prev), abs(low-prev)) return daily_return, true_range/prev def calculate(dates): count = [{col: 0 for col in COUNT_FIELDS} for _ in dates[20:]] for values in stock_history(dates).values(): observations = [normalized_values(values[day]) if day in values else (None, None) for day in dates] history = [] for k in range(len(count)): prior = [tr for _, tr in observations[k:k+20]] price_return = observations[k+20][0] if price_return is None or None in prior or not any(prior): history.append(None) else: history.append(-price_return >= math.fsum(prior)/20) if history[0] is None: continue initial = history[0] for k, shock in enumerate(history): row = count[k] row["fixed_d0_count"] += 1 row["initially_stressed_count"] += int(initial) row["initially_unpressured_count"] += int(not initial) price_return = observations[k+20][0] if price_return is not None: row["all_fixed_valid_quote_today"] += 1 row["all_fixed_decliners"] += int(price_return < 0) if shock is None: continue if initial: row["initially_stressed_valid_today"] += 1 row["initially_stressed_shock_today"] += int(shock) else: row["unpressured_valid_today"] += 1 if shock and True not in history[:k]: col = "first_observed_after_gap_count" if None in history[:k] else "first_shock_today" row[col] += 1 for row in count: for col, (num, den) in RATIOS.items(): row[col] = row[num] / row[den] if row[den] else None return count def main(): with gzip.open(CALENDAR, "rt") as stream: calendar = [date.fromisoformat(row["timestamp"][:10]) for row in json.load(stream)["data"]] years, differences, inspected = set(), [], [] truth = {(int(row["episode_id"]), int(row["k"])): row for row in file_rows("breadth.csv")} if len(truth) != len(file_rows("breadth.csv")): raise ValueError("广度明细出现重复日期序号") available = {row["date"] for row in file_rows("market_daily.csv") if row["coverage_valid"] == "True"} for episode in file_rows("episodes.csv"): if not episode["d0"] or not episode["d5"]: continue start = calendar.index(date.fromisoformat(episode["d0"])) dates = calendar[start-20:start+6] if not all(day.isoformat() in available for day in dates[20:]): continue if dates[-1].isoformat() != episode["d5"]: raise ValueError("D5与交易日历不符") years.update(day.year for day in dates) for k, check in enumerate(calculate(dates)): day, key = dates[20+k].isoformat(), (int(episode["episode_id"]), k) expected = truth.pop(key, {}) diff = {} if expected.get("date") != day or expected.get("d0") != episode["d0"]: diff["date_or_d0"] = "明细日期不符或行缺失" for col, value in check.items(): raw = expected.get(col) other = float(raw) if raw not in (None, "") else None equal = value == other if value is not None and other is not None and col in RATIOS: equal = math.isclose(value, other, abs_tol=1e-11, rel_tol=0) if not equal: diff[col] = {"原广度结果": other, "另一份缓存重算": value} if diff: differences.append({"date": day, "fields": diff}) inspected.append({"episode": key[0], "k": k, "date": day, "pass": not diff}) frozen = json.loads((HERE / "breadth_coverage.json").read_text()) main_hashes = {f"year_{y}.parquet": digest(MAIN_CACHE/f"year_{y}.parquet") for y in sorted(years)} other_hashes = {str(other_file(y)): digest(other_file(y)) for y in sorted(years)} matches = (not differences and not truth and bool(inspected) and main_hashes == frozen["source_sha256"] and digest(HERE/"breadth.csv") == frozen["breadth_sha256"]) record = { "passed": matches, "checked_dates": len(inspected), "passed_dates": sum(r["pass"] for r in inspected), "scope": "两份物理缓存均来自gp_day_data,验证不同存储与实现能否复现,不能独立验证供应商原始行情。", "command_from_repository_root": "/opt/anaconda3/bin/python3 -B research/liquidity_tail_20261120/breadth_audit.py", "main_cache": str(MAIN_CACHE), "main_sha256": main_hashes, "check_cache_sha256": other_hashes, "breadth_csv_sha256": digest(HERE/"breadth.csv"), "calendar_sha256": digest(CALENDAR), "compared_fields": COUNT_FIELDS + list(RATIOS), "fraction_absolute_tolerance": 1e-11, "outside_comparison": "D0全市场有效股票总数及据其计算的ATR不足数由market_data.py审计覆盖。比较以独立确定的D0连续历史有效名单为起点。", "dates": inspected, "differences": differences, "unexpected_rows": [list(key) for key in truth], } output = HERE / "breadth_audit.json" output.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n") if not matches: raise ValueError(f"股票广度独立复核异常,详见 {output}") print(f"逐股复算通过,共{len(inspected)}个日期,比较{len(record['compared_fields'])}列。") if __name__ == "__main__": main()