Download recipe/pit.py from ZipLime/us-treasury-events: direct link, hf CLI and curl.
- Browser
- Download file 8 kB
-
https://huggingface.co/datasets/ZipLime/us-treasury-events/resolve/main/recipe/pit.py
- Command line
-
hf download hf://datasets/ZipLime/us-treasury-events/recipe/pit.py
-
curl -L -o pit.py https://huggingface.co/datasets/ZipLime/us-treasury-events/resolve/main/recipe/pit.py
8 kB
| """Folding the seven tables into the one a backtest mounts. | |
| `pit` is an entity, a date, an instant and a number. Two kinds of series go | |
| into it and they are dated in completely different ways, which is exactly why | |
| they belong in one table: a strategy that reads both must respect both. | |
| **Curve points** are `UST_CMT_10Y`, `UST_REAL_CMT_10Y`, `UST_BILL_13W_CE`. Their | |
| `event_date` is the day the curve describes and their `knowledge_date` is | |
| 18:00 Eastern that day, because that is when the Treasury says the rates are | |
| usually on its site. | |
| **Auction metrics** are `UST_AUCTION_10Y_HIGH_YIELD`, `..._BID_TO_COVER`, | |
| `..._INDIRECT_PCT`. Their `event_date` is the auction day and their | |
| `knowledge_date` is the minute the result artifact states -- 11:32 for an | |
| 11:30 close. Those two instants are minutes apart, and the difference is the | |
| whole trading opportunity. | |
| Auction series are keyed by **term**, not by CUSIP. `UST_AUCTION_10Y_BID_TO_COVER` | |
| runs from 1979 to today; a series keyed on one CUSIP is a handful of rows that | |
| stops when that bond is issued. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from datetime import UTC, datetime | |
| import polars as pl | |
| from .schema import PIT_SCHEMA, align | |
| PERCENT = "percent" | |
| RATIO = "ratio" | |
| # What each auction result contributes, as (column, suffix, unit). | |
| AUCTION_METRICS = ( | |
| ("high_yield", "HIGH_YIELD", PERCENT), | |
| ("high_discount_rate", "HIGH_DISCOUNT_RATE", PERCENT), | |
| ("investment_rate", "INVESTMENT_RATE", PERCENT), | |
| ("bid_to_cover", "BID_TO_COVER", RATIO), | |
| ("allocation_percentage", "ALLOTMENT_AT_HIGH_PCT", PERCENT), | |
| ("indirect_accepted_pct", "INDIRECT_PCT", PERCENT), | |
| ("direct_accepted_pct", "DIRECT_PCT", PERCENT), | |
| ("dealer_accepted_pct", "DEALER_PCT", PERCENT), | |
| ("tendered_to_offering", "TENDERED_TO_OFFERING", RATIO), | |
| ) | |
| DERIVED = { | |
| "indirect_accepted_pct", "direct_accepted_pct", "dealer_accepted_pct", "tendered_to_offering", | |
| } | |
| # One auction of a term per day is the rule. A reopening of the same term on | |
| # the same day would be two, and the pair is kept apart by the CUSIP in | |
| # `record_id` while the series stays keyed on the term. | |
| TERM_CODE = re.compile(r"[^A-Z0-9]+") | |
| def term_code(security_term: str | None, security_type: str | None) -> str | None: | |
| """`10-Year` + `tips` -> `10Y_TIPS`; `4-Week` + `bill` -> `4W`. | |
| The security type is part of the key because a 10-year note and a 10-year | |
| TIPS are auctioned on different days at different yields, and a series that | |
| mixed them would be two series pretending to be one. | |
| """ | |
| if not security_term: | |
| return None | |
| cleaned = TERM_CODE.sub("_", security_term.upper()).strip("_") | |
| cleaned = ( | |
| cleaned.replace("_YEAR", "Y").replace("_WEEK", "W") | |
| .replace("_MONTH", "M").replace("_DAY", "D") | |
| ) | |
| if security_type in {"tips", "frn", "cmb"}: | |
| cleaned = f"{cleaned}_{security_type.upper()}" | |
| return cleaned or None | |
| def _auction_rows(results: pl.DataFrame) -> list[dict]: | |
| rows = [] | |
| for result in results.iter_rows(named=True): | |
| term = term_code(result["security_term"], result["security_type"]) | |
| if term is None or result["knowledge_at"] is None or result["auction_date"] is None: | |
| continue | |
| for column, suffix, unit in AUCTION_METRICS: | |
| value = result.get(column) | |
| if value is None: | |
| continue | |
| rows.append( | |
| { | |
| "entity_id": f"UST_AUCTION_{term}_{suffix}", | |
| "event_date": result["auction_date"], | |
| "knowledge_date": result["knowledge_at"], | |
| "subset": "auction_results", | |
| "record_id": result["result_id"], | |
| "actual": float(value), | |
| "unit": unit, | |
| "value_method": "derived" if column in DERIVED else "reported", | |
| "knowledge_time_precision": result["knowledge_time_precision"], | |
| "source_url": result["source_url"], | |
| } | |
| ) | |
| return rows | |
| def entity_for(prefix: str, maturity: str) -> str: | |
| """`UST_CMT_` + `10Y` -> `UST_CMT_10Y`, without repeating a prefix. | |
| The long-term feeds label their rows `LT_COMPOSITE` and `LT_REAL_AVERAGE`, | |
| which already carry the prefix the feed would add. Concatenating blindly | |
| gives `UST_REAL_LT_LT_REAL_AVERAGE`. | |
| """ | |
| head = prefix.rstrip("_") | |
| if maturity.startswith("LT_") and head.endswith("_LT"): | |
| return f"{head[:-3]}_{maturity}" | |
| return f"{prefix}{maturity}" | |
| def _curve_rows(curve: pl.DataFrame, *, prefix: str, subset: str) -> list[dict]: | |
| if curve.is_empty(): | |
| return [] | |
| return [ | |
| { | |
| "entity_id": entity_for(prefix, row["maturity"]), | |
| "event_date": row["curve_date"], | |
| "knowledge_date": row["knowledge_at"], | |
| "subset": subset, | |
| "record_id": row["curve_id"], | |
| "actual": row["yield_pct"], | |
| "unit": PERCENT, | |
| "value_method": "reported", | |
| "knowledge_time_precision": row["knowledge_time_precision"], | |
| "source_url": row["source_url"], | |
| } | |
| for row in curve.iter_rows(named=True) | |
| if row["yield_pct"] is not None | |
| ] | |
| def _bill_rows(bills: pl.DataFrame) -> list[dict]: | |
| rows = [] | |
| for row in bills.iter_rows(named=True): | |
| for column, suffix in ( | |
| ("bank_discount_rate", "BD"), | |
| ("coupon_equivalent_rate", "CE"), | |
| ): | |
| value = row.get(column) | |
| if value is None: | |
| continue | |
| rows.append( | |
| { | |
| "entity_id": f"UST_BILL_{row['maturity']}_{suffix}", | |
| "event_date": row["rate_date"], | |
| "knowledge_date": row["knowledge_at"], | |
| "subset": "bill_rates", | |
| "record_id": row["bill_rate_id"], | |
| "actual": value, | |
| "unit": PERCENT, | |
| "value_method": "reported", | |
| "knowledge_time_precision": row["knowledge_time_precision"], | |
| "source_url": row["source_url"], | |
| } | |
| ) | |
| return rows | |
| def build_pit(frames: dict[str, pl.DataFrame]) -> pl.DataFrame: | |
| nominal = frames["nominal_yield_curve"] | |
| real = frames["real_yield_curve"] | |
| rows = [ | |
| *_auction_rows(frames["auction_results"]), | |
| *_curve_rows( | |
| nominal.filter(pl.col("curve_type") == "nominal"), | |
| prefix="UST_CMT_", subset="nominal_yield_curve", | |
| ), | |
| *_curve_rows( | |
| nominal.filter(pl.col("curve_type") == "long_term_composite"), | |
| prefix="UST_LT_", subset="nominal_yield_curve", | |
| ), | |
| *_curve_rows( | |
| real.filter(pl.col("curve_type") == "real"), | |
| prefix="UST_REAL_CMT_", subset="real_yield_curve", | |
| ), | |
| *_curve_rows( | |
| real.filter(pl.col("curve_type") == "long_term_real"), | |
| prefix="UST_REAL_LT_", subset="real_yield_curve", | |
| ), | |
| *_bill_rows(frames["bill_rates"]), | |
| ] | |
| 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["auction_results"]["parser_version"][0]) | |
| if not frames["auction_results"].is_empty() | |
| else pl.lit("1.0.0"), | |
| ingested_at=pl.lit(now).cast(pl.Datetime(time_unit="us", time_zone="UTC")), | |
| ) | |
| frame = frame.sort(["entity_id", "knowledge_date", "record_id"]).with_columns( | |
| previous=pl.col("actual").shift(1).over("entity_id") | |
| ) | |
| frame = frame.with_columns(change=(pl.col("actual") - pl.col("previous")).round(8)) | |
| return align(frame, PIT_SCHEMA).sort(["entity_id", "event_date", "knowledge_date"]) | |
| __all__ = ["AUCTION_METRICS", "build_pit", "entity_for", "term_code"] | |