"""From two feeds to seven tables. The run has two halves that share nothing but a timezone. **Auctions.** One JSON document from TreasuryDirect carries every security auctioned since 1979 with a hundred and twenty fields each. From it come the calendar, the announcements and the results. What it does not carry is when a result was published, so for every auction since March 2008 the small result artifact is fetched as well and read for the one line that matters: `11:32`. **Curves.** Five CSV feeds, one file per year each, wide. Every cell becomes a row and a blank cell becomes nothing, because a maturity the Treasury did not publish that day is not a zero and not a gap to be filled. The instants differ, and the difference is the whole point. An auction result states its own minute. A curve does not: its quotations are struck at 3:30 p.m. Eastern and the Treasury says the rates are usually on its site by 6:00 p.m., so 15:30 is what the number describes and 18:00 is when it could be read. """ from __future__ import annotations import asyncio import json import logging from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path import polars as pl from .config import COUNTRY, FIRST_CURVE_YEAR, Settings, validate_user_agent from .coverage import write_build_record, write_coverage from .http import Artifact, Fetcher from .methodology import methodology_for, write_registry from .pit import build_pit from .schema import ( ANNOUNCEMENT_SCHEMA, AUCTION_CALENDAR_SCHEMA, BILL_RATE_SCHEMA, CURVE_FEATURE_SCHEMA, CURVE_SCHEMA, PARSER_VERSION, RESULT_SCHEMA, align, ) from .sources.auctions import ( ANNOUNCED_URL, ARTIFACT_URL, SEARCH_URL, Auction, parse_artifact, parse_auctions, security_type, to_bool, to_date, to_float, ) from .sources.curves import FEEDS, RATES_URL, parse_bill_rates, parse_curve from .store import read_table, write_table from .timing import ( CURVE_TIME_BASIS, at, clock, curve_instants, end_of_day, release_instant, ) LOGGER = logging.getLogger(__name__) SOURCE_AUCTIONS = "treasurydirect.gov" SOURCE_RATES = "home.treasury.gov" PIT_DELTA_NAME = "us_treasury_events.delta" # The auction query gains a row whenever an auction is announced and fills in # the result fields on the afternoon of the auction. Nothing else about it # changes, so an hour is fresh enough and a scheduled run costs one request. QUERY_MAX_AGE = 3600 # A finished year of rates is finished. The current year is not. CURRENT_YEAR_MAX_AGE = 3600 # Which feed fills which table, and under which curve_type. A table fed by two # feeds keeps them apart by curve_type, so a held year can be matched back to # the feed that produced it. FEED_TABLES = { "nominal": ("nominal_yield_curve", "nominal", "curve_date"), "long_term_composite": ("nominal_yield_curve", "long_term_composite", "curve_date"), "real": ("real_yield_curve", "real", "curve_date"), "long_term_real": ("real_yield_curve", "long_term_real", "curve_date"), "bill": ("bill_rates", None, "rate_date"), } # A result artifact for an auction that has happened never changes, and a miss # is permanent: no artifact was published for auctions before March 2008. SETTLED = 365 * 24 * 3600 @dataclass(slots=True) class Quarantined: record_id: str subset: str url: str reason: str @dataclass(slots=True) class BuildResult: counts: dict[str, int] = field(default_factory=dict) quarantined: list[Quarantined] = field(default_factory=list) def provenance(artifact: Artifact | None, *, source: str, url: str) -> dict: return { "source": source, "source_url": url, "raw_sha256": artifact.sha256 if artifact else None, "parser_version": PARSER_VERSION, "first_seen_at": artifact.downloaded_at if artifact else None, "ingested_at": datetime.now(UTC), } def share(part: float | None, whole: float | None) -> float | None: """`part / whole` as a percentage, or nothing. Nothing is the answer when either side is absent. A bidder category that the Treasury did not publish is not a zero share; before 2008 it published none of them, and a table of zeroes would read as "no indirect bidders took any of it", which is a claim nobody made. """ if part is None or not whole: return None return round(100.0 * part / whole, 6) # --------------------------------------------------------------------------- # Auctions. async def fetch_auctions(fetcher: Fetcher) -> tuple[list[Auction], Artifact]: """Every security in the query, and the query document they came from. The document is returned with them because the calendar and announcement rows are built from it and nothing else. An earlier version attached the digest of the result artifact to those rows, which is the digest of a different document saying different things. """ artifact = await fetcher.get(SEARCH_URL, max_age_seconds=QUERY_MAX_AGE) auctions = parse_auctions(json.loads(artifact.text)) # The announced feed is the same shape and holds auctions that the search # endpoint has not picked up yet. Merging it costs one request and is the # difference between knowing about tomorrow's auction and not. upcoming = await fetcher.get(ANNOUNCED_URL, max_age_seconds=QUERY_MAX_AGE, allow_missing=True) if upcoming is not None: held = {auction.auction_id for auction in auctions} for auction in parse_auctions(json.loads(upcoming.text)): if auction.auction_id not in held: auctions.append(auction) auctions.sort(key=lambda auction: (auction.auction_date, auction.row.get("cusip") or "")) return auctions, artifact async def result_times(fetcher: Fetcher, auction: Auction) -> tuple[Artifact | None, dict]: """The artifact for one auction, and the times it states.""" if not auction.result_artifact: return None, {} url = ARTIFACT_URL.format(name=auction.result_artifact) artifact = await fetcher.get(url, allow_missing=True, missing_max_age=SETTLED) if artifact is None: return None, {} stated = parse_artifact(artifact.text) return artifact, { "release_time": stated.release_time, "competitive_close": stated.competitive_close, "noncompetitive_close": stated.noncompetitive_close, } def calendar_row(auction: Auction, *, artifact: Artifact | None, times: dict) -> dict: row = auction.row announced_on = auction.announcement_date auctioned_on = auction.auction_date close = clock(times.get("competitive_close") or row.get("closingTimeCompetitive")) # A calendar entry becomes public when the auction is announced, not when # it is held. Dating it to the auction would hide the week of notice the # Treasury actually gives. known = end_of_day(announced_on) if announced_on else end_of_day(auctioned_on) return { "auction_id": auction.auction_id, "cusip": row.get("cusip") or None, "security_type": security_type(row), "security_term": row.get("securityTerm") or None, "original_security_term": row.get("originalSecurityTerm") or None, "reopening": to_bool(row.get("reopening")), "announcement_date": announced_on, "announcement_at": end_of_day(announced_on) if announced_on else None, "auction_date": auctioned_on, "auction_at": at(auctioned_on, close) if close else None, "issue_date": to_date(row.get("issueDate")), "maturity_date": to_date(row.get("maturityDate")), "offering_amount": to_float(row.get("offeringAmount")), "status": "published" if auction.has_result else "scheduled", "knowledge_at": known, "knowledge_date": known, "knowledge_time_precision": "date", **provenance(artifact, source=SOURCE_AUCTIONS, url=SEARCH_URL), } def announcement_row(auction: Auction, *, artifact: Artifact | None, times: dict) -> dict | None: row = auction.row announced_on = auction.announcement_date auctioned_on = auction.auction_date if announced_on is None: return None known = end_of_day(announced_on) competitive = clock(times.get("competitive_close") or row.get("closingTimeCompetitive")) noncompetitive = clock( times.get("noncompetitive_close") or row.get("closingTimeNoncompetitive") ) return { "announcement_id": f"{auction.auction_id}_ANN", "auction_id": auction.auction_id, # The announcement states no time of its own, so none is claimed. "release_at": None, "knowledge_at": known, "knowledge_date": known, "knowledge_time_precision": "date", "offering_amount": to_float(row.get("offeringAmount")), "security_type": security_type(row), "security_term": row.get("securityTerm") or None, "cusip": row.get("cusip") or None, "announcement_date": announced_on, "auction_date": auctioned_on, "issue_date": to_date(row.get("issueDate")), "maturity_date": to_date(row.get("maturityDate")), "competitive_close_at": at(auctioned_on, competitive) if competitive else None, "noncompetitive_close_at": at(auctioned_on, noncompetitive) if noncompetitive else None, "reopening": to_bool(row.get("reopening")), "soma_holdings": to_float(row.get("somaHoldings")), "maturing_amount": to_float(row.get("estimatedAmountOfPubliclyHeldMaturingSecuritiesByType")), **provenance(artifact, source=SOURCE_AUCTIONS, url=SEARCH_URL), } def result_row(auction: Auction, *, artifact: Artifact | None, times: dict) -> dict | None: if not auction.has_result: return None row = auction.row auctioned_on = auction.auction_date instant, precision = release_instant(auctioned_on, times.get("release_time")) accepted = to_float(row.get("totalAccepted")) competitive_accepted = to_float(row.get("competitiveAccepted")) tendered = to_float(row.get("totalTendered")) offering = to_float(row.get("offeringAmount")) url = ARTIFACT_URL.format(name=auction.result_artifact) if auction.result_artifact else SEARCH_URL return { "result_id": f"{auction.auction_id}_RES", "auction_id": auction.auction_id, "cusip": row.get("cusip") or None, "security_type": security_type(row), "security_term": row.get("securityTerm") or None, "auction_date": auctioned_on, "issue_date": to_date(row.get("issueDate")), "maturity_date": to_date(row.get("maturityDate")), "result_release_at": instant if precision == "minute" else None, "knowledge_at": instant, "knowledge_date": instant, "knowledge_time_precision": precision, "auction_format": row.get("auctionFormat") or None, "offering_amount": offering, "total_tendered": tendered, "total_accepted": accepted, "competitive_tendered": to_float(row.get("competitiveTendered")), "competitive_accepted": competitive_accepted, # The query publishes what was accepted noncompetitively and whether # noncompetitive tenders were accepted at all, but never an amount # tendered. Copying the accepted figure across would assert that every # noncompetitive bid was filled, which is usually true and is not a # number the Treasury printed. "noncompetitive_tendered": None, "noncompetitive_accepted": to_float(row.get("noncompetitiveAccepted")), "high_yield": to_float(row.get("highYield")), "median_yield": to_float(row.get("averageMedianYield")), "low_yield": to_float(row.get("lowYield")), "high_discount_rate": to_float(row.get("highDiscountRate")), "median_discount_rate": to_float(row.get("averageMedianDiscountRate")), "low_discount_rate": to_float(row.get("lowDiscountRate")), "investment_rate": to_float(row.get("highInvestmentRate")), "interest_rate": to_float(row.get("interestRate")), "price_per_100": to_float(row.get("pricePer100")), "bid_to_cover": to_float(row.get("bidToCoverRatio")), "allocation_percentage": to_float(row.get("allocationPercentage")), "primary_dealer_tendered": to_float(row.get("primaryDealerTendered")), "primary_dealer_accepted": to_float(row.get("primaryDealerAccepted")), "direct_bidder_tendered": to_float(row.get("directBidderTendered")), "direct_bidder_accepted": to_float(row.get("directBidderAccepted")), "indirect_bidder_tendered": to_float(row.get("indirectBidderTendered")), "indirect_bidder_accepted": to_float(row.get("indirectBidderAccepted")), "soma_tendered": to_float(row.get("somaTendered")), "soma_accepted": to_float(row.get("somaAccepted")), "treasury_retail_accepted": to_float(row.get("treasuryRetailAccepted")), "dealer_accepted_pct": share(to_float(row.get("primaryDealerAccepted")), accepted), "direct_accepted_pct": share(to_float(row.get("directBidderAccepted")), accepted), "indirect_accepted_pct": share(to_float(row.get("indirectBidderAccepted")), accepted), "noncompetitive_accepted_pct": share(to_float(row.get("noncompetitiveAccepted")), accepted), "tendered_to_offering": ( round(tendered / offering, 6) if tendered is not None and offering else None ), # The tail is the high yield minus the when-issued market yield, and no # official point-in-time when-issued series exists. The daily par curve # is a different measurement taken at a different moment, and calling # its difference a tail would be a number nobody could trade on. "wi_yield": None, "auction_tail": None, "status": "published", **provenance(artifact, source=SOURCE_AUCTIONS, url=url), } # --------------------------------------------------------------------------- # Curves. # The Treasury generates each year's CSV on request and takes about seventeen # seconds to do it. One at a time, thirty-seven years of five feeds is an hour # of waiting; six at a time it is ten minutes, and six requests in flight is # not a load worth apologising for. A warm run refetches only the current year # of each feed, which is five requests. CURVE_CONCURRENCY = 6 def held_closing_times(data_dir: Path) -> dict[str, dict]: """The closing times a previous run read out of an artifact. Almost every auction has its closing times in the query as well, but five of 11 114 do not: the artifact states a noncompetitive close that the query leaves empty. Rebuilding those announcements from the query alone would quietly drop a field that the dataset already had, and the incremental build would stop matching the full one. """ try: rows = read_table(data_dir, "auction_announcements").collect() except (FileNotFoundError, pl.exceptions.ComputeError): return {} if rows.is_empty(): return {} return { row["auction_id"]: { "competitive_close_at": row["competitive_close_at"], "noncompetitive_close_at": row["noncompetitive_close_at"], } for row in rows.iter_rows(named=True) } def held_curve_years(data_dir: Path, *, first_year: int = FIRST_CURVE_YEAR) -> dict[str, set[int]]: """Which years of which feed a previous run already published. A year of rates that is over cannot change, and each of these files is generated on request and takes the Treasury about seventeen seconds to produce. Refetching thirty-six finished years of five feeds on every scheduled run is half an hour of somebody else's compute to rediscover numbers that are fixed. The current year is always refetched, because it gains a row every trading day. """ this_year = datetime.now(UTC).year held: dict[str, set[int]] = {} for feed, (table, curve_type, _column) in FEED_TABLES.items(): try: rows = read_table(data_dir, table).collect() except (FileNotFoundError, pl.exceptions.ComputeError): continue if rows.is_empty(): continue if curve_type is not None: rows = rows.filter(pl.col("curve_type") == curve_type) if rows.is_empty(): continue # Every past year is settled, not only the ones that produced rows. # The real curve starts in 2003 and the years before it return a file # with nothing but a header; treating those as unread meant fetching # thirteen empty years on every run, forever, to be told again that # they are empty. held[feed] = set(range(first_year, this_year)) return held def held_curve_rows(data_dir: Path, held: dict[str, set[int]]) -> dict[str, pl.DataFrame]: """The published rows for the years being reused, by table.""" frames: dict[str, pl.DataFrame] = {} for feed, years in held.items(): table, curve_type, column = FEED_TABLES[feed] if not years: continue rows = read_table(data_dir, table).collect() if curve_type is not None: rows = rows.filter(pl.col("curve_type") == curve_type) rows = rows.filter(pl.col(column).dt.year().is_in(sorted(years))) frames[table] = ( pl.concat([frames[table], rows], how="vertical") if table in frames else rows ) return frames async def fetch_curves( fetcher: Fetcher, *, first_year: int, skip: dict[str, set[int]] | None = None ) -> dict[str, list]: """Every year of every rate feed that is not already held, a few at a time.""" skip = skip or {} this_year = datetime.now(UTC).year wanted = [ (name, year, RATES_URL.format(year=year, feed=feed)) for name, feed in FEEDS.items() for year in range(first_year, this_year + 1) if year not in skip.get(name, set()) ] LOGGER.info( "%d rate files to fetch, %d years reused", len(wanted), sum(len(years) for years in skip.values()), ) gate = asyncio.Semaphore(CURVE_CONCURRENCY) async def one(name: str, year: int, url: str): async with gate: artifact = await fetcher.get( url, max_age_seconds=CURRENT_YEAR_MAX_AGE if year == this_year else None, allow_missing=True, ) return name, url, artifact collected: dict[str, list] = {name: [] for name in FEEDS} for name, url, artifact in await asyncio.gather(*(one(*item) for item in wanted)): if artifact is None: continue parsed = parse_bill_rates(artifact.text) if name == "bill" else parse_curve(artifact.text) collected[name].extend((point, artifact, url) for point in parsed) for name, rows in collected.items(): LOGGER.info("%s: %d rows", name, len(rows)) return collected def curve_rows(points: list, *, curve_type: str) -> list[dict]: rows = [] for point, artifact, url in points: observed, known, precision = curve_instants(point.curve_date) rows.append( { "curve_id": f"{curve_type}_{point.curve_date:%Y-%m-%d}_{point.maturity}", "curve_date": point.curve_date, "curve_type": curve_type, "maturity": point.maturity, "source_label": point.source_label, "maturity_years": point.maturity_years, "yield_pct": point.yield_pct, "market_observation_at": observed, # What the Treasury actually published is a date and a number. # There is no stated publication instant, so none is claimed. "publication_at": None, "knowledge_at": known, "knowledge_date": known, "knowledge_time_precision": precision, "availability_time_basis": CURVE_TIME_BASIS, "methodology_id": ( methodology_for(point.curve_date) if curve_type == "nominal" else None ), **provenance(artifact, source=SOURCE_RATES, url=url), } ) return rows def bill_rows(points: list) -> list[dict]: rows = [] for point, artifact, url in points: observed, known, precision = curve_instants(point.rate_date) rows.append( { "bill_rate_id": f"bill_{point.rate_date:%Y-%m-%d}_{point.maturity}", "rate_date": point.rate_date, "maturity": point.maturity, "source_label": point.source_label, "maturity_weeks": point.maturity_weeks, "bank_discount_rate": point.bank_discount_rate, "coupon_equivalent_rate": point.coupon_equivalent_rate, "market_observation_at": observed, "knowledge_at": known, "knowledge_date": known, "knowledge_time_precision": precision, "availability_time_basis": CURVE_TIME_BASIS, **provenance(artifact, source=SOURCE_RATES, url=url), } ) return rows def curve_features(nominal: pl.DataFrame, real: pl.DataFrame) -> pl.DataFrame: """Slopes and one spread, from curves published for the same day. Every feature here is arithmetic on two numbers that were public at the same instant, so its `knowledge_at` is that instant and not something earlier. Where a leg is missing -- no 20-year point between 2002 and 2020, no real curve before 2003 -- the feature is null rather than interpolated. """ def wide(frame: pl.DataFrame, prefix: str) -> pl.DataFrame: if frame.is_empty(): return pl.DataFrame(schema={"curve_date": pl.Date}) return ( frame.select("curve_date", "maturity", "yield_pct", "knowledge_at") .pivot(on="maturity", index=["curve_date", "knowledge_at"], values="yield_pct") .rename(lambda name: name if name in {"curve_date", "knowledge_at"} else prefix + name) ) left, right = wide(nominal, "n_"), wide(real, "r_") if "curve_date" not in left.columns or left.is_empty(): return pl.DataFrame(schema=dict(CURVE_FEATURE_SCHEMA)) joined = left.join(right.drop("knowledge_at", strict=False), on="curve_date", how="left") def gap(high: str, low: str) -> pl.Expr: if high not in joined.columns or low not in joined.columns: return pl.lit(None, dtype=pl.Float64) return ((pl.col(high) - pl.col(low)) * 100).round(4) return align( joined.select( feature_id=pl.col("curve_date").dt.strftime("curve_%Y-%m-%d"), curve_date=pl.col("curve_date"), knowledge_at=pl.col("knowledge_at"), knowledge_date=pl.col("knowledge_at"), knowledge_time_precision=pl.lit("modeled_conservative"), slope_3m10y_bp=gap("n_10Y", "n_3M"), slope_2y10y_bp=gap("n_10Y", "n_2Y"), slope_5y30y_bp=gap("n_30Y", "n_5Y"), real_5y10y_slope_bp=gap("r_10Y", "r_5Y"), nominal_10y_minus_real_10y_bp=gap("n_10Y", "r_10Y"), derived_from=pl.lit("nominal_yield_curve, real_yield_curve"), parser_version=pl.lit(PARSER_VERSION), ingested_at=pl.lit(datetime.now(UTC)).cast(pl.Datetime("us", "UTC")), ), CURVE_FEATURE_SCHEMA, ).sort("curve_date") # --------------------------------------------------------------------------- # The run. def held_results(data_dir: Path) -> dict[str, dict]: """The result rows a previous run already published, by auction. A finished auction's result artifact never changes, so a run that already has the row does not need to ask TreasuryDirect for it again. Without this every scheduled run would refetch six thousand artifacts -- forty minutes of somebody else's bandwidth to rediscover numbers that cannot move. What decides reuse is `raw_sha256`, not the precision. A row carrying a digest is one whose artifact was fetched and read, and that is settled whether or not the artifact turned out to state a release time -- 1 357 of them do not, and an earlier version of this function kept refetching every one of them forever, looking for a line that was never going to appear. A row with no digest is one whose artifact was never found. Those are looked for again, in case the Treasury has since published one. """ try: rows = read_table(data_dir, "auction_results").collect() except (FileNotFoundError, pl.exceptions.ComputeError): return {} if rows.is_empty(): return {} return { row["auction_id"]: row for row in rows.iter_rows(named=True) if row["raw_sha256"] } async def build( *, settings: Settings, limit: int | None = None, refresh: bool = False, reuse: bool = True, ) -> tuple[dict[str, pl.DataFrame], list[Quarantined]]: user_agent = validate_user_agent(settings.user_agent) quarantined: list[Quarantined] = [] calendar: list[dict] = [] announcements: list[dict] = [] results: list[dict] = [] async with Fetcher( user_agent=user_agent, cache_dir=Path(settings.cache_dir), requests_per_second=settings.requests_per_second, force_revalidate=refresh, ) as fetcher: auctions, query = await fetch_auctions(fetcher) if limit: auctions = auctions[-limit:] held = held_results(Path(settings.data_dir)) if reuse and not refresh else {} held_times = held_closing_times(Path(settings.data_dir)) if held else {} LOGGER.info( "%d auctions in the query, %d results already held", len(auctions), len(held) ) reused = 0 for index, auction in enumerate(auctions, start=1): known = held.get(auction.auction_id) if known is not None: # The artifact was read on an earlier run and cannot have # changed. Its closing times come from the query, which has # them too. times = { "competitive_close": auction.row.get("closingTimeCompetitive"), "noncompetitive_close": auction.row.get("closingTimeNoncompetitive"), } calendar.append(calendar_row(auction, artifact=query, times=times)) announcement = announcement_row(auction, artifact=query, times=times) if announcement is not None: # Carry forward the two fields that came from the artifact # and are not in the query. for field, value in (held_times.get(auction.auction_id) or {}).items(): if announcement.get(field) is None: announcement[field] = value announcements.append(announcement) results.append(known) reused += 1 continue artifact, times = await result_times(fetcher, auction) calendar.append(calendar_row(auction, artifact=query, times=times)) announcement = announcement_row(auction, artifact=query, times=times) if announcement is not None: announcements.append(announcement) result = result_row(auction, artifact=artifact, times=times) if result is not None: results.append(result) elif auction.has_result: quarantined.append( Quarantined(auction.auction_id, "auction_results", SEARCH_URL, "unreadable") ) if index % 1000 == 0: LOGGER.info("%d/%d auctions read", index, len(auctions)) LOGGER.info("%d results reused, %d read from source", reused, len(results) - reused) held_years = ( held_curve_years(Path(settings.data_dir), first_year=settings.first_curve_year) if reuse and not refresh else {} ) curves = await fetch_curves( fetcher, first_year=settings.first_curve_year, skip=held_years ) reused_curves = held_curve_rows(Path(settings.data_dir), held_years) if held_years else {} def with_held(fresh: pl.DataFrame, table: str) -> pl.DataFrame: keep = reused_curves.get(table) if keep is None or keep.is_empty(): return fresh return pl.concat([keep, fresh], how="vertical_relaxed") frames = { "auction_calendar": align(_frame(calendar), AUCTION_CALENDAR_SCHEMA), "auction_announcements": align(_frame(announcements), ANNOUNCEMENT_SCHEMA), "auction_results": align(_frame(results), RESULT_SCHEMA), "nominal_yield_curve": with_held( align( _frame( curve_rows(curves["nominal"], curve_type="nominal") + curve_rows(curves["long_term_composite"], curve_type="long_term_composite") ), CURVE_SCHEMA, ), "nominal_yield_curve", ), "real_yield_curve": with_held( align( _frame( curve_rows(curves["real"], curve_type="real") + curve_rows(curves["long_term_real"], curve_type="long_term_real") ), CURVE_SCHEMA, ), "real_yield_curve", ), "bill_rates": with_held( align(_frame(bill_rows(curves["bill"])), BILL_RATE_SCHEMA), "bill_rates" ), } frames["curve_features"] = curve_features( frames["nominal_yield_curve"].filter(pl.col("curve_type") == "nominal"), frames["real_yield_curve"].filter(pl.col("curve_type") == "real"), ) frames["pit"] = build_pit(frames) return frames, quarantined def _frame(rows: list[dict]) -> pl.DataFrame: # `infer_schema_length=None` because a column whose first thousand rows are # null is not a null column; it is a column whose values start later, and # the bidder categories start in 2008. if not rows: return pl.DataFrame() return pl.DataFrame(rows, infer_schema_length=None) def run_build( *, settings: Settings, limit: int | None = None, rebuild: bool = False ) -> BuildResult: import shutil frames, quarantined = asyncio.run( build(settings=settings, limit=limit, refresh=rebuild, reuse=not rebuild) ) data_dir = Path(settings.data_dir) counts = {name: write_table(data_dir, name, frame) for name, frame in frames.items()} delta = data_dir / "pit" / PIT_DELTA_NAME if delta.exists(): shutil.rmtree(delta) delta.parent.mkdir(parents=True, exist_ok=True) frames["pit"].write_delta(str(delta), mode="overwrite") metadata = data_dir.resolve().parent / "metadata" metadata.mkdir(parents=True, exist_ok=True) pl.DataFrame( [ { "record_id": item.record_id, "subset": item.subset, "url": item.url, "reason": item.reason, "country": COUNTRY, "quarantined_at": datetime.now(UTC), } for item in quarantined ], schema={ "record_id": pl.String, "subset": pl.String, "url": pl.String, "reason": pl.String, "country": pl.String, "quarantined_at": pl.Datetime(time_unit="us", time_zone="UTC"), }, ).write_parquet(metadata / "quarantine.parquet", compression="zstd") write_registry(metadata) write_coverage(frames, metadata_dir=metadata) write_build_record(frames, metadata_dir=metadata, quarantined=len(quarantined)) return BuildResult(counts=counts, quarantined=quarantined) __all__ = [ "PIT_DELTA_NAME", "BuildResult", "Quarantined", "announcement_row", "bill_rows", "build", "calendar_row", "curve_features", "curve_rows", "held_closing_times", "held_curve_rows", "held_curve_years", "held_results", "result_row", "run_build", "share", ]