"""核 @default-researchagent 给的两只真值段 + hs300/zz500 副本因子实况（只读）。
用法: ./zt_venv/bin/python code/chk_factor_truth_segments.py
"""
import os, glob, time
import pandas as pd

ROOT = "backtest_zt_full"
POOLS = ["hs300", "zz500", "zz1000", "zz2000"]

print("=== 四池 mtime（写盘竞态观测）===")
for p in POOLS:
    fs = glob.glob(f"{ROOT}/daily_{p}/*.csv")
    if not fs:
        continue
    mt = [os.path.getmtime(f) for f in fs]
    print(f"  {p:<7} 文件 {len(fs):<5} mtime 最新 {time.strftime('%m-%d %H:%M', time.localtime(max(mt)))}"
          f" 最早 {time.strftime('%m-%d %H:%M', time.localtime(min(mt)))}")
a = pd.read_csv(f"{ROOT}/adj_factor_all.csv")
print(f"  本地 adj_factor_all.csv: {a.shape} 行, 日期 {a['trade_date'].min()}~{a['trade_date'].max()}"
      f" ({a['trade_date'].nunique()} 个交易日)  <- 快照 or 累积表?")

SEG = {
    '002812.SZ': [(20210104, 3.495), (20210430, None), (20220516, None), (20230821, None),
                  (20230921, None), (20240603, None), (20260911, 3.665)],
    '600705.SH': [(20210104, 51.135), (20230630, 54.989), (20250115, 56.1086)],
}
for code, pts in SEG.items():
    print(f"\n=== {code} ===")
    for p in POOLS:
        f = f"{ROOT}/daily_{p}/{code}.csv"
        if not os.path.exists(f):
            continue
        d = pd.read_csv(f)
        d['trade_date'] = d['trade_date'].astype(int)
        first, last = d.iloc[0], d.iloc[-1]
        print(f"  @{p:<7} 行 {len(d):<5} 首行 {first['trade_date']} factor {first['adj_factor']:.6f}"
              f" | 末行 {last['trade_date']} factor {last['adj_factor']:.6f}")
        for dt, tv in pts:
            if tv is None:
                continue
            r = d[d.trade_date == dt]
            if not len(r):
                print(f"      {dt}: 无该行")
                continue
            got = float(r['adj_factor'].iloc[0])
            print(f"      {dt}: 副本 {got:.6f} vs 真值 {tv:.6f}  rel {abs(got/tv-1):.2e}"
                  f" {'✅' if abs(got/tv-1) < 1e-4 else '❌'}")
