Coverage for scripts/compare_datasets.py: 100%

59 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Cell-by-cell comparison of two dataset builds (V6.1.0; the V6.0.0 session carried the same check inline). 

2 

3Rows are matched on (date, ticker). The report lists rows only in one file, every numeric column whose values differ 

4by more than 1e-6 (max delta, rows over), the differing cells per ticker, and split-label mismatches. 

5 

6 python scripts/compare_datasets.py <reference.csv> <candidate.csv> [--out report.json] [--splits train validation ...] 

7""" 

8 

9from __future__ import annotations 

10 

11import argparse 

12import json 

13from pathlib import Path 

14 

15import numpy as np 

16import pandas as pd 

17 

18TOLERANCE = 1e-6 

19 

20 

21def compare_frames(reference: pd.DataFrame, candidate: pd.DataFrame, tolerance: float = TOLERANCE) -> dict: 

22 """Both frames indexed by (date, ticker).""" 

23 report: dict = {"rows_reference": len(reference), "rows_candidate": len(candidate)} 

24 report["only_reference"] = [list(key) for key in reference.index.difference(candidate.index)[:50]] 

25 report["only_candidate"] = [list(key) for key in candidate.index.difference(reference.index)[:50]] 

26 report["num_only_reference"] = int(len(reference.index.difference(candidate.index))) 

27 report["num_only_candidate"] = int(len(candidate.index.difference(reference.index))) 

28 common = reference.index.intersection(candidate.index) 

29 numeric = [c for c in reference.columns if c in candidate.columns and pd.api.types.is_numeric_dtype(reference[c])] 

30 columns: dict[str, dict] = {} 

31 by_ticker: dict[str, int] = {} 

32 for column in numeric: 

33 a = reference.loc[common, column].to_numpy(dtype=float) 

34 b = candidate.loc[common, column].to_numpy(dtype=float) 

35 delta = np.abs(a - b) 

36 nan_mismatch = np.isnan(a) != np.isnan(b) 

37 over = (delta > tolerance) | nan_mismatch 

38 over = np.where(np.isnan(delta) & ~nan_mismatch, False, over) 

39 if over.any(): 

40 finite = delta[~np.isnan(delta)] 

41 columns[column] = {"max": float(finite.max()) if finite.size else None, "rows_over": int(over.sum())} 

42 for ticker, count in pd.Series(over, index=common).groupby(level="ticker").sum().items(): 

43 if count: 

44 by_ticker[str(ticker)] = by_ticker.get(str(ticker), 0) + int(count) 

45 report["columns_differing"] = columns 

46 report["differing_cells_by_ticker"] = dict(sorted(by_ticker.items(), key=lambda item: -item[1])) 

47 if "split" in reference.columns and "split" in candidate.columns: 

48 report["split_mismatch_rows"] = int((reference.loc[common, "split"] != candidate.loc[common, "split"]).sum()) 

49 return report 

50 

51 

52def load(path: str, splits: list[str] | None) -> pd.DataFrame: 

53 parts = [] 

54 for chunk in pd.read_csv(path, chunksize=40_000): 

55 parts.append(chunk[chunk["split"].isin(splits)] if splits else chunk) 

56 frame = pd.concat(parts, ignore_index=True) 

57 frame["date"] = frame["date"].astype(str).str[:10] 

58 return frame.set_index(["date", "ticker"]).sort_index() 

59 

60 

61def main() -> int: 

62 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

63 parser.add_argument("reference") 

64 parser.add_argument("candidate") 

65 parser.add_argument("--out", default=None) 

66 parser.add_argument("--splits", nargs="*", default=None) 

67 args = parser.parse_args() 

68 report = {"reference": args.reference, "candidate": args.candidate, 

69 **compare_frames(load(args.reference, args.splits), load(args.candidate, args.splits))} 

70 summary = {key: value for key, value in report.items() if key not in ("columns_differing", "only_reference", "only_candidate")} 

71 print(json.dumps(summary, indent=1)) 

72 print("columns differing:", len(report["columns_differing"])) 

73 if args.out: 

74 Path(args.out).parent.mkdir(parents=True, exist_ok=True) 

75 Path(args.out).write_text(json.dumps(report, indent=1), encoding="utf-8") 

76 return 0 

77 

78 

79if __name__ == "__main__": 

80 raise SystemExit(main())