File size: 9,029 Bytes
72eadef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """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
|