File size: 6,579 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
"""Checks that decide whether a build may be published.

Splits are the risky half. A wrong ratio does not raise -- it rescales a
company's whole per-share history by a factor of two and the result still looks
like a price series. So the checks are about the ratios being declared ones,
the factors composing consistently, and the inferred set not drifting away from
the tagged set that validates it.
"""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import polars as pl

from .splits import KNOWN_RATIOS
from .store import read_table

MIN_DIVIDEND_FILERS = 2_000
MIN_SPLIT_FILERS = 800
# The inferred method agreed with the tagged ratio for 79% of the companies
# where both exist. The floor sits below that: a drop means the restatement
# signal has started picking up something that is not a split.
MIN_METHOD_AGREEMENT = 0.65


@dataclass
class QualityReport:
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    metrics: dict[str, Any] = field(default_factory=dict)

    def error(self, message: str) -> None:
        self.errors.append(message)

    def warn(self, message: str) -> None:
        self.warnings.append(message)

    def metric(self, name: str, value: Any) -> None:
        self.metrics[name] = value

    @property
    def ok(self) -> bool:
        return not self.errors

    def as_dict(self) -> dict[str, Any]:
        return {
            "ok": self.ok,
            "generated_at": datetime.now(UTC).isoformat(),
            "errors": self.errors,
            "warnings": self.warnings,
            "metrics": self.metrics,
        }

    def write(self, path: Path) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8")


def validate(data_dir: Path) -> QualityReport:
    report = QualityReport()
    data_dir = Path(data_dir)
    dividends = read_table(data_dir, "dividends").collect()
    splits = read_table(data_dir, "splits").collect()
    factors = read_table(data_dir, "adjustment_factors").collect()
    pit = read_table(data_dir, "pit").collect()

    for name, frame in (("dividends", dividends), ("splits", splits),
                        ("adjustment_factors", factors), ("pit", pit)):
        report.metric(f"rows_{name}", frame.height)

    if dividends.is_empty():
        report.error("dividends table is empty")
        return report

    filers = dividends["cik"].n_unique()
    report.metric("dividend_filers", filers)
    if filers < MIN_DIVIDEND_FILERS:
        report.error(f"only {filers} filers pay dividends, below the {MIN_DIVIDEND_FILERS} floor")
    negative = dividends.filter(pl.col("amount_per_share") < 0).height
    if negative:
        report.error(f"dividends: {negative} negative amounts per share")
    report.metric(
        "dividends_by_kind",
        {r["kind"]: r["n"] for r in dividends.group_by("kind").agg(pl.len().alias("n")).iter_rows(named=True)},
    )
    report.metric(
        "dividend_subsequent_events",
        dividends.filter(pl.col("is_subsequent_event")).height,
    )
    restated = dividends.filter(pl.col("revision") > 1).height
    report.metric("dividend_restated_rows", restated)

    if splits.is_empty():
        report.error("splits table is empty")
        return report

    split_filers = splits["cik"].n_unique()
    report.metric("split_filers", split_filers)
    report.metric(
        "splits_by_method",
        {r["method"]: r["n"] for r in splits.group_by("method").agg(pl.len().alias("n")).iter_rows(named=True)},
    )
    report.metric(
        "splits_by_confidence",
        {r["confidence"]: r["n"] for r in splits.group_by("confidence").agg(pl.len().alias("n")).iter_rows(named=True)},
    )
    if split_filers < MIN_SPLIT_FILERS:
        report.error(f"only {split_filers} filers have a split, below the {MIN_SPLIT_FILERS} floor")

    # Every published ratio has to be one companies actually declare. A ratio of
    # 1.83 is a restatement that slipped through, not a split.
    allowed = [ratio for ratio, _label in KNOWN_RATIOS]
    stray = splits.filter(~pl.col("ratio").is_in(allowed)).height
    if stray:
        report.error(f"splits: {stray} rows carry a ratio that is not a declared one")
    if splits.filter(pl.col("detected_before") < pl.col("detected_after")).height:
        report.error("splits: detection windows that end before they start")

    # Agreement is measured over the events strong enough to be relied on. The
    # low-confidence tail is published for completeness, not for gating.
    strong = splits.filter(pl.col("confidence").is_in(["high", "medium"]))
    both = strong.filter(pl.col("corroborated_by") == "xbrl_tag+eps_restatement")["cik"].n_unique()
    tagged_filers = strong.filter(pl.col("method") == "xbrl_tag")["cik"].n_unique()
    if tagged_filers:
        agreement = both / tagged_filers
        report.metric("method_agreement", round(agreement, 4))
        if agreement < MIN_METHOD_AGREEMENT:
            report.error(
                f"the inferred and tagged methods agree for {agreement:.1%} of tagged filers, "
                f"below the {MIN_METHOD_AGREEMENT:.0%} floor"
            )

    if not factors.is_empty():
        report.metric("factor_filers", factors["cik"].n_unique())
        if factors.filter(pl.col("cumulative_split_factor") <= 0).height:
            report.error("adjustment_factors: non-positive factor")
        # The newest span of every filer is the present, where nothing needs
        # adjusting. A factor other than one there means the walk backwards
        # started from the wrong end.
        latest = factors.filter(pl.col("valid_to").is_null())
        wrong = latest.filter(pl.col("cumulative_split_factor") != 1.0).height
        if wrong:
            report.error(f"adjustment_factors: {wrong} filers whose current factor is not 1.0")
        report.metric("factor_max", float(factors["cumulative_split_factor"].max()))

    if not pit.is_empty():
        for column in ("entity_id", "event_date", "knowledge_date"):
            if pit[column].null_count():
                report.error(f"pit.{column}: {pit[column].null_count()} nulls")
        report.metric(
            "pit_by_action",
            {r["action_type"]: r["n"] for r in pit.group_by("action_type").agg(pl.len().alias("n")).iter_rows(named=True)},
        )
    return report


__all__ = ["QualityReport", "validate"]