"""What each subset actually spans, and from when each field is populated. The Treasury did not start publishing all of this at once, and the differences are large enough to change an analysis. The auction query reaches 1979; the bidder categories that everyone looks at -- indirect, direct, primary dealer -- begin in 2008, and so does the result artifact that states the release minute. The nominal curve starts in 1990, the real curve in 2003. The 20-year point vanished in 2002 and came back in 2020. A reader who assumes a uniform history will read "no indirect bidders" where the truth is "the Treasury did not publish that yet", so the spans are published as tables and the reason for each start date is written beside them. """ from __future__ import annotations from datetime import UTC, datetime from pathlib import Path import polars as pl NOTES = { "auction_calendar": ( "Every security in the TreasuryDirect auction query, from 1979 to the next announced " "auction. A calendar entry becomes knowable on its announcement date, not its auction " "date, which is the week of notice the Treasury gives." ), "auction_announcements": ( "One row per announced auction. The announcement carries no time of its own, so it is " "dated to the end of its announcement day." ), "auction_results": ( "One row per completed auction. From March 2008 the result artifact states the release " "minute and knowledge_time_precision is 'minute'; before that no artifact exists and " "the result is dated to the end of the auction day. Bidder categories, SOMA and the " "competitive breakdown also begin in 2008 and are null before it rather than zero." ), "nominal_yield_curve": ( "The Daily Treasury par yield curve from 1990, plus the long-term composite as its own " "curve_type. The set of maturities changes: the 20-year point ends in 2002 and returns " "in May 2020, and the 4-month bill is added in October 2022. Missing maturities are " "absent rows, never interpolated." ), "real_yield_curve": ( "The TIPS par real yield curve from 2003, plus the long-term real average as its own " "curve_type. Never mixed with the nominal curve; curve_type separates them." ), "bill_rates": ( "Daily bill rates on both quote conventions, bank discount and coupon equivalent, on " "one row per maturity per day because they are the same instrument measured " "differently." ), "curve_features": ( "Derived. Slopes between two points of the same day's official curve, and the spread " "between the nominal and real 10-year. That spread is not a market breakeven: both " "legs are par yields struck from indicative quotations." ), "pit": ( "Every subset folded into one entity-date-instant-number table. Auction metrics are " "keyed by term rather than by CUSIP so that a series runs across issues." ), } DATE_COLUMNS = { "auction_calendar": "auction_date", "auction_announcements": "announcement_date", "auction_results": "auction_date", "nominal_yield_curve": "curve_date", "real_yield_curve": "curve_date", "bill_rates": "rate_date", "curve_features": "curve_date", "pit": "event_date", } SCHEMA = { "subset": pl.String, "series_or_document_type": pl.String, "first_date": pl.Date, "last_date": pl.Date, "row_count": pl.Int64, "coverage_notes": pl.String, "generated_at": pl.Datetime(time_unit="us", time_zone="UTC"), } FIELD_SCHEMA = { "subset": pl.String, "field": pl.String, "first_date": pl.Date, "last_date": pl.Date, "populated_rows": pl.Int64, "total_rows": pl.Int64, "generated_at": pl.Datetime(time_unit="us", time_zone="UTC"), } BUILD_SCHEMA = { "build_at": pl.Datetime(time_unit="us", time_zone="UTC"), "parser_version": pl.String, "build_version": pl.String, "package_version": pl.String, "recipe_hash": pl.String, "source_snapshot_at": pl.Datetime(time_unit="us", time_zone="UTC"), "row_counts": pl.String, "quarantine_count": pl.Int64, } def coverage_table(frames: dict[str, pl.DataFrame]) -> pl.DataFrame: now = datetime.now(UTC) rows = [] for subset, column in DATE_COLUMNS.items(): frame = frames.get(subset) if frame is None or frame.is_empty() or column not in frame.columns: continue rows.append( { "subset": subset, "series_or_document_type": subset, "first_date": frame[column].min(), "last_date": frame[column].max(), "row_count": frame.height, "coverage_notes": NOTES.get(subset, ""), "generated_at": now, } ) return pl.DataFrame(rows, schema=SCHEMA) if rows else pl.DataFrame(schema=SCHEMA) def field_coverage(frames: dict[str, pl.DataFrame]) -> pl.DataFrame: """From when each field of the auction result is actually populated. This is the table that stops a reader treating a null as a zero. It says, per field, the first date on which the Treasury published it. """ now = datetime.now(UTC) rows = [] for subset in ("auction_results", "auction_announcements"): frame = frames.get(subset) column = DATE_COLUMNS[subset] if frame is None or frame.is_empty(): continue for field in frame.columns: if frame[field].dtype not in (pl.Float64, pl.Int64, pl.Int32): continue populated = frame.filter(pl.col(field).is_not_null()) if populated.is_empty(): rows.append( { "subset": subset, "field": field, "first_date": None, "last_date": None, "populated_rows": 0, "total_rows": frame.height, "generated_at": now, } ) continue rows.append( { "subset": subset, "field": field, "first_date": populated[column].min(), "last_date": populated[column].max(), "populated_rows": populated.height, "total_rows": frame.height, "generated_at": now, } ) return pl.DataFrame(rows, schema=FIELD_SCHEMA) if rows else pl.DataFrame(schema=FIELD_SCHEMA) def write_coverage(frames: dict[str, pl.DataFrame], *, metadata_dir: Path) -> int: metadata_dir.mkdir(parents=True, exist_ok=True) table = coverage_table(frames) table.write_parquet(metadata_dir / "coverage.parquet", compression="zstd") field_coverage(frames).write_parquet( metadata_dir / "field_coverage.parquet", compression="zstd" ) return table.height def write_build_record( frames: dict[str, pl.DataFrame], *, metadata_dir: Path, quarantined: int ) -> None: """One row saying what this build was, so a published tree can explain itself.""" import json from . import __version__ from .manifest import recipe_hash from .schema import BUILD_VERSION, PARSER_VERSION pit = frames.get("pit") newest = pit["knowledge_date"].max() if pit is not None and not pit.is_empty() else None record = pl.DataFrame( [ { "build_at": datetime.now(UTC), "parser_version": PARSER_VERSION, "build_version": BUILD_VERSION, "package_version": __version__, "recipe_hash": recipe_hash(), "source_snapshot_at": newest, "row_counts": json.dumps( {name: frame.height for name, frame in sorted(frames.items())} ), "quarantine_count": quarantined, } ], schema=BUILD_SCHEMA, ) metadata_dir.mkdir(parents=True, exist_ok=True) record.write_parquet(metadata_dir / "build.parquet", compression="zstd") __all__ = [ "BUILD_SCHEMA", "DATE_COLUMNS", "FIELD_SCHEMA", "NOTES", "SCHEMA", "coverage_table", "field_coverage", "write_build_record", "write_coverage", ]