"""Folding the seven tables into the one a backtest mounts. `pit` is the same data in the only shape a point-in-time bundle can use: an entity, the date it is about, the instant it became knowable, and a number. Everything else -- who voted, what the minutes said, the whole distribution of dots -- stays in its own table for anyone who wants it. Two decisions shape what is in here. **Projections are keyed by horizon, not by year.** `US_FOMC_SEP_MEDIAN_PCE_ INFLATION_Y1` is a series that runs from 2012 to today. `...PCE_INFLATION_2019` is five rows that stop. The horizon is the projection year minus the year of the meeting that produced it, which is what makes successive releases comparable; `event_date` still carries the year being projected, so nothing is lost. **`previous` is the previous release of the same series, not the previous meeting.** A meeting with no projections does not interrupt the SEP series, and a meeting that published nothing at all contributes no rows to interrupt. """ from __future__ import annotations from datetime import UTC, datetime import polars as pl from .schema import PIT_SCHEMA, align PERCENT = "percent" # What each event type contributes, as (column, entity suffix, unit). POLICY_RATES = ( ("target_rate_lower", "TARGET_RATE_LOWER", PERCENT), ("target_rate_upper", "TARGET_RATE_UPPER", PERCENT), ("target_rate_mid", "TARGET_RATE_MID", PERCENT), ) ADMINISTERED_RATES = ( ("iorb_rate", "IORB", PERCENT), ("on_rrp_rate", "ON_RRP", PERCENT), ("primary_credit_rate", "PRIMARY_CREDIT", PERCENT), ) SEP_UNITS = { "real_gdp_growth": "percent_change_q4_over_q4", "pce_inflation": "percent_change_q4_over_q4", "core_pce_inflation": "percent_change_q4_over_q4", "unemployment_rate": PERCENT, "federal_funds_rate": PERCENT, } def horizon_label(projection_year: str, meeting_year: int) -> str | None: """`2027` seen from a 2026 meeting is `Y1`; `longer_run` is `LR`.""" if projection_year == "longer_run": return "LR" try: offset = int(projection_year) - meeting_year except ValueError: return None return f"Y{offset}" if 0 <= offset <= 5 else None def weighted_median(levels: list[float], counts: list[int]) -> float | None: """The middle dot, counting each participant once. With an even number of participants the two middle dots are averaged, which is the convention the Committee itself uses for the medians it publishes. """ dots = [level for level, count in zip(levels, counts, strict=True) for _ in range(count)] if not dots: return None dots.sort() middle = len(dots) // 2 if len(dots) % 2: return dots[middle] return (dots[middle - 1] + dots[middle]) / 2 def _rows_from_events(events: pl.DataFrame, meetings: pl.DataFrame) -> list[dict]: ends = dict(zip(meetings["meeting_id"], meetings["meeting_end_date"], strict=True)) rows = [] for event in events.iter_rows(named=True): event_date = ends.get(event["meeting_id"]) if event_date is None or event["knowledge_at"] is None: continue columns = ( POLICY_RATES if event["event_type"] == "STATEMENT" else ADMINISTERED_RATES if event["event_type"] == "IMPLEMENTATION_NOTE" else () ) for column, suffix, unit in columns: value = event.get(column) if value is None: continue rows.append( { "entity_id": f"US_FOMC_{suffix}", "event_date": event_date, "knowledge_date": event["knowledge_at"], "meeting_id": event["meeting_id"], "event_id": event["event_id"], "event_type": event["event_type"], "actual": float(value), "unit": unit, "decision": event.get("decision") if column == "target_rate_mid" else None, "vote_for": event.get("vote_for") if column == "target_rate_mid" else None, "vote_against": ( event.get("vote_against") if column == "target_rate_mid" else None ), "value_method": "derived" if column == "target_rate_mid" else "reported", "knowledge_time_precision": event["knowledge_time_precision"], "source_url": event["source_url"], } ) return rows def _rows_from_sep(sep: pl.DataFrame, meetings: pl.DataFrame) -> list[dict]: ends = dict(zip(meetings["meeting_id"], meetings["meeting_end_date"], strict=True)) rows = [] for projection in sep.iter_rows(named=True): end = ends.get(projection["meeting_id"]) if end is None or projection["median"] is None: continue horizon = horizon_label(projection["projection_year"], end.year) if horizon is None: continue year = end.year if projection["projection_year"] == "longer_run" else int( projection["projection_year"] ) rows.append( { "entity_id": f"US_FOMC_SEP_MEDIAN_{projection['variable'].upper()}_{horizon}", "event_date": end.replace(year=year, month=12, day=31), "knowledge_date": projection["knowledge_at"], "meeting_id": projection["meeting_id"], "event_id": f"{projection['meeting_id']}_SEP", "event_type": "SEP", "actual": projection["median"], "unit": SEP_UNITS.get(projection["variable"], PERCENT), "value_method": "reported", "knowledge_time_precision": "exact", "source_url": projection["source_url"], } ) return rows def _rows_from_dots(dots: pl.DataFrame, meetings: pl.DataFrame) -> list[dict]: """The median dot, which is the number the Committee does not print. The published SEP median for the funds rate begins in September 2015. For the eleven earlier dot plots this is the only median there is, and it is computed the same way for every release so the series does not change definition halfway through. """ ends = dict(zip(meetings["meeting_id"], meetings["meeting_end_date"], strict=True)) grouped = dots.group_by("meeting_id", "projection_year").agg( pl.col("rate_level"), pl.col("dot_count"), pl.col("knowledge_at").first(), pl.col("source_url").first(), ) rows = [] for group in grouped.iter_rows(named=True): end = ends.get(group["meeting_id"]) if end is None: continue horizon = horizon_label(group["projection_year"], end.year) median = weighted_median(group["rate_level"], group["dot_count"]) if horizon is None or median is None: continue year = end.year if group["projection_year"] == "longer_run" else int( group["projection_year"] ) rows.append( { "entity_id": f"US_FOMC_DOT_MEDIAN_{horizon}", "event_date": end.replace(year=year, month=12, day=31), "knowledge_date": group["knowledge_at"], "meeting_id": group["meeting_id"], "event_id": f"{group['meeting_id']}_SEP", "event_type": "SEP", "actual": median, "unit": PERCENT, "value_method": "derived", "knowledge_time_precision": "exact", "source_url": group["source_url"], } ) return rows def build_pit(frames: dict[str, pl.DataFrame]) -> pl.DataFrame: meetings = frames["meetings"] rows = [ *_rows_from_events(frames["events"], meetings), *_rows_from_sep(frames["sep"], meetings), *_rows_from_dots(frames["dot_plot"], meetings), ] if not rows: return pl.DataFrame(schema=dict(PIT_SCHEMA)) now = datetime.now(UTC) frame = pl.DataFrame(rows, infer_schema_length=None).with_columns( forecast=pl.lit(None, dtype=pl.Float64), parser_version=pl.lit(frames["events"]["parser_version"][0]), ingested_at=pl.lit(now).cast(pl.Datetime(time_unit="us", time_zone="UTC")), ) frame = frame.sort(["entity_id", "knowledge_date"]).with_columns( previous=pl.col("actual").shift(1).over("entity_id"), ) frame = frame.with_columns(change=pl.col("actual") - pl.col("previous")) return align(frame, PIT_SCHEMA).sort(["entity_id", "event_date", "knowledge_date"]) __all__ = ["build_pit", "horizon_label", "weighted_median"]