"""The gate. Nothing is published that fails it. Most of what is checked here is not about parsing at all -- a number can be read perfectly and still be dated wrongly, and a wrongly dated number is worse than a missing one because a backtest cannot tell. So the checks divide in two. **Look-ahead.** These are the ones that matter. Minutes must be knowable after the meeting they describe, never on the day of it. A statement must be knowable on the day it was released and not before. Nothing may be knowable before the Committee met, and nothing about a meeting may be knowable before the earliest instant the `meetings` row claims. Each of these has been an actual bug in a dataset somewhere, and each would be invisible in the numbers. **Shape.** Identifiers unique, vocabularies respected, target ranges the right way round, dot plots that count the same number of participants in every year they cover. These catch a parser that has started reading the wrong column. A failed check is an error and stops publication. A `warning` is something worth knowing that does not make the data wrong -- a meeting whose minutes have not appeared yet is normal three weeks of the year. """ from __future__ import annotations import json from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from pathlib import Path import polars as pl from .schema import ( DECISIONS, DOCUMENT_TYPES, EVENT_TYPES, KNOWLEDGE_PRECISIONS, MEETING_TYPES, VOTES, ) from .store import read_table # The minutes have been published three weeks after the meeting since 2005. # Anything sooner than a week would mean the release date was misread. MIN_MINUTES_LAG = timedelta(days=7) MAX_MINUTES_LAG = timedelta(days=60) # A participant may decline to give a longer-run projection, so the dot counts # can differ a little between years of one release. They cannot differ a lot. MAX_DOT_SPREAD = 3 @dataclass(slots=True) class Report: errors: list[str] = field(default_factory=list) warnings: list[str] = field(default_factory=list) counts: dict[str, int] = field(default_factory=dict) checked_at: datetime = field(default_factory=lambda: datetime.now(UTC)) @property def ok(self) -> bool: return not self.errors def error(self, message: str) -> None: self.errors.append(message) def warn(self, message: str) -> None: self.warnings.append(message) def as_dict(self) -> dict: return { "ok": self.ok, "checked_at": self.checked_at.isoformat(), "counts": self.counts, "errors": self.errors, "warnings": self.warnings, } def write(self, target: Path) -> None: target.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8") def _load(data_dir: Path, table: str) -> pl.DataFrame: try: return read_table(data_dir, table).collect() except (FileNotFoundError, pl.exceptions.ComputeError): return pl.DataFrame() def validate(data_dir: Path) -> Report: report = Report() tables = { name: _load(data_dir, name) for name in ( "events", "meetings", "documents", "sep", "dot_plot", "votes", "calendar", "pit", ) } report.counts = {name: frame.height for name, frame in tables.items()} for name, frame in tables.items(): if frame.is_empty(): report.error(f"{name} is empty") if not report.errors: check_identifiers(tables, report) check_vocabularies(tables, report) check_rates(tables["events"], report) check_look_ahead(tables, report) check_dot_plot(tables["dot_plot"], report) check_sep(tables["sep"], report) check_coverage(tables, report) check_pit(tables["pit"], report) return report def check_pit(pit: pl.DataFrame, report: Report) -> None: """The table a bundle mounts: every row datable, every number a number.""" for column in ("entity_id", "event_date", "knowledge_date", "actual"): if pit[column].null_count(): report.error(f"pit.{column} has nulls; the bundle cannot be mounted") if pit["forecast"].null_count() != pit.height: report.error("pit.forecast is not null everywhere; this dataset carries no forecasts") duplicates = pit.height - pit.select("entity_id", "event_date", "knowledge_date").n_unique() if duplicates: report.error(f"pit has {duplicates} rows sharing an entity, date and instant") unknown = set(pit["value_method"].drop_nulls().unique()) - {"reported", "derived"} if unknown: report.error(f"pit.value_method has values outside its vocabulary: {sorted(unknown)}") def check_identifiers(tables: dict[str, pl.DataFrame], report: Report) -> None: keys = { "events": "event_id", "meetings": "meeting_id", "documents": "document_id", "sep": "sep_id", "dot_plot": "dot_id", "votes": "vote_id", "calendar": "calendar_id", } for table, key in keys.items(): frame = tables[table] duplicates = frame.height - frame.select(key).n_unique() if duplicates: report.error(f"{table}.{key} has {duplicates} duplicate values") if frame[key].null_count(): report.error(f"{table}.{key} has nulls") meetings = set(tables["meetings"]["meeting_id"].to_list()) for table in ("events", "documents", "sep", "dot_plot", "votes", "calendar", "pit"): orphans = set(tables[table]["meeting_id"].drop_nulls().to_list()) - meetings if orphans: report.error(f"{table} references {len(orphans)} unknown meetings, e.g. {sorted(orphans)[0]}") def check_vocabularies(tables: dict[str, pl.DataFrame], report: Report) -> None: checks = [ ("events", "event_type", EVENT_TYPES), ("events", "decision", DECISIONS), ("events", "knowledge_time_precision", KNOWLEDGE_PRECISIONS), ("documents", "document_type", DOCUMENT_TYPES), ("documents", "knowledge_time_precision", KNOWLEDGE_PRECISIONS), ("meetings", "meeting_type", MEETING_TYPES), ("votes", "vote", VOTES), ("calendar", "knowledge_time_precision", KNOWLEDGE_PRECISIONS), ] for table, column, allowed in checks: frame = tables[table] if column not in frame.columns: continue unknown = set(frame[column].drop_nulls().unique().to_list()) - set(allowed) if unknown: report.error(f"{table}.{column} has values outside its vocabulary: {sorted(unknown)}") def check_rates(events: pl.DataFrame, report: Report) -> None: statements = events.filter(pl.col("event_type") == "STATEMENT") inverted = statements.filter(pl.col("target_rate_lower") > pl.col("target_rate_upper")) if inverted.height: report.error(f"{inverted.height} statements have a target range the wrong way round") outside = statements.filter( (pl.col("target_rate_upper") > 25) | (pl.col("target_rate_lower") < 0) ) if outside.height: report.error(f"{outside.height} statements have a target range outside 0-25 percent") missing = statements.filter(pl.col("target_rate_lower").is_null()) if missing.height: report.warn(f"{missing.height} statements state no target rate") for column in ("iorb_rate", "on_rrp_rate", "primary_credit_rate"): strange = events.filter((pl.col(column) < 0) | (pl.col(column) > 25)) if strange.height: report.error(f"{strange.height} events have an implausible {column}") def check_look_ahead(tables: dict[str, pl.DataFrame], report: Report) -> None: """The checks this dataset exists for. Every one of these compares an instant against the event it describes, and every failure means a backtest could have traded on something it could not have known. """ events = tables["events"] meetings = tables["meetings"].select( "meeting_id", "meeting_start_date", "meeting_end_date", "meeting_type", "knowledge_date" ).rename({"knowledge_date": "meeting_knowledge"}) joined = events.join(meetings, on="meeting_id", how="left") # Compared in Eastern time, not UTC. An end-of-day instant in Washington is # already tomorrow in UTC, and comparing the UTC date would call every # date-precision event a day late. early = joined.filter(pl.col("release_date_et") < pl.col("meeting_start_date")) if early.height: report.error( f"{early.height} events are knowable before their meeting began, " f"e.g. {early['event_id'][0]}" ) # A scheduled meeting announces on the day it ends. A conference call held # in the evening is announced the next morning -- 16 August 2007 and three # others -- so an unscheduled gathering is allowed one day, and no more. statements = joined.filter(pl.col("event_type") == "STATEMENT") allowance = pl.when(pl.col("meeting_type") == "scheduled").then(0).otherwise(1) late_statements = statements.filter( (pl.col("release_date_et") - pl.col("meeting_end_date")).dt.total_days() > allowance ) if late_statements.height: report.error( f"{late_statements.height} statements are dated too long after the meeting ended, " f"e.g. {late_statements['event_id'][0]}" ) minutes = joined.filter(pl.col("event_type") == "MINUTES") too_soon = minutes.filter( (pl.col("release_date_et") - pl.col("meeting_end_date")) < MIN_MINUTES_LAG ) if too_soon.height: report.error( f"{too_soon.height} minutes are knowable less than a week after their meeting, " f"e.g. {too_soon['event_id'][0]}" ) too_late = minutes.filter( (pl.col("release_date_et") - pl.col("meeting_end_date")) > MAX_MINUTES_LAG ) if too_late.height: report.warn(f"{too_late.height} minutes are dated more than 60 days after their meeting") behind = joined.filter(pl.col("knowledge_at") < pl.col("meeting_knowledge")) if behind.height: report.error( f"{behind.height} events are knowable before the meeting row they belong to, " f"e.g. {behind['event_id'][0]}" ) for table, column in (("documents", "knowledge_at"), ("sep", "knowledge_at"), ("dot_plot", "knowledge_at"), ("votes", "knowledge_at")): frame = tables[table] if frame[column].null_count(): report.error(f"{table}.{column} has nulls; every row must be datable") for table in ("events", "documents", "sep", "dot_plot", "votes", "calendar", "meetings"): frame = tables[table] column = "knowledge_at" if "knowledge_at" in frame.columns else "knowledge_date" if frame[column].null_count(): report.error(f"{table}.{column} has nulls") mismatched = frame.filter(pl.col("knowledge_date") != pl.col(column)) if "knowledge_at" in frame.columns and mismatched.height: report.error(f"{table}.knowledge_date disagrees with knowledge_at in {mismatched.height} rows") calendar = tables["calendar"] ahead = calendar.filter(pl.col("knowledge_date") > pl.col("scheduled_at")) if ahead.height: report.warn( f"{ahead.height} calendar entries become knowable only at the meeting itself" ) def check_dot_plot(dots: pl.DataFrame, report: Report) -> None: """One release's dots must count the same participants in every year.""" totals = dots.group_by("meeting_id", "projection_year").agg( pl.col("dot_count").sum().alias("participants") ) spread = totals.group_by("meeting_id").agg( (pl.col("participants").max() - pl.col("participants").min()).alias("spread"), pl.col("participants").max().alias("most"), ) uneven = spread.filter(pl.col("spread") > MAX_DOT_SPREAD) if uneven.height: report.error( f"{uneven.height} dot plots disagree with themselves about how many participants " f"there were, e.g. {uneven['meeting_id'][0]}" ) implausible = spread.filter((pl.col("most") < 5) | (pl.col("most") > 25)) if implausible.height: report.error( f"{implausible.height} dot plots have an implausible number of participants, " f"e.g. {implausible['meeting_id'][0]}" ) outside = dots.filter((pl.col("rate_level") < -1) | (pl.col("rate_level") > 25)) if outside.height: report.error(f"{outside.height} dots sit outside -1 to 25 percent") def check_sep(sep: pl.DataFrame, report: Report) -> None: inverted = sep.filter( (pl.col("range_low") > pl.col("range_high")) | (pl.col("central_tendency_low") > pl.col("central_tendency_high")) ) if inverted.height: report.error(f"{inverted.height} projections have an interval the wrong way round") outside = sep.filter( (pl.col("central_tendency_low") < pl.col("range_low")) | (pl.col("central_tendency_high") > pl.col("range_high")) ) if outside.height: report.error( f"{outside.height} projections have a central tendency wider than the range, " "which means two columns were read as one" ) empty = sep.filter( pl.col("median").is_null() & pl.col("range_low").is_null() & pl.col("central_tendency_low").is_null() ) if empty.height: report.error(f"{empty.height} projection rows carry no number at all") def check_coverage(tables: dict[str, pl.DataFrame], report: Report) -> None: meetings = tables["meetings"] held = meetings.filter(pl.col("meeting_end_date") < datetime.now(UTC).date()) without_statement = held.filter(~pl.col("has_statement") & pl.col("scheduled")) if without_statement.height: report.warn( f"{without_statement.height} scheduled meetings that have been held have no statement" ) recent = held.sort("meeting_end_date").tail(8) if recent.height and not recent["has_minutes"].any(): report.error("none of the last eight held meetings has minutes; discovery is broken") sep_meetings = set(tables["sep"]["meeting_id"].unique().to_list()) dot_meetings = set(tables["dot_plot"]["meeting_id"].unique().to_list()) if dot_meetings - sep_meetings: report.warn( f"{len(dot_meetings - sep_meetings)} meetings have a dot plot but no projections table" ) __all__ = [ "MAX_DOT_SPREAD", "MAX_MINUTES_LAG", "MIN_MINUTES_LAG", "Report", "check_pit", "validate", ]