Files
stack/src/bls/ppi.py

53 lines
1.4 KiB
Python

"""PPI extract. The caller supplies the CSV. No download.
JOLTS and QCEW use this same reader. A later file with different columns
should stop calling :func:`parse_series`.
"""
from __future__ import annotations
import csv
import io
from dataclasses import dataclass
_COLUMNS = ("series_id", "year", "period", "value")
@dataclass(frozen=True)
class SeriesRow:
series_id: str
year: int
period: str
value: float | None
def _value(text: str) -> float | None:
raw = text.strip()
if raw in {"", "."}:
return None
return float(raw)
def parse_series(csv_text: str) -> tuple[SeriesRow, ...]:
"""Read ``series_id,year,period,value``. A missing column raises."""
reader = csv.DictReader(io.StringIO(csv_text))
names = set(reader.fieldnames or ())
missing = [name for name in _COLUMNS if name not in names]
if missing:
raise ValueError(f"missing columns: {missing}")
rows: list[SeriesRow] = []
for record in reader:
rows.append(
SeriesRow(
series_id=(record.get("series_id") or "").strip(),
year=int(record["year"]),
period=(record.get("period") or "").strip(),
value=_value(record.get("value") or ""),
)
)
return tuple(rows)
def parse_ppi(csv_text: str) -> tuple[SeriesRow, ...]:
return parse_series(csv_text)