"""Read the fundamentals dataset, derive the actions, write the tables.""" from __future__ import annotations import logging import shutil from datetime import UTC, datetime, time from pathlib import Path import polars as pl from .config import SIBLING_DIR, SOURCE_REPO, Settings from .dividends import build_dividends from .schema import ADJUSTMENT_SCHEMA, CONFIG_SCHEMAS, PIT_SCHEMA, align, empty_frame from .splits import combine, from_restatements, from_tags from .store import atomic_write_parquet LOGGER = logging.getLogger(__name__) PIT_DELTA_NAME = "corporate_actions.delta" MAX_ROWS_PER_FILE = 5_000_000 def _source_files(settings: Settings, config: str, token: str | None) -> list[Path]: if settings.siblings_dir is not None: local = settings.siblings_dir / SIBLING_DIR / "data" / config files = sorted( path for path in local.rglob("*.parquet") if not any(part.endswith(".delta") for part in path.parts) ) if files: return files from huggingface_hub import snapshot_download LOGGER.info("downloading %s/%s", SOURCE_REPO, config) root = Path( snapshot_download( repo_id=SOURCE_REPO, repo_type="dataset", allow_patterns=[f"data/{config}/**"], token=token, ) ) return sorted( path for path in (root / "data" / config).rglob("*.parquet") if not any(part.endswith(".delta") for part in path.parts) ) def _write(data_dir: Path, table: str, frame: pl.DataFrame) -> int: root = Path(data_dir) / table if root.exists(): shutil.rmtree(root) root.mkdir(parents=True, exist_ok=True) frame = align(frame, CONFIG_SCHEMAS[table]) if frame.is_empty(): atomic_write_parquet(frame, root / "part-00000.parquet") return 0 for index, start in enumerate(range(0, frame.height, MAX_ROWS_PER_FILE)): atomic_write_parquet(frame.slice(start, MAX_ROWS_PER_FILE), root / f"part-{index:05d}.parquet") return frame.height def build_adjustment_factors(splits: pl.DataFrame, *, horizon: datetime) -> pl.DataFrame: """What to multiply an as-filed per-share figure by, to match today's prices. This is the table that closes the hole. A filing states shares as of the day it was made; every price series is adjusted for splits since. Multiply one by the other and the answer is wrong by the split factor -- the failure that turned a 6.9% earnings yield into 41.7% and a P/E of 1.8. The factor is cumulative and stepwise: for a company that split two-for-one in 2020 and three-for-one in 2024, a figure filed in 2019 needs six, one filed in 2021 needs three, one filed today needs one. """ if splits.is_empty(): return empty_frame(ADJUSTMENT_SCHEMA) events = ( splits.filter(pl.col("detected_before").is_not_null()) .select("cik", "ratio", "confidence", pl.col("detected_before").dt.date().alias("on")) .sort(["cik", "on"]) ) rows: list[dict] = [] horizon_day = horizon.date() for cik, group in events.group_by("cik", maintain_order=True): cik_value = cik[0] if isinstance(cik, tuple) else cik days = group["on"].to_list() ratios = group["ratio"].to_list() confidences = group["confidence"].to_list() # Walk backwards: the factor for a span is the product of every split # that happened after it. cumulative = 1.0 boundaries = [*days, horizon_day] for index in range(len(days) - 1, -1, -1): cumulative *= ratios[index] rows.append({ "cik": cik_value, "valid_from": None if index == 0 else boundaries[index - 1], "valid_to": boundaries[index], "cumulative_split_factor": cumulative, "splits_after": len(days) - index, "confidence": min(confidences[index:], key=lambda c: {"high": 0, "medium": 1}.get(c, 2)), }) rows.append({ "cik": cik_value, "valid_from": boundaries[-2], "valid_to": None, "cumulative_split_factor": 1.0, "splits_after": 0, "confidence": "high", }) frame = pl.DataFrame(rows, strict=False).with_columns( pl.lit(datetime.now(UTC)).alias("inserted_at") ) return align(frame, ADJUSTMENT_SCHEMA).sort(["cik", "valid_to"]) def build_pit(dividends: pl.DataFrame, splits: pl.DataFrame, *, run_at: datetime) -> pl.DataFrame: """Both action types in one point-in-time table. A dividend's knowledge date is the acceptance of the filing that stated it, to the second. A split's is the acceptance of the first filing that showed the restated figures -- the earliest moment the split was demonstrably public, which is later than it happened and therefore safe. """ parts: list[pl.DataFrame] = [] if not dividends.is_empty(): parts.append( dividends.with_columns( pl.concat_str( [pl.col("accession_number"), pl.col("kind"), pl.col("security_class"), pl.col("period_end").cast(pl.String)], separator="|" ).alias("pit_event_id"), pl.col("cik").alias("entity_id"), pl.col("period_end").alias("event_date"), pl.col("accepted_at").alias("knowledge_date"), pl.lit(False).alias("knowledge_estimated"), pl.concat_str([pl.lit("dividend_"), pl.col("kind")]).alias("action_type"), pl.lit(None, dtype=pl.Float64).alias("split_ratio"), pl.lit("high").alias("confidence"), ) ) if not splits.is_empty(): parts.append( splits.with_columns( pl.concat_str( [pl.col("cik"), pl.lit("split"), pl.col("ratio").cast(pl.String)], separator="|", ).alias("pit_event_id"), pl.col("cik").alias("entity_id"), pl.col("detected_before").dt.date().alias("event_date"), pl.col("detected_before").alias("knowledge_date"), pl.lit(True).alias("knowledge_estimated"), pl.lit("split").alias("action_type"), pl.col("ratio").alias("split_ratio"), pl.lit(None, dtype=pl.Float64).alias("amount_per_share"), pl.lit(None, dtype=pl.String).alias("currency"), pl.lit(None, dtype=pl.String).alias("security_class"), pl.lit(None, dtype=pl.Int32).alias("quarters"), pl.lit(False).alias("is_subsequent_event"), ) ) if not parts: return empty_frame(PIT_SCHEMA) frame = pl.concat([align(part, PIT_SCHEMA) for part in parts], how="vertical_relaxed") return frame.with_columns(pl.lit(run_at).alias("ingested_at")).sort( ["entity_id", "event_date", "knowledge_date"] ) def run_build(*, settings: Settings, token: str | None = None) -> dict[str, int]: data_dir = Path(settings.data_dir) run_at = datetime.now(UTC) facts = pl.scan_parquet(_source_files(settings, "facts", token)) dimensional = pl.scan_parquet(_source_files(settings, "facts_dimensional", token)) fundamentals = pl.scan_parquet(_source_files(settings, "fundamentals", token)) dividends = build_dividends( pl.concat( [facts.select( "cik", "accession_number", "tag", "value", "unit", "period_end", "quarters", "form", "fiscal_year", "fiscal_period", "filed_date", "accepted_at", ).with_columns(pl.lit(None, dtype=pl.String).alias("segments")), dimensional.select( "cik", "accession_number", "tag", "value", "unit", "period_end", "quarters", "form", "fiscal_year", "fiscal_period", "filed_date", "accepted_at", "segments", )], how="vertical_relaxed", ) ) LOGGER.info("dividends: %d rows, %d filers", dividends.height, dividends["cik"].n_unique()) tagged = from_tags(pl.concat([facts, dimensional], how="diagonal_relaxed")) inferred = from_restatements(fundamentals) splits = combine(tagged, inferred) LOGGER.info( "splits: %d (tagged %d, inferred %d), %d filers", splits.height, tagged.height, inferred.height, splits["cik"].n_unique(), ) factors = build_adjustment_factors(splits, horizon=run_at) pit = build_pit(dividends, splits, run_at=run_at) counts = { "dividends": _write(data_dir, "dividends", dividends), "splits": _write(data_dir, "splits", splits), "adjustment_factors": _write(data_dir, "adjustment_factors", factors), "pit": _write(data_dir, "pit", pit), } delta = data_dir / "pit" / PIT_DELTA_NAME if delta.exists(): shutil.rmtree(delta) if not pit.is_empty(): align(pit, PIT_SCHEMA).write_delta(str(delta), mode="overwrite") _ = time return counts