Time and data
The panel layout, the times, the intervals and the missing-data rules that every Lacuna method relies on, and what Lacuna does when an input breaks them.
Most look-ahead bugs are not in the statistics. They are in a join that picked up a restated value, a horizon that counted calendar days across a holiday, a sector label that did not exist yet, or a duplicate row that quietly won a tie. A result built on any of these looks fine and is wrong.
Lacuna’s answer is a set of shared rules, plus policies specific to each method that you can see as parameters. The rules are stated up front, checked where they can be checked, and recorded in the result where they cannot. This page lists them. When an input breaks a rule, Lacuna raises a DataContractError rather than guessing; see Errors. When the input is valid but the evidence is weak, you get a finding instead; see Results.
A first example
Six instruments over ten sessions, a signal known at each session’s open, and one-session forward returns that enter and exit at that session’s close. The timing is stated in the call so that each choice is visible.
from datetime import date, timedelta
from itertools import product
import lacuna as lc
import numpy as np
import polars as pl
rng = np.random.default_rng(7)
instruments = ["A", "B", "C", "D", "E", "F"]
days = [date(2025, 3, 3) + timedelta(days=n) for n in range(14)]
sessions = [d for d in days if d.weekday() < 5]
pairs = list(product(instruments, sessions))
prices = pl.DataFrame(
{
"time": [t for _, t in pairs],
"instrument": [i for i, _ in pairs],
"close": 100.0 * np.exp(np.cumsum(rng.normal(0.0, 0.01, (6, 10)), axis=1)).ravel(),
}
)
signal = pl.DataFrame(
{
"time": [t for _, t in pairs],
"instrument": [i for i, _ in pairs],
"signal": rng.normal(size=len(pairs)),
}
)
labels = lc.labels.forward_returns(
prices, horizon="1D", signal_time="open", entry="current_close"
)
print(labels.frame.columns)
ic = lc.signal.ic(signal, labels)
print(ic.metrics["n_periods"], ic.metrics["n_observations"], ic.metrics["excluded_rows"]) ['observation_time', 'label_start', 'entry_time', 'label_end', 'instrument', 'horizon', 'forward_return']
9 54 0 Ten sessions give nine labelled observation times, because the last session has no later exit. Six instruments at each of the nine give 54 aligned observations. Nothing was dropped for missing values.
Long-form panels
Almost every table Lacuna reads is long-form: one row per instrument per time, never a wide matrix with one column per ticker. A panel is identified by its key. The exceptions are lc.signal.ic, which also accepts two one-dimensional NumPy arrays and treats them as a single cross-section, and the series methods in lc.validation, which take a plain sequence or array of values.
| Table | Key | Default column names |
|---|---|---|
| Prices | time, instrument | time, instrument, close (and open, or a delisting-return column, if you use them) |
| Signal | time, instrument | time, instrument, signal |
| Labels | observation_time, instrument, horizon | observation_time, instrument, horizon, forward_return, plus label_start, entry_time, label_end |
Two columns carry identity, and Lacuna restricts their types so that a join cannot silently compare unlike things.
| Column | Accepted types |
|---|---|
| Time | Date, Datetime (any unit, with or without a time zone), Duration, an integer, or a float that holds only whole numbers (an observation index) |
| Instrument | string, categorical, enum, an integer, or a float that holds only whole numbers |
The table describes the panel validators used by labels, signals and most other methods. The cross-validation splitters are narrower: they accept integer, Date and Datetime observation times only. A string time column, or a fractional float, is rejected before any computation:
lc.labels.forward_returns(prices.with_columns(pl.col("time").cast(pl.String)), horizon="1D") DataContractError: prices time column 'time' must be Date, Datetime, Duration, or a whole-number observation index; got String Both key columns must be free of nulls. A null key has no defined meaning, so Lacuna counts the nulls per column and raises.
Where two tables are joined, their key columns must have the same dtype. Lacuna does not cast one to match the other, because a silent cast between Date and Datetime, or between time units, is a way to misalign periods. Labels built from Datetime prices will not join to a Date signal:
lc.signal.ic(signal, lc.labels.forward_returns(prices.with_columns(pl.col("time").cast(pl.Datetime("ns"))), horizon="1D")) DataContractError: aligned semantic keys must use matching dtypes: time=Date vs observation_time=Datetime(time_unit='ns', time_zone=None) Column names
Defaults are only defaults. Every function that reads a table takes the names of its columns as parameters, so you pass your names instead of renaming your data. For lc.signal.ic:
| Parameter | Meaning |
|---|---|
signal_time | The signal table’s time column. Default time. |
label_time | The labels’ observation-time column. Default observation_time, which is what forward_returns writes. |
instrument | The identifier column of the signal table. Labels from forward_returns always name theirs instrument, and the signal functions read that name when you pass the LabelResult. A bare label table is read with this name when it has that column and with instrument otherwise, so labels.frame works too. |
signal_value | The signal column. Default signal. |
label_value | The label column. Default forward_return. |
by | Which columns define a cross-section. Default observation_time: one correlation per time. Add a group column to compute one per time and group. |
min_observations | The smallest cross-section that gets a correlation. Smaller ones are left out and reported; see Missing values. |
group_available_time | When each row’s group attribute became known; see Group availability. |
null_policy | What to do with null or NaN values; see Missing values. |
lc.labels.forward_returns takes time, instrument and price for the price table. Whatever names you use there, its output always uses the fixed names in the table above. entry="next_open" reads a column literally named open, and that name is not configurable. Entry and exit prices must be strictly positive and finite, or forward_returns raises. Tables that call the time column date, the price px and the signal alpha work like this:
renamed_prices = prices.rename({"time": "date", "close": "px"})
renamed_signal = signal.rename({"time": "date", "signal": "alpha"})
renamed_labels = lc.labels.forward_returns(renamed_prices, horizon="1D", time="date", price="px")
renamed = lc.signal.ic(renamed_signal, renamed_labels, signal_time="date", signal_value="alpha")
print(renamed.metrics["mean_ic"] == ic.metrics["mean_ic"]) True forward_returns always writes the identifier to a column called instrument, whatever the source column was called, and bucketize does the same. The functions that read labels or buckets (ic, quantiles, bucket_returns, decay, portfolio_projection) look for that name on the label side, whether you pass the LabelResult or its frame, so an identifier column called ticker needs no renaming. Pass instrument="ticker" to the call that reads your own table, and likewise to SignalStudy(instrument="ticker"):
ticker_prices = prices.rename({"instrument": "ticker"})
ticker_signal = signal.rename({"instrument": "ticker"})
ticker_labels = lc.labels.forward_returns(
ticker_prices, horizon="1D", instrument="ticker", signal_time="open", entry="current_close"
)
ticker_ic = lc.signal.ic(ticker_signal, ticker_labels, instrument="ticker")
print(ticker_labels.frame.columns[4], ticker_ic.metrics["mean_ic"] == ic.metrics["mean_ic"]) instrument True A ticker is still not a durable identity; see Instruments.
The times Lacuna distinguishes
A research record has several timestamps that people routinely treat as one. Lacuna keeps them apart because the gap between them is where look-ahead lives.
| Time | What it is | Where Lacuna uses it |
|---|---|---|
| Observation time | When the measurement was recorded, such as a bar’s close. The time of a price or signal row. | time, and observation_time in labels |
| Availability time | The earliest moment the record could have been known to you. | available_time, group_available_time, market_available_time |
| Effective time | The period a fact applies to, such as a fiscal quarter end. It can precede publication by a long time. | effective_time in lc.bias.asof_join and lc.bias.revision_diagnostics |
| Revision | Which version of a fact a row holds. A restatement shares its effective time with the original but has a later availability time. | revision in lc.bias.asof_join |
| Decision time | When a signal or portfolio decision is formed. Everything it uses must already be available. | decision_time in lc.bias.asof_join and lc.bias.future_data_check |
| Entry time | When the position is entered. | entry_time in labels |
| Label end | The observation at which the return is measured. | label_end in labels |
The rule that ties them together: a record may be used at a decision only if available_time <= decision_time. Equality is allowed: lc.bias.asof_join accepts exact matches by default (allow_exact_matches=True), and lc.bias.future_data_check counts rows where the two times are equal separately and does not treat them as future data. An effective date is not an availability time. A fiscal quarter that ended on 31 March does not become usable on 31 March.
lc.bias.asof_join applies the rule when it attaches slow-moving data to decisions. It matches on availability time, not on effective time:
decisions = pl.DataFrame(
{"decision_time": [date(2025, 3, 31), date(2025, 4, 30)], "instrument": ["A", "A"]}
)
fundamentals = pl.DataFrame(
{
"instrument": ["A", "A"],
"effective_time": [date(2025, 3, 31), date(2025, 6, 30)],
"available_time": [date(2025, 4, 15), date(2025, 8, 14)],
"eps": [1.0, 2.0],
}
)
joined = lc.bias.asof_join(
decisions, fundamentals, effective_time="effective_time", revision_mode="point_in_time"
)
print(joined.frame.select("decision_time", "effective_time", "available_time", "eps"))
print(joined.evidence.metrics["unmatched_rows"]) shape: (2, 4)
┌───────────────┬────────────────┬────────────────┬──────┐
│ decision_time ┆ effective_time ┆ available_time ┆ eps │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ date ┆ date ┆ f64 │
╞═══════════════╪════════════════╪════════════════╪══════╡
│ 2025-03-31 ┆ null ┆ null ┆ null │
│ 2025-04-30 ┆ 2025-03-31 ┆ 2025-04-15 ┆ 1.0 │
└───────────────┴────────────────┴────────────────┴──────┘
1 The decision on 31 March gets nothing: the March fundamentals describe that date but were published on 15 April, so on 31 March they were still in the future. The decision on 30 April gets the March figures and not the June ones. effective_time is carried through to the output and validated as a time column; it plays no part in the match. lc.bias.future_data_check runs the same comparison over a table you built yourself and reports how many rows used data that was not yet available. Point-in-time data covers revisions, membership and survivorship.
Lacuna proves ordering between the timestamps you supply. It cannot prove the timestamps are accurate. The join’s own result says so in its warnings.
Half-open intervals
Every interval in Lacuna is half-open: [start, end) includes its start and excludes its end. Two adjacent periods, [a, b) and [b, c), share no point, so there is never a question of which one owns the boundary. This applies to label intervals, to the folds of lc.cv.WalkForward, and to purging.
A label covers [label_start, label_end): from the observation the signal belongs to up to, but not including, the exit observation. Purged cross-validation removes a training row when its label interval overlaps a test row’s, and half-open intervals decide the overlap exactly. Here each label spans two observations, and the first three rows are the test set:
frame = pl.DataFrame({"observation_time": list(range(6))}).with_columns(
label_start=pl.col("observation_time"), label_end=pl.col("observation_time") + 2
)
split = lc.cv.PurgedKFold(n_splits=2).split(frame)
fold = split.folds[0]
print("test", fold.test_indices, "purged", fold.purged_indices, "train", fold.train_indices) test (0, 1, 2) purged (3,) train (4, 5) The test labels cover [0, 2), [1, 3) and [2, 4). The row at time 3 has label [3, 5), which overlaps [2, 4), so it is purged. The row at time 4 has label [4, 6). It starts exactly where [2, 4) ends, shares nothing with it, and stays in training. Fold indices are positions in the table you passed, so they stay valid whatever order the rows are in. Cross-validation covers embargoes and the other splitters.
When you supply your own labels, the interval columns are optional for lc.signal.ic, quantiles and decay. Leaving out both label_start and label_end is fine; supplying only one raises. If both are present they must be nonnull, have the same dtype as the observation time, and satisfy label_start < label_end, and an entry_time, if present, must lie within [label_start, label_end]. Purged cross-validation cannot work without them: lc.cv.PurgedKFold and CombinatorialPurgedKFold require both columns, and need them to share a dtype with each other. The audit rule LABEL_INTERVALS_PRESENT also looks for them.
Horizons count observations
A horizon such as "5D" or 5 is a count of observations per instrument, not of calendar days. Lacuna never infers a trading calendar from your dates. The label for a row ends at that instrument’s fifth later observation, wherever the dates fall. So an instrument with a gap in its history gets a longer calendar span, not a shorter horizon:
gap = pl.DataFrame(
{
"time": [date(2025, 3, d) for d in (3, 4, 5, 6, 3, 4, 6)],
"instrument": ["A"] * 4 + ["B"] * 3,
"close": [10.0, 10.5, 11.0, 11.5, 20.0, 20.5, 21.0],
}
)
gap_labels = lc.labels.forward_returns(gap, horizon="1D")
print(gap_labels.frame.filter(pl.col("instrument") == "B").select("observation_time", "label_end")) shape: (2, 2)
┌──────────────────┬────────────┐
│ observation_time ┆ label_end │
│ --- ┆ --- │
│ date ┆ date │
╞══════════════════╪════════════╡
│ 2025-03-03 ┆ 2025-03-04 │
│ 2025-03-04 ┆ 2025-03-06 │
└──────────────────┴────────────┘ Instrument B has no observation on 5 March. Its one-observation label from 4 March therefore ends on 6 March. If a missing row means “the market was closed”, that is what you want. If it means “the data vendor lost a row”, fill the row or accept that the label is longer than it looks. A row that is present with a null price is different: it still counts as an observation when horizons are counted, and the labels that depend on its price are dropped as censored. Forward-return labels covers entry and exit conventions.
Instruments
instrument is the primary identity of every row. Lacuna treats its values as opaque keys: it compares them for equality and never maps, normalizes or deduplicates them. That is the right behaviour only if the values are stable identifiers.
A ticker is not one. Tickers are reused after delistings, change after mergers, and differ between venues. If you key a panel on tickers, two companies that held the same symbol at different times become one instrument, and the join, the cross-section and the survivorship accounting all inherit the merge. Lacuna cannot detect this, because the values look perfectly valid. Key your panels on a durable identifier from your data vendor, and keep tickers as display columns. Passing an identifier column of the wrong type (a boolean, say) is rejected; passing a ticker column is a choice only you can validate. Identifier values also matter in one place beyond identity. When signal values tie, lc.signal.bucketize and quantiles break the tie by sorting on the instrument value, and turnover assigns its membership buckets the same way, so relabelling the instruments can change which of them land in which bucket.
Ordering and duplicates
Rows have no inherent order in Lacuna’s panel methods, and duplicate keys are rejected rather than resolved by position. What a method does with order depends on the input.
| Input | Behaviour |
|---|---|
| Panels with a time and an instrument (prices, signals, labels) | Order is irrelevant. Lacuna sorts internally where it needs order, or computes per group. Shuffling the rows gives the same result. |
lc.bias.asof_join | Sorts both sides internally and returns rows in the left table’s original order. |
| Cross-validation splitters | Order is irrelevant; fold indices are positions in your table. |
| Plain series and strategy matrices | The values are taken in the order you give them, and there is no time column to sort by, so you must supply them already in time order. This matters for the block methods of lc.validation.bootstrap, permutation_test with scheme="block", joint_stationary_bootstrap, reality_check, superior_predictive_ability and probability_of_backtest_overfitting. sharpe_inference uses only the sample moments, so it does not depend on order beyond floating-point rounding. |
The last row matters because block resampling and blocked partitions are only valid when neighbouring values are neighbours in time. Lacuna cannot check this. Here a persistent series is bootstrapped twice with the same seed: once in time order and once shuffled. The mean is the same, but the standard error of the mean is not, because shuffling destroys the dependence the blocks were meant to preserve.
x = np.empty(400)
shocks = rng.normal(size=400)
x[0] = shocks[0]
for i in range(1, 400):
x[i] = 0.8 * x[i - 1] + shocks[i]
ordered = lc.validation.bootstrap(x, seed=1, resamples=500, block_length=20)
shuffled = lc.validation.bootstrap(rng.permutation(x), seed=1, resamples=500, block_length=20)
print(round(ordered.metrics["observed"], 6) == round(shuffled.metrics["observed"], 6))
print(round(ordered.metrics["standard_error"], 3), round(shuffled.metrics["standard_error"], 3)) True
0.213 0.078 Duplicate keys are never resolved for you. Every function that needs a unique key checks it and raises, counting the rows involved. A single repeated pair of rows reports two, because both members of a duplicated key are counted:
lc.signal.ic(pl.concat([signal, signal.head(1)]), labels) DataContractError: signal contains 2 duplicate rows for logical key (time, instrument) Which key is checked depends on the table:
| Table | Unique key | If it is not |
|---|---|---|
| Signal, prices, exposures | time, instrument | DataContractError |
| Labels | observation_time, instrument, plus horizon if present | DataContractError |
| Events | event_id | DataContractError |
| Regime source | time | DataContractError |
Right side of asof_join | the by columns and the availability time | DataContractError, unless you pass a revision column to order the ties; the combination with the revision must then be unique, and the revision must have an intended order (integer, finite float, Date, Datetime, Duration or ordered Enum). String and categorical revisions raise DataContractError |
Resolve duplicates yourself before calling, by choosing which version you mean. Dedup is a research decision, and “keep the last row” is a different decision from “keep the latest published”.
Missing values
Missing data is handled at several levels, and the details differ by method.
| Level | Rule |
|---|---|
| Keys: the time and instrument columns | A null always raises DataContractError, with a count per column. |
| Availability times | A null raises in the signal and regime methods. lc.bias.future_data_check counts it as missing availability instead, and the cost models treat it as unavailable. |
| Infinity in a value column | Raises DataContractError whatever the missing-value policy, since an infinite value is not a missing one. lc.signal.ic checks the declared signal and label inputs as a whole, so an infinite value raises even on a row that finds no join partner, such as a date with no label. lc.costs.liquidity_diagnostics and BorrowCostModel classify non-finite inputs as unknown instead of raising. |
| Null or NaN in a value column | In methods with a policy parameter, "drop" removes the row and counts it in excluded_rows, and "raise" raises. Nulls and NaN are treated alike. Methods without one behave as listed below. |
Methods without a policy parameter handle missing values on their own terms:
| Method | Null or NaN values |
|---|---|
lc.regime.quantile_regimes | The row is labelled unknown, and unknown_rows counts it. |
lc.events.event_windows | A NaN or non-positive price raises. A null price is recorded as missing coverage in the window’s evidence. |
lc.costs.BorrowCostModel, lc.costs.liquidity_diagnostics | The trade is marked unknown, or raises under BorrowCostModel(missing="raise"). |
lc.signal.neutralize | A null in a categorical exposure raises. |
lc.labels.forward_returns | Uses missing, and reports source_missing_rows and censored_rows as metrics. |
The policy parameter and its default differ by method, so check the one you are calling.
| Methods | Parameter | Default |
|---|---|---|
lc.signal.ic, quantiles, turnover, bucketize, bucket_returns, neutralize; lc.validation.bootstrap | null_policy | "drop" |
lc.validation.sharpe_inference, permutation_test, multiple_testing | null_policy | "raise" |
lc.labels.forward_returns, and missing on SignalStudy | missing | "drop" |
SignalStudy(missing=...) controls label construction only. The study’s own methods have no null_policy: a null or NaN signal value is always dropped.
Dropping is visible. With null_policy="drop", the result reports how many rows were excluded and how many matched before the policy was applied:
with_nan = signal.with_columns(
pl.when(pl.col("instrument") == "A").then(float("nan")).otherwise(pl.col("signal")).alias("signal")
)
dropped = lc.signal.ic(with_nan, labels)
print(dropped.metrics["excluded_rows"], dropped.metrics["n_observations"]) 9 45 lc.signal.ic(with_nan, labels, null_policy="raise") DataContractError: numeric input contains 9 rows with null or NaN values For plain series, dropping a null closes the gap: the neighbours on either side become adjacent, which block resampling then treats as consecutive. Fill or exclude explicitly if the position in time matters.
In forward_returns, a label needs an exit observation, so the last rows of every instrument are always censored at the end of the sample. Those rows are dropped under either policy, and censored_rows and the coverage_by_horizon table count them. missing="raise" rejects the other kinds of gap: a null or NaN entry or exit price in the source (except a null exit price on a row that carries a delisting return), and a label whose entry and exit observations both exist but give no defined return. With the default "drop" those rows are dropped and counted as well, so read source_missing_rows and censored_rows to see what was lost.
Groups that are too small
Some methods work per group and a group can be too small to estimate anything. Whether that raises or is reported depends on the method.
| Method | What happens |
|---|---|
lc.signal.ic | A group with fewer than min_observations rows gets no correlation and produces a WARN finding (IC_UNDERSIZED_GROUPS). A group whose signal or label is constant has an undefined correlation, reported as null with IC_UNDEFINED_GROUPS. If no group qualifies, it raises. |
lc.signal.bucketize | A group too small for the requested buckets raises, or is dropped with small_group_policy="drop". |
lc.signal.neutralize | A group with too few residual degrees of freedom raises, or is dropped with insufficient_policy="drop". |
lc.signal.portfolio_projection | A cohort with only one side raises, or is dropped with incomplete_group_policy="drop". |
lc.events.event_windows | Events whose windows overlap on the same instrument raise, or are kept and tagged with overlap_policy="keep". |
Group availability
Cross-sectional analysis is often done within groups: sectors, index members, a volatility regime. The group labels are data too, and they have the same timing problem as any other. A sector classification that was assigned or restated in 2024 and then applied to 2015 gives every 2015 row a label nobody could have used.
Methods that group take the time each row’s attribute became known and check it. In lc.signal.ic and quantiles the parameter is group_available_time; in lc.signal.bucketize it is available_time, and in lc.signal.neutralize it timestamps the exposures. Add a sector column to the signal and compute the IC within sectors:
sector = {"A": "tech", "B": "tech", "C": "tech", "D": "energy", "E": "energy", "F": "energy"}
grouped = signal.with_columns(
pl.col("instrument").replace_strict(sector).alias("sector"),
pl.col("time").alias("sector_known"),
)
keys = ["observation_time", "sector"]
unstamped = lc.signal.ic(grouped, labels, by=keys)
print([f.code for f in unstamped.findings if f.code.startswith("GROUP")])
stamped = lc.signal.ic(grouped, labels, by=keys, group_available_time="sector_known")
print([(f.code, f.state.value) for f in stamped.findings if f.code.startswith("GROUP")]) ['GROUP_AVAILABILITY_UNKNOWN']
[('GROUP_AVAILABILITY_VERIFIED', 'PASS')] Without a timestamp, the grouped analysis has no evidence that the classification was available, so the finding is UNKNOWN, with high severity. It is not a pass and it is not an error: the numbers are computed, and the doubt is recorded. With a timestamp that is no later than each row’s observation time, the finding becomes PASS. A timestamp that is later is not a weak result but an invalid one:
late = grouped.with_columns(pl.col("sector_known").dt.offset_by("1d"))
lc.signal.ic(late, labels, by=keys, group_available_time="sector_known") DataContractError: group attributes contain 54 rows available after observation time The availability column must have the same dtype as the time column. The comparison is made per row: the attribute’s timestamp against the observation time of the row it labels. Lacuna checks that you did not stamp a label as available after the row that uses it. It cannot check that the stamp is true, that is, that this was in fact the sector assigned on that date. That is your assertion; Lacuna records it and holds you to it.
Other methods that take an availability time handle a late or missing one differently, so check the one you use.
| Methods | Parameter | A timestamp later than the row it serves | No timestamp |
|---|---|---|---|
lc.signal.ic | group_available_time | DataContractError, checked only when by has a grouping column | UNKNOWN finding GROUP_AVAILABILITY_UNKNOWN, when grouping |
lc.signal.quantiles | group_available_time | DataContractError, whether or not by groups | UNKNOWN finding GROUP_AVAILABILITY_UNKNOWN, when grouping |
lc.signal.bucketize | available_time | DataContractError | UNKNOWN finding GROUP_AVAILABILITY_UNKNOWN, when grouping |
lc.signal.neutralize | available_time, on the exposure data | DataContractError | UNKNOWN finding GROUP_AVAILABILITY_UNKNOWN, always, because exposures are attributes too |
lc.regime.regime_analysis | available_time | FAIL finding REGIME_AVAILABILITY_LEAKAGE | UNKNOWN finding REGIME_AVAILABILITY_UNKNOWN (unless the classification is declared retrospective) |
lc.regime.quantile_regimes | available_time | FAIL finding REGIME_SOURCE_NOT_AVAILABLE, for the fixed, expanding and rolling methods | UNKNOWN finding REGIME_SOURCE_AVAILABILITY_UNKNOWN, for those methods. REGIME_THRESHOLDS_POINT_IN_TIME covers only the thresholds, never the source values |
lc.costs.SquareRootImpactModel, ParticipationImpactModel, VolatilitySlippageModel | market_available_time, volatility_available_time | DataContractError when the value was not available by execution_time | no check |
lc.costs.BorrowCostModel | borrow_available_time | the borrow rate counts as missing and follows the model’s missing policy | no check |
lc.costs.liquidity_diagnostics, capacity_curve | available_time | the trade’s liquidity counts as unknown, lowering coverage | no check. Both take a required classification_mode, and "point_in_time" requires available_time (MethodContractError) |
In lc.events.event_windows the availability time has another job: each event’s window is anchored at the first price observation at or after its available_time by default, so an announcement published after the event happened is not credited with price moves that came before anyone could see it. Pass anchor="event_time" to anchor at the event’s own time.
Copies and lazy inputs
Lacuna reads Polars frames directly. pandas frames, dictionaries, NumPy arrays, and Arrow-compatible tables are converted to Polars at the edge. A Polars LazyFrame is accepted, but every analytical method needs the whole table, so Lacuna collects it. It does this once per method call, deliberately, and records that it did. SignalStudy keeps a lazy frame as you gave it and collects it again in each method call; only the labels are cached.
Each result keeps a description of what happened to every input table under keys such as signal_input and label_input in its metadata.parameters:
def intake(source):
result = lc.signal.ic(source, labels)
info = result.metadata.parameters["signal_input"]
return info["source_type"], info["adapter_copy"], info["materialized"]
print(intake(signal))
print(intake(signal.lazy()))
print(intake(signal.to_dict(as_series=False))) ('polars.DataFrame', 'zero_copy', False)
('polars.LazyFrame', 'materializing', True)
('builtins.dict', 'one_copy', False) adapter_copy | Meaning |
|---|---|
zero_copy | An eager Polars frame was used as it is. |
potentially_zero_copy | NumPy arrays and Arrow-compatible tables, which Polars may share rather than copy. |
one_copy | pandas frames and dictionaries, which are copied once into Polars. |
materializing | A lazy frame was collected because the method needs an eager table. |
Lacuna does not modify the objects you pass in. The frame of a label, signal-transform, portfolio-projection or event-window result is a shallow clone, so replacing a column on it does not reach the result. pandas input needs pandas installed; the core install does not require it. The pandas index is dropped, so a time or instrument held in the index is lost: call reset_index() first. A pandas datetime64 column arrives as a Polars Datetime, not a Date, so both of your tables must come through pandas, or be cast to the same dtype, for their time columns to match.
What Lacuna cannot check
Several parts of the contract are statements you make and Lacuna records. It enforces consistency among them and reports their absence as UNKNOWN, but it has no way to confirm them against the world.
| Declaration | What Lacuna does with it |
|---|---|
price_adjustment | Records it. "unknown" produces an UNKNOWN finding. It cannot tell from prices whether they were adjusted. |
signal_time (signal_observed_at in SignalStudy) | Uses it only to reject trading at the close the signal was computed from, and only the value "close" triggers that check. It cannot know when your signal was really computed, and it does not validate the string: a typo such as "clsoe" is accepted silently. |
| Timestamps of availability, revision and membership | Checks their order. It cannot check their accuracy. |
| Time zones and calendars | Compares dtypes, including time zone. It does not convert between zones or build a calendar. Normalize to one zone and one session convention before calling. |
| Instrument identity | Treats it as an opaque key, as above. |
| Delisting returns | Uses the column you name. Without one, the label’s delisting handling is UNKNOWN. |
Each declaration shows up in the result’s metadata.parameters, so a reviewer can see what you claimed. The audit turns the missing ones into questions; see Audits and reports.
Next
Results
What the metrics, tables and findings in a result mean, and how to store one.
Data inputs
Input formats, vendor schemas and lazy frames in detail.
Point-in-time data
As-of joins, revisions, membership and survivorship.
Forward-return labels
Entry, exit and horizon conventions.
The generated signatures are in the API reference for signal, labels, bias and cv.