Coverage for evaluation/dataset_io.py: 100%
29 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Read a few columns of the 800 MB training dataset without holding all of it (V6.6.9, #389).
3`pd.read_csv` of the whole file needs about 3 GB; the dev PC has 3.9. A chunked read of the columns a step needs, as float32
4where they are numeric, and with an optional date floor applied chunk by chunk, fits in a few hundred MB."""
6from __future__ import annotations
8from collections.abc import Sequence
9from pathlib import Path
11import numpy as np
12import pandas as pd
14TEXT_COLUMNS = frozenset({"date", "ticker", "split", "timestamp", "security_type", "market", "asset_class"})
17def read_dataset_columns(path: Path | str, columns: Sequence[str], *, start: str | None = None, chunk_rows: int = 50_000) -> pd.DataFrame:
18 """`columns` of the CSV at `path`, rows dated `start` or later (the `date` column is read for the floor even when not asked for).
19 Numeric columns come back as float32; `date` as an ISO string. A requested column the file lacks is an error, never a silent gap."""
20 wanted = list(dict.fromkeys(columns))
21 header = pd.read_csv(path, nrows=0).columns
22 missing = [name for name in wanted if name not in header]
23 if missing:
24 raise KeyError(f"columns not in {Path(path).name}: {missing[:5]}")
25 read = list(dict.fromkeys([*wanted, "date"])) if start is not None else wanted
26 pieces = []
27 for chunk in pd.read_csv(path, usecols=read, chunksize=max(1, int(chunk_rows))):
28 if "date" in chunk:
29 chunk["date"] = chunk["date"].astype(str).str[:10]
30 if start is not None:
31 chunk = chunk[chunk["date"] >= str(start)[:10]]
32 numeric = [name for name in chunk.columns if name not in TEXT_COLUMNS and pd.api.types.is_numeric_dtype(chunk[name])]
33 chunk = chunk.astype(dict.fromkeys(numeric, np.float32))
34 pieces.append(chunk[wanted])
35 return pd.concat(pieces, ignore_index=True)
38def read_dataset_rows(path: Path | str, *, split: str | Sequence[str] | None = None, chunk_rows: int = 50_000) -> pd.DataFrame:
39 """Every column of the rows whose `split` is `split` (or one of several; all rows when None), read in chunks so the rows of the
40 other splits are never held. The values are exactly those of a plain `pd.read_csv`: a rank-book evaluation reads closes and
41 returns, which stay float64."""
42 wanted = None if split is None else ({split} if isinstance(split, str) else set(split))
43 pieces = []
44 for chunk in pd.read_csv(path, chunksize=max(1, int(chunk_rows))):
45 pieces.append(chunk if wanted is None else chunk[chunk["split"].isin(wanted)])
46 return pd.concat(pieces, ignore_index=True) if pieces else pd.DataFrame()