Skip to Content

Point-in-time data

Join slow-moving data to decisions using only what was published by then, and check datasets, revisions, membership and universes for look-ahead and survivorship.

A backtest decides at one moment and later learns what happened. Look-ahead enters when the data used at the decision was not yet known: an earnings figure that was published six weeks after its quarter ended, a number that was restated months later, an index whose membership list was written with hindsight. The backtest looks fine because it used information that did not exist.

lacuna.bias makes those timing assumptions explicit. asof_join attaches each decision’s most recently published record and nothing newer. The other functions check the tables that feed it (a dataset’s structure, its revision history, its membership intervals) and report what they can and cannot establish. Anything that cannot be established is UNKNOWN, not a pass. Read Time and data for the shared timing vocabulary.

A first example

A company reports earnings per share (EPS) for the quarter ended 31 December on 20 February, revises it on 10 March, and reports the next quarter on 5 May. Each row of facts is one published version. We decide on four dates.

from datetime import date

import lacuna as lc
import polars as pl

facts = pl.DataFrame(
    {
        "instrument": ["AAA", "AAA", "AAA"],
        "effective_time": [date(2024, 12, 31), date(2024, 12, 31), date(2025, 3, 31)],
        "available_time": [date(2025, 2, 20), date(2025, 3, 10), date(2025, 5, 5)],
        "revision_id": [1, 2, 1],
        "eps": [1.00, 1.40, 1.10],
    }
)
decisions = pl.DataFrame(
    {
        "instrument": ["AAA"] * 4,
        "decision_time": [date(2025, 2, 28), date(2025, 3, 12), date(2025, 4, 15), date(2025, 5, 6)],
    }
)

The common shortcut keeps the latest revision of each quarter and matches on the quarter-end date. It looks reasonable and leaks twice.

latest = (
    facts.sort("revision_id")
    .group_by("instrument", "effective_time", maintain_order=True)
    .last()
    .sort("effective_time")
)
naive = decisions.join_asof(
    latest,
    left_on="decision_time",
    right_on="effective_time",
    by="instrument",
    check_sortedness=False,
)
print(naive.select("decision_time", "effective_time", "available_time", "eps"))
shape: (4, 4)
┌───────────────┬────────────────┬────────────────┬─────┐
│ decision_time ┆ effective_time ┆ available_time ┆ eps │
│ ---           ┆ ---            ┆ ---            ┆ --- │
│ date          ┆ date           ┆ date           ┆ f64 │
╞═══════════════╪════════════════╪════════════════╪═════╡
│ 2025-02-28    ┆ 2024-12-31     ┆ 2025-03-10     ┆ 1.4 │
│ 2025-03-12    ┆ 2024-12-31     ┆ 2025-03-10     ┆ 1.4 │
│ 2025-04-15    ┆ 2025-03-31     ┆ 2025-05-05     ┆ 1.1 │
│ 2025-05-06    ┆ 2025-03-31     ┆ 2025-05-05     ┆ 1.1 │
└───────────────┴────────────────┴────────────────┴─────┘

On 28 February the naive join uses 1.40, a revision nobody knew until 10 March. On 15 April it uses the March-quarter figure, which was not published until 5 May. In both rows available_time is later than decision_time. Because the naive frame carries both columns, future_data_check finds them:

check = lc.bias.future_data_check(naive)
print(check.metrics["future_rows"], check.metrics["future_fraction"])
print([(f.code, f.state.value) for f in check.findings])
2 0.5
[('BIAS_FUTURE_DATA', 'FAIL')]

Now the as-of join. It keeps, for each decision, the most recently published record for the same instrument, and breaks ties between versions published together with revision.

joined = lc.bias.asof_join(
    decisions,
    facts,
    effective_time="effective_time",
    revision="revision_id",
    revision_mode="point_in_time",
)
print(joined.frame.select("decision_time", "effective_time", "available_time", "revision_id", "eps"))
shape: (4, 5)
┌───────────────┬────────────────┬────────────────┬─────────────┬─────┐
│ decision_time ┆ effective_time ┆ available_time ┆ revision_id ┆ eps │
│ ---           ┆ ---            ┆ ---            ┆ ---         ┆ --- │
│ date          ┆ date           ┆ date           ┆ i64         ┆ f64 │
╞═══════════════╪════════════════╪════════════════╪═════════════╪═════╡
│ 2025-02-28    ┆ 2024-12-31     ┆ 2025-02-20     ┆ 1           ┆ 1.0 │
│ 2025-03-12    ┆ 2024-12-31     ┆ 2025-03-10     ┆ 2           ┆ 1.4 │
│ 2025-04-15    ┆ 2024-12-31     ┆ 2025-03-10     ┆ 2           ┆ 1.4 │
│ 2025-05-06    ┆ 2025-03-31     ┆ 2025-05-05     ┆ 1           ┆ 1.1 │
└───────────────┴────────────────┴────────────────┴─────────────┴─────┘

Each row now uses the newest record published on or before its decision. The 28 February decision sees the original 1.00. The 15 April decision still sees the restated 1.40, because the March quarter had not been published. The result also carries evidence:

print(joined.evidence.metrics["matched_rows"], joined.evidence.metrics["max_information_age"])
print([(f.code, f.state.value) for f in joined.evidence.findings])
4 36
[('BIAS_ASOF_TEMPORAL_FIREWALL', 'PASS')]

max_information_age is the staleness of the oldest match, in days here because the time columns are dates; information_age_unit names the unit. The PASS finding is conditional: it needs a declared revision_mode and no unmatched rows. See What the evidence does not prove.

Availability, effective and decision time

A fact has several times, and mixing them up is the usual source of look-ahead.

TimeMeaningExample
EffectiveWhen the fact applies economically.The quarter ended on 31 December.
AvailableWhen the fact became known to the market or to you.The report appeared on 20 February.
RevisionWhich version of the fact this is.The first report, then the restatement.
DecisionWhen your strategy acted.The close on 28 February.

A record is usable at a decision only if available_time <= decision_time. The effective time says what the fact is about and is not a substitute for availability. Joining on the quarter-end date, as the naive join did, silently treats every fact as known the moment its period ends.

As-of joins

asof_join(left, right, ...) returns one row per left row, in the left table’s original order, unless unmatched="drop" removes the rows with no match. left holds the decisions and right holds the published records. For each left row it picks the right row, within the same by key, with the greatest availability time that is at most the decision time. A right row dated after the decision is never eligible.

Keys and time columns

by is the identity, "instrument" by default. Use a stable instrument identifier, not a ticker that can be reused. by can be a list for composite keys. The left and right time columns, and the identity columns, must have the same dtype on both sides.

An empty left table raises a DataContractError. Left rows must have no nulls in the decision time or the identity. Right rows must have no nulls in the availability time or the identity, and none in revision when you pass one.

Time columns can be Date, Datetime, Duration, integers, or floats holding whole numbers (1.0 passes, 1.5 raises). The evidence records Duration values as ISO 8601 text, such as "P1D". Identity columns can be strings, categoricals, enums, integers or whole-number floats.

Exact matches

allow_exact_matches=True, the default, treats a record published at exactly the decision time as usable. Set it to False when a record stamped at the decision timestamp would not yet have been seen, for example when both times are daily dates but the data is published after the close and you decide at the close.

Staleness

tolerance is the maximum age of a usable record: a match is rejected when the decision time minus the availability time exceeds it. Lacuna checks it against the unit system of the decision-time column before joining, and raises a MethodContractError for anything that does not fit.

Decision-time columnAcceptedRejected
Date, Datetime, DurationA non-negative timedelta, or a fixed-length lowercase duration string such as "30d" or "1h30m" (units ns, us, ms, s, m, h, d, w).A bare number, because it has no unit on a temporal column. Uppercase units ("30D"), calendar-variable units ("1mo", "1q", "1y"), negative strings and a negative timedelta.
Integer, or float holding whole numbersA non-negative whole number in the column’s own units (5 or 5.0).A fractional number (5.5), a negative number, a string and a timedelta.

A bool, NaN or infinite tolerance is rejected for every column type. Without a tolerance a record that is a year old still matches.

lc.bias.asof_join(decisions, facts, revision="revision_id", tolerance=30)
MethodContractError: numeric tolerance has no unit for Date time columns; pass a timedelta or a fixed-length duration string such as '30d'

Pass "30d" or timedelta(days=30) instead:

stale = lc.bias.asof_join(
    decisions,
    facts,
    revision="revision_id",
    revision_mode="point_in_time",
    tolerance="30d",
)
print(stale.frame.select("decision_time", "available_time", "eps"))
print(stale.evidence.metrics["unmatched_rows"], stale.evidence.metrics["stale_matches_rejected"])
shape: (4, 3)
┌───────────────┬────────────────┬──────┐
│ decision_time ┆ available_time ┆ eps  │
│ ---           ┆ ---            ┆ ---  │
│ date          ┆ date           ┆ f64  │
╞═══════════════╪════════════════╪══════╡
│ 2025-02-28    ┆ 2025-02-20     ┆ 1.0  │
│ 2025-03-12    ┆ 2025-03-10     ┆ 1.4  │
│ 2025-04-15    ┆ null           ┆ null │
│ 2025-05-06    ┆ 2025-05-05     ┆ 1.1  │
└───────────────┴────────────────┴──────┘
1 1

On 15 April the newest record is the 10 March revision, 36 days old. It is rejected, so the row is unmatched, and the metrics count it separately in stale_matches_rejected so a missing value is distinguishable from a stale one.

Unmatched rows

unmatched sets what happens to left rows with no usable record.

ValueBehaviour
"keep"Keep the row with null right-side columns. This is the default.
"drop"Remove the row from the output.
"raise"Raise a DataContractError.

Any unmatched row, kept or dropped, adds a BIAS_ASOF_UNMATCHED warning with the counts.

Revisions and ties

When the same key has several records with the same availability time, which one is the answer? Lacuna refuses to guess from row order. With no revision column, such ties raise a DataContractError. With one, the row with the greatest revision value wins, and the number of rows involved is recorded as revision_tie_rows. Revisions are compared in the column’s natural order, so asof_join only accepts a revision dtype that has one: integer, finite float, Date, Datetime, Duration or an Enum. String and categorical revisions raise a DataContractError, because they sort lexicographically ("9" would beat "10"). Cast the column to an integer, or to an Enum listing the versions in order. An exact duplicate of the key, availability time and revision also raises.

revision_mode declares what you know about the source’s revision history.

ValueMeaningEffect on findings
"point_in_time"The source keeps every historical version.No revision finding; the join can pass.
"latest_only"The source holds only the latest value of each fact.BIAS_REVISION_LATEST_ONLY, UNKNOWN.
"unknown"Not established. This is the default.BIAS_REVISION_STATUS_UNKNOWN, UNKNOWN.
"not_applicable"The data is never revised.No revision finding.

This is a declaration. Lacuna cannot tell from the rows whether the vendor dropped old versions, so declaring "point_in_time" is your claim, recorded in the result. "latest_only" is the honest label for most free fundamentals sources, and it keeps the audit from reporting the join as safe.

The effective time does not choose the row

effective_time is an optional right-side column. Lacuna validates that it is a time column, carries it through to the output, and records its name. It does not use it to pick a row. The join returns the most recently published record, whichever period that record describes. Passing effective_time adds a result warning saying so, because the argument can look as if it filters by period.

That matters when an old period is restated after a newer one is published. The restatement is the newest record, so it is what the join returns, and it hides the newer period’s figure.

restated = pl.DataFrame(
    {
        "instrument": ["AAA"] * 3,
        "effective_time": [date(2024, 12, 31), date(2025, 3, 31), date(2024, 12, 31)],
        "available_time": [date(2025, 2, 20), date(2025, 5, 5), date(2025, 6, 1)],
        "revision_id": [1, 1, 2],
        "eps": [1.00, 1.10, 1.40],
    }
)
later = pl.DataFrame({"instrument": ["AAA"], "decision_time": [date(2025, 6, 2)]})
result = lc.bias.asof_join(
    later, restated, effective_time="effective_time", revision="revision_id", revision_mode="point_in_time"
)
print(result.frame.select("decision_time", "effective_time", "available_time", "eps"))
shape: (1, 4)
┌───────────────┬────────────────┬────────────────┬─────┐
│ decision_time ┆ effective_time ┆ available_time ┆ eps │
│ ---           ┆ ---            ┆ ---            ┆ --- │
│ date          ┆ date           ┆ date           ┆ f64 │
╞═══════════════╪════════════════╪════════════════╪═════╡
│ 2025-06-02    ┆ 2024-12-31     ┆ 2025-06-01     ┆ 1.4 │
└───────────────┴────────────────┴────────────────┴─────┘

On 2 June the March-quarter figure (1.10) was already public, but the December-quarter restatement published on 1 June is newer, so that is the record returned. This is the correct answer to “what was the most recent publication for this instrument”, and it may not be the answer to “what is the latest quarter”. Check the carried effective_time in the output, and if your strategy wants the newest period, filter or reshape the right table before joining.

Output and evidence

The output keeps every left column, then the right columns. A right column whose name collides with a left column gets suffix appended ("_right" by default), including the availability column when the left table has one with the same name.

MetricMeaning
left_rows, right_rows, output_rowsRow counts. output_rows is smaller than left_rows only with unmatched="drop".
matched_rows, unmatched_rowsLeft rows with and without a usable record.
stale_matches_rejectedUnmatched rows that had an eligible record outside tolerance.
revision_tie_rowsRight rows that shared a key and availability time with another row.
mean_information_age, median_information_age, max_information_ageDecision time minus matched availability time, in information_age_unit.
future_matchesMatched rows whose selected availability time is later than the decision time, counted on the joined output.

future_matches is computed from the output, so it is a real check of the result rather than a constant. The join is built so that it cannot select a later record, which means the count is 0 unless something is badly wrong, and if it were not 0 the join would raise instead of returning.

Revision history

revision_diagnostics(data, ...) checks a table of versioned facts before you join it. A fact is identified by entity plus effective_time; each version of it has a revision and an available_time.

history = lc.bias.revision_diagnostics(facts, source_mode="point_in_time", value="eps")
print(history.metrics["fact_count"], history.metrics["revised_facts"])
print([(f.code, f.state.value) for f in history.findings])
print(history.table("facts")[0])
2 1
[('BIAS_REVISION_HISTORY_VALID', 'PASS')]
{'instrument': 'AAA', 'effective_time': '2024-12-31', 'version_count': 2, 'first_available_time': '2025-02-20', 'last_available_time': '2025-03-10', 'distinct_value_count': 2}

It raises on duplicate version identities (the same fact and revision twice), and on a string or categorical revision column, for the same reason as asof_join. It fails with BIAS_REVISION_ORDER_INVALID when a higher revision became available before a lower one, which usually means the revision numbers or the timestamps are wrong. With source_mode="latest_only" or "unknown", it reports UNKNOWN and never passes: structure can be valid and still incomplete, because a vendor that kept only some versions produces a clean-looking table. Pass revision=None to identify versions by availability time instead of a revision column. source_mode="point_in_time" requires a revision column, and "not_applicable" is rejected, since a source with no revisions needs no diagnostics.

Dataset contracts

DatasetSpec declares what a table must look like; validate_dataset checks a table against it and reports every violation instead of stopping at the first.

spec = lc.bias.DatasetSpec(
    name="fundamentals",
    required=("instrument", "effective_time", "available_time", "revision_id", "eps"),
    keys=("instrument", "effective_time", "revision_id"),
    non_null=("instrument", "eps"),
    numeric=("eps",),
    temporal=("effective_time", "available_time"),
    temporal_order=(("effective_time", "available_time"),),
)
print([(f.code, f.state.value) for f in lc.bias.validate_dataset(facts, spec=spec).findings])

dirty = facts.with_columns(
    eps=pl.Series([1.0, None, float("nan")]),
    available_time=pl.Series([date(2024, 1, 1), date(2025, 5, 5), date(2025, 6, 1)]),
).vstack(facts.head(1))
report = lc.bias.validate_dataset(dirty, spec=spec)
for finding in report.findings:
    print(finding.code, finding.state.value)
[('DATASET_CONTRACT_VALID', 'PASS')]
DATASET_NULL_CONSTRAINT_FAILED FAIL
DATASET_KEY_NOT_UNIQUE FAIL
DATASET_NONFINITE_VALUES FAIL
DATASET_TEMPORAL_ORDER_INVALID FAIL

The first call passes. The second reports four separate failures: a null eps (non_null), a repeated key because the appended row duplicates the first (keys), a NaN in eps (numeric), and an available_time earlier than its effective_time (temporal_order).

FieldChecks
requiredEvery column exists. Every other field may reference only required columns.
keysThe combination is unique. Rows in a duplicated group all count as duplicates.
non_nullNo nulls in these columns.
numericThe dtype is numeric, and no value is NaN or infinite.
temporalThe dtype is an ordered time type (Date, Datetime, Duration, integer or whole-number float).
temporal_orderEach (earlier, later) pair satisfies earlier <= later on rows where both are present. Both columns must also be in temporal. If the two columns have different dtypes, every row is reported as a violation.

An empty table fails with DATASET_EMPTY. A table that passes every check gets one PASS finding, DATASET_CONTRACT_VALID.

Checking for future data

future_data_check is the direct test: how many rows have an availability time after their decision time? Use it on any table that already carries both columns, such as a joined feature table, a signal table, or a join someone else built. The two columns must share a dtype, which can be Duration as well as a date or datetime.

signals = pl.DataFrame(
    {
        "instrument": ["AAA", "AAA", "BBB"],
        "decision_time": [date(2025, 3, 1)] * 3,
        "available_time": [date(2025, 2, 1), date(2025, 3, 10), None],
        "signal": [1.0, -4.0, 2.0],
    },
    schema_overrides={"available_time": pl.Date},
)
check = lc.bias.future_data_check(signals, materiality="signal")
print(check.metrics["future_rows"], check.metrics["missing_availability_rows"])
print(check.metrics["future_materiality_fraction"])
print([(f.code, f.state.value, f.severity.value) for f in check.findings])
1 1
0.5714285714285714
[('BIAS_FUTURE_DATA', 'FAIL', 'critical'), ('BIAS_AVAILABILITY_MISSING', 'UNKNOWN', 'high')]

Rows available exactly at the decision time are fine; they are counted in equal_boundary_rows so you can see how many sit on the boundary. A missing availability time cannot be classified, so it is UNKNOWN, not clear. The instrument column defaults to "instrument" and must exist, or the call raises a DataContractError for missing columns; pass instrument=None when your table has no identity column. Pass materiality, a numeric column such as a position size or signal value, to measure how much of the total absolute weight sits on the leaking rows (future_materiality_fraction). Ten leaking rows of tiny positions matter less than one leaking row of the largest. The future_rows table lists up to max_examples offending rows.

Membership and survivorship

An index or universe changes over time. If you test on today’s constituents you have already filtered out every company that failed, which is survivorship bias. A membership table fixes that by recording intervals: an instrument belongs to a universe from valid_from up to, but not including, valid_to. A null valid_to means still a member. Intervals are half-open, [valid_from, valid_to), so an instrument is not a member on its valid_to date.

Each row also has an available_time: when that membership fact became known. An index provider might announce an addition weeks before it takes effect (fine) or publish a historical list years later (not fine for a backtest).

members = pl.DataFrame(
    {
        "index": ["IDX"] * 4,
        "instrument": ["AAA", "BBB", "CCC", "DDD"],
        "valid_from": [date(2020, 1, 1), date(2020, 1, 1), date(2021, 6, 1), date(2022, 1, 1)],
        "valid_to": [None, date(2022, 12, 31), date(2024, 1, 1), None],
        "available_time": [date(2020, 1, 1), date(2020, 1, 1), date(2021, 5, 15), date(2022, 3, 1)],
        "delisted": [False, True, False, False],
    },
    schema_overrides={"valid_to": pl.Date},
)
audit = lc.bias.survivorship_diagnostics(
    members, delisted="delisted", source_status="confirmed_safe", includes_delisted=True
)
print(audit.metrics["late_availability_rows"])
print([(f.code, f.state.value) for f in audit.findings])
1
[('BIAS_MEMBERSHIP_LATE_AVAILABILITY', 'FAIL')]

DDD joined on 1 January 2022 but the source only knew that on 1 March. The diagnostics fail the table with BIAS_MEMBERSHIP_LATE_AVAILABILITY, because a backtest that used the table would include DDD two months before anyone could have known it was a member.

Source status

source_status is your declaration about how the source was built. Lacuna checks the intervals and timestamps; it cannot see whether the vendor kept the delisted companies.

SurvivorshipStatusMeaningFinding
"confirmed_safe"The source keeps delisted instruments and historical membership. Requires delisted= and includes_delisted=True.BIAS_SURVIVORSHIP_SAFE (PASS) only if the structural checks pass and at least one row is marked delisted. With no delisted row, BIAS_SURVIVORSHIP_DELISTINGS_NOT_OBSERVED (UNKNOWN).
"confirmed_biased"The source filtered history using future survival.BIAS_SURVIVORSHIP_CONFIRMED, FAIL, critical.
"unknown"Not established. This is the default.BIAS_SURVIVORSHIP_UNKNOWN, UNKNOWN.

You can pass the enum, lc.bias.SurvivorshipStatus.CONFIRMED_SAFE, or its string value. If a structural check fails (invalid or overlapping intervals, or late availability) or any availability timestamp is missing, the structural finding is reported and "confirmed_safe" gets no PASS, because a table with those problems cannot support a safe claim. "unknown" and "confirmed_biased" still add their survivorship finding alongside the structural one. The PASS needs at least one row marked delisted. A "confirmed_safe" source whose delisted column marks no row (all False, or nulls, which count as False) gets BIAS_SURVIVORSHIP_DELISTINGS_NOT_OBSERVED with state UNKNOWN instead: the declaration that delisted history is included is not corroborated by the data.

survivors_only = members.filter(~pl.col("delisted")).with_columns(available_time=pl.col("valid_from"))
check = lc.bias.survivorship_diagnostics(
    survivors_only, delisted="delisted", source_status="confirmed_safe", includes_delisted=True
)
print([(f.code, f.state.value) for f in check.findings])
[('BIAS_SURVIVORSHIP_DELISTINGS_NOT_OBSERVED', 'UNKNOWN')]

The structural checks are: valid_from < valid_to on every closed interval, no two intervals for the same identity overlapping, no available_time after valid_from, and missing availability timestamps reported as UNKNOWN. identity is the key that defines one membership, ("index", "instrument") by default. Pass the names of your columns if they differ.

Membership at a date

membership_at(data, as_of=...) returns the instruments that were members, and observable as members, at one instant.

early = lc.bias.membership_at(members, as_of=date(2022, 1, 10))
print(early.frame["instrument"].to_list())
print(early.evidence.metrics["not_yet_available_rows"])
print([(f.code, f.state.value) for f in early.evidence.findings])

after = lc.bias.membership_at(members, as_of=date(2022, 12, 31))
print(after.frame["instrument"].to_list())
['AAA', 'BBB', 'CCC']
1
[('BIAS_MEMBERSHIP_NOT_YET_AVAILABLE', 'WARN'), ('BIAS_SURVIVORSHIP_UNKNOWN', 'UNKNOWN')]
['AAA', 'CCC', 'DDD']

On 10 January 2022 DDD’s interval has begun, but its availability time is March, so the availability firewall excludes it and a BIAS_MEMBERSHIP_NOT_YET_AVAILABLE warning counts the exclusion. On 31 December 2022 BBB is gone, because that is its valid_to and intervals are half-open.

membership_at returns a MembershipResult: frame holds the active, observable rows sorted by identity, and evidence holds the counts and findings. The rows excluded by the firewall are listed in evidence.table("excluded_active_rows"). A row with a null available_time is excluded and counted the same way as a not-yet-available row, so it also triggers BIAS_MEMBERSHIP_NOT_YET_AVAILABLE. It raises a DataContractError if intervals are invalid or overlap, because an ambiguous membership has no answer. Since source_status defaults to "unknown", the result above is UNKNOWN, not safe; a PASS needs a declared "confirmed_safe" source.

Universe drift

universe_drift takes dated snapshots of a universe (one row per instrument per snapshot) and measures how much each snapshot differs from the one before. For consecutive snapshots with membership sets A and B:

retention=∣A∩B∣∣A∣,jaccard=∣A∩B∣∣A∪B∣,drift=1−jaccard\text{retention} = \frac{\lvert A \cap B \rvert}{\lvert A \rvert}, \qquad \text{jaccard} = \frac{\lvert A \cap B \rvert}{\lvert A \cup B \rvert}, \qquad \text{drift} = 1 - \text{jaccard}
snapshots = pl.DataFrame(
    {
        "snapshot_time": [date(2024, 1, 31)] * 4 + [date(2024, 2, 29)] * 4 + [date(2024, 3, 29)] * 3,
        "instrument": ["A", "B", "C", "D", "A", "B", "C", "E", "A", "B", "F"],
    }
)
drift = lc.bias.universe_drift(snapshots, warning_threshold=0.5)
print(drift.metrics["mean_drift"], drift.metrics["maximum_drift"], drift.metrics["high_drift_transitions"])
print(pl.DataFrame(drift.table("transitions")).select("current_time", "additions", "removals", "jaccard", "drift"))
0.5 0.6 1
shape: (2, 5)
┌──────────────┬───────────┬──────────┬─────────┬───────┐
│ current_time ┆ additions ┆ removals ┆ jaccard ┆ drift │
│ ---          ┆ ---       ┆ ---      ┆ ---     ┆ ---   │
│ str          ┆ i64       ┆ i64      ┆ f64     ┆ f64   │
╞══════════════╪═══════════╪══════════╪═════════╪═══════╡
│ 2024-02-29   ┆ 1         ┆ 1        ┆ 0.6     ┆ 0.4   │
│ 2024-03-29   ┆ 1         ┆ 2        ┆ 0.4     ┆ 0.6   │
└──────────────┴───────────┴──────────┴─────────┴───────┘

Every transition at or above warning_threshold adds a BIAS_UNIVERSE_DRIFT_HIGH warning. Heavy turnover is not wrong on its own, but a result that relies on a stable universe, or a signal whose apparent persistence is really universe churn, should be read with it in mind. Pass universe= to measure several universes (sectors, indexes) in one call, each against its own previous snapshot. Transitions are computed between consecutive snapshots that exist in the table, so a missing snapshot makes one transition span a longer interval; it is not reported as a gap.

A universe with fewer than two snapshots has no transition, so drift is undefined rather than zero. mean_drift and maximum_drift are None (JSON null) when no universe has a transition, and the result adds BIAS_UNIVERSE_DRIFT_UNDEFINED with state UNKNOWN. With universe=, the finding counts the universes that lack two snapshots (universes_without_transitions), and the means and maxima cover the transitions that exist. A declared "confirmed_safe" source gets no PASS in that case.

single = lc.bias.universe_drift(snapshots.filter(pl.col("snapshot_time") == date(2024, 1, 31)))
print(single.metrics["mean_drift"], single.metrics["maximum_drift"], single.metrics["transitions"])
print([(f.code, f.state.value) for f in single.findings])
None None 0
[('BIAS_UNIVERSE_DRIFT_UNDEFINED', 'UNKNOWN'), ('BIAS_SURVIVORSHIP_UNKNOWN', 'UNKNOWN')]

Drift measures change in composition. It says nothing about whether the snapshots were taken in real time or rebuilt later. That is what source_status records, and like the other functions, an undeclared source is UNKNOWN.

What the evidence does not prove

Everything above checks the timestamps you supplied. None of it checks that the timestamps are true.

  • asof_join proves that no match has an availability time after its decision time. It does not prove that the vendor’s availability timestamps are accurate, and a table whose available_time was backfilled with the effective date passes every check. The result carries that warning.
  • revision_mode, source_mode, source_status and includes_delisted are declarations. Lacuna records them and acts on them but cannot verify them. A declaration of "point_in_time" or "confirmed_safe" is only as good as your knowledge of the source.
  • Structural checks on revisions and membership cannot detect versions or delisted companies that the vendor never supplied.

When you cannot establish a property, leave the declaration at its default. You get an UNKNOWN finding, which is the true state of your knowledge, and the audit shows it as unanswered instead of passed.

Parameters

asof_join

ParameterMeaning
leftThe decisions: one row per decision, with a decision time and the identity. Polars, pandas, Arrow or anything to_polars accepts.
rightThe published records, with an availability time and the identity.
left_timeThe decision-time column in left. Default "decision_time".
right_timeThe availability-time column in right. Default "available_time".
byOne identity column or a list of them, present in both tables with the same dtype.
effective_timeOptional right-side column for the period the fact describes. Validated, carried through and recorded; it never affects which row matches.
revisionOptional right-side column ordering versions of one fact. Required if any key shares an availability time; the highest value wins the tie. Must be an integer, finite float, Date, Datetime, Duration or Enum; string and categorical columns raise DataContractError.
revision_modeYour declaration about the source’s revision history. Default "unknown".
toleranceMaximum age of a usable record. For Date, Datetime and Duration time: a non-negative timedelta or a fixed-length lowercase duration string such as "30d". For integer time: a non-negative whole number in the column’s units. Anything else raises MethodContractError. None accepts any age.
allow_exact_matchesWhether a record available at exactly the decision time is usable. Default True.
unmatched"keep", "drop" or "raise" for left rows with no usable record.
suffixAppended to right-side column names that collide with left-side names.

revision_diagnostics

ParameterMeaning
dataA table of versioned facts.
entityThe identity column or columns. Default "instrument".
effective_timeThe period the fact describes. Together with entity it identifies a fact.
available_timeWhen each version became known.
revisionThe version column, with the same rule as asof_join: an integer, finite float, Date, Datetime, Duration or Enum. String and categorical columns raise DataContractError, because they sort lexicographically. None identifies versions by availability time.
valueOptional numeric or other column; when given, the facts table reports how many distinct values each fact took.
source_modeYour declaration about revision coverage. "point_in_time" is the only value that can pass.

validate_dataset and DatasetSpec

ParameterMeaning
dataThe table to check.
specA DatasetSpec. Passing anything else raises a TypeError.
ParameterMeaning
nameA label for the contract, recorded in the result.
requiredColumns that must exist. At least one.
keysColumns whose combination must be unique.
non_nullColumns that must contain no nulls.
numericColumns that must be numeric and finite.
temporalColumns that must be ordered time types.
temporal_orderPairs (earlier, later) that must satisfy earlier <= later.

future_data_check

ParameterMeaning
dataA table carrying a decision time and an availability time.
decision_timeThe decision-time column.
available_timeThe availability-time column. It must have the same dtype as decision_time; nulls are reported, not failed.
row_idOptional column included in the example rows to identify them.
instrumentOptional identity column included in the example rows. None omits it.
materialityOptional numeric column used to weight the leak by absolute size. Must be finite.
max_examplesThe most offending rows to list in the future_rows table.

survivorship_diagnostics

ParameterMeaning
dataA membership table with intervals and availability.
identityThe columns that identify one membership. Default ("index", "instrument").
valid_fromStart of the membership interval, inclusive.
valid_toEnd of the interval, exclusive; null means open-ended.
available_timeWhen the membership row became known.
delistedOptional Boolean column marking delisted rows, counted in delisted_rows. Required for "confirmed_safe".
source_statusYour declaration: "confirmed_safe", "confirmed_biased" or "unknown".
includes_delistedYour declaration that the source includes delisted instruments. Must be True for "confirmed_safe".

membership_at

ParameterMeaning
dataA membership table, as for survivorship_diagnostics.
as_ofThe instant to select, representable as the dtype of valid_from.
identityThe membership identity columns.
valid_fromInterval start, inclusive.
valid_toInterval end, exclusive; null means open-ended.
available_timeWhen the row became known; rows not yet available at as_of are excluded.
source_statusYour declaration about the source, as above. Unlike survivorship_diagnostics, "confirmed_safe" needs no delisted column here.

universe_drift

ParameterMeaning
dataSnapshot rows: one per instrument per snapshot.
snapshot_timeThe snapshot date column.
instrumentThe instrument identity column.
universeOptional column naming the universe each row belongs to; drift is then computed within each.
source_statusYour declaration about the source.
warning_thresholdDrift (between 0 and 1) at or above which a transition counts as high. Default 0.5.

The full signatures are in the API reference.