"""双源逐字段对账:语义不匹配分流,未解数值冲突隔离。""" import json from decimal import Decimal as D from datetime import datetime, timezone, timedelta def row(day, close, volume=1000, session="regular", basis="raw"): return {"date": day, "close": D(close), "volume": volume, "session": session, "basis": basis, "currency": "CNY", "symbol": "AAA", "timestamp": f"{day}T{'18' if session == 'after_hours' else '15'}:00:00+08:00"} def session_date(value): stamp = datetime.fromisoformat(value) if stamp.tzinfo is None: raise ValueError("timezone_required") return stamp.astimezone(timezone(timedelta(hours=8))).date().isoformat() a = {f"2026-10-{d}": row(f"2026-10-{d}", str(d-9)) for d in range(19, 24)} b = {"2026-10-19": row("2026-10-19", "10.005"), "2026-10-20": row("2026-10-20", "11.3", session="after_hours"), "2026-10-21": row("2026-10-21", "6", basis="adjusted"), "2026-10-22": row("2026-10-22", "13.5"), "2026-10-23": row("2026-10-23", "14", volume=900), "2026-10-26": row("2026-10-26", "15")} b["2026-10-19"]["timestamp"] = "2026-10-19T07:00:00+00:00" assert all(session_date(value["timestamp"]) == day for data in [a, b] for day, value in data.items()) assert session_date("2026-10-18T17:00:00+00:00") == "2026-10-19" canonical, audit = {}, {} for day in sorted(set(a) | set(b)): candidates = [(name, data[day]) for name, data in [("A", a), ("B", b)] if day in data] valid = [(name, value) for name, value in candidates if value["session"] == "regular" and value["basis"] == "raw" and value["currency"] == "CNY" and value["symbol"] == "AAA"] if not valid: audit[day] = "no_compatible_row" continue if len(valid) == 2: differences = [field for field, tolerance in [("close", D("0.01")), ("volume", D("0"))] if abs(D(valid[0][1][field])-D(valid[1][1][field])) > tolerance] if differences: audit[day] = "unresolved:"+"+".join(differences) continue chosen, value = valid[0] canonical[day] = {"source": chosen, "close": str(value["close"]), "volume": value["volume"]} audit[day] = "within_tolerance:A" if len(valid) == 2 else "single_compatible:"+chosen assert sorted(canonical) == ["2026-10-19", "2026-10-20", "2026-10-21", "2026-10-26"] assert canonical["2026-10-19"]["close"] == "10" and canonical["2026-10-26"]["source"] == "B" assert audit["2026-10-22"] == "unresolved:close" and audit["2026-10-23"] == "unresolved:volume" assert "2026-10-22" not in canonical and "2026-10-23" not in canonical print(json.dumps({"canonical": canonical, "audit": audit, "quarantined": ["2026-10-22", "2026-10-23"]}, sort_keys=True))