Results and findings
What an AnalysisResult holds, how findings express weak or missing evidence, how results serialize, and how seeds make them reproducible.
A number from a statistical method is only useful with its context: which method produced it, with which parameters, on what input, from which random stream, and whether anything about the data should make you doubt it. Lacuna returns that context with every result instead of leaving it in your notebook.
Every analytical method returns the same structure, AnalysisResult: metrics, tables, findings, warnings, and the provenance of the calculation. Methods that also produce a table of rows, such as labels or event windows, return a small typed container that holds an AnalysisResult beside the rows. Audit rules, reports, bundles and experiment records all consume this one structure, so the contract described here holds everywhere.
A first result
A moving-block bootstrap of the mean of simulated daily returns:
import lacuna as lc
import numpy as np
import polars as pl
rng = np.random.default_rng(42)
returns = rng.normal(0.05, 1.0, 250)
result = lc.validation.bootstrap(returns, statistic="mean", seed=11, resamples=500)
print(type(result).__name__)
print({k: round(result.metrics[k], 4) for k in ("observed", "standard_error", "confidence_lower", "confidence_upper")})
print(list(result.tables))
print(len(result.findings), len(result.warnings)) AnalysisResult
{'observed': 0.0013, 'standard_error': 0.058, 'confidence_lower': -0.1193, 'confidence_upper': 0.1066}
['distribution_summary']
0 2 The result separates what was computed from how and from what to doubt. The sections below take each part in turn.
What a result holds
| Attribute | Type | Holds |
|---|---|---|
metadata | ResultMetadata | The method name and version, the resolved parameters, the seed, an input fingerprint when the method computes one, and the creation time. |
metrics | read-only mapping | Named scalars: the numbers you usually want. |
tables | read-only mapping | Named tables of rows, for results that have more than one value per period, group or horizon. |
findings | tuple of Finding | Structured statements about this data: checks passed, failed, doubtful or not possible. |
warnings | tuple of strings | Caveats about the method itself, such as an assumption it makes. |
schema_version | string | The version of the serialized layout. Currently "1". |
Every value inside a result is JSON-compatible: strings, booleans, integers, finite floats, None, and nested mappings or tuples of these. Dates and datetimes are stored as ISO 8601 strings, but how depends on the path. A datetime passed directly to a constructor must be timezone-aware and is stored as UTC with a Z suffix; a naive one raises ValueError. Rows that a method puts in a table are serialized with isoformat(), so a timezone-aware value keeps its offset (for example -05:00), and a duration becomes the text of a timedelta. Some methods, such as the bias and regime ones, convert to UTC first, and the bias methods write durations as ISO 8601 text such as "P1D". Do not rely on one uniform timestamp format across tables. A result cannot hold a NaN or an infinity. A value that is undefined is stored as None, and a finding says why. Trying to build a result with a non-finite value fails:
empty = lc.ResultMetadata(method="custom.example") lc.AnalysisResult(metadata=empty, metrics={"x": float("nan")}) ValueError: result values must not contain NaN or infinity This is why you will see None in a metric or a table where you expected a number: the value was undefined on that input (a correlation of a constant signal, say), and the result records the reason in a finding or a warning.
Metrics and tables
metrics is a flat mapping of names to scalars. tables maps a name to a list of row dictionaries. result.table(name) returns one of them. Build a small panel and read the coverage table of its labels:
sessions = [f"2025-03-{d:02d}" for d in range(3, 9)]
instruments = ["A", "B", "C", "D", "E", "F"]
rows = [(s, i) for s in sessions for i in instruments]
prices = pl.DataFrame(
{
"time": [s for s, _ in rows],
"instrument": [i for _, i in rows],
"close": 100.0 * np.exp(np.cumsum(rng.normal(0.0, 0.01, (6, 6)), axis=0)).ravel(),
}
).with_columns(pl.col("time").str.to_date())
signal = prices.select("time", "instrument").with_columns(
signal=pl.Series(rng.normal(size=len(rows))),
sector=pl.col("instrument").replace_strict(
{"A": "tech", "B": "tech", "C": "tech", "D": "energy", "E": "energy", "F": "energy"}
),
)
labels = lc.labels.forward_returns(prices, horizon="1D")
print(labels.evidence.table("coverage_by_horizon")) [{'horizon': '1D', 'eligible_rows': 30, 'censored_rows': 6}] The rows are plain dictionaries, which any dataframe library reads directly: pl.DataFrame(result.table("ic_by_horizon")). The returned list is a copy. Changing it does not change the result. Inside the result, result.tables[name] is a tuple of read-only mappings, and table() converts it to plain lists and dictionaries. By convention each table is a list of row mappings, but a table can hold any JSON-compatible value. Asking for a table that does not exist raises a KeyError that lists the ones that do, and the exception is not a LacunaError, because it is the ordinary lookup failure of a mapping:
result.table("nope") KeyError: "unknown result table 'nope'; available tables: distribution_summary" Findings
A finding is one explicit statement about the evidence. Its fields:
| Field | Meaning |
|---|---|
code | A stable machine-readable identifier, such as IC_PERIOD_SUPPORT_LOW. Code that reacts to a finding should match on this. |
title | A short human-readable label. |
message | One sentence saying what was found. |
state | The outcome of the check; see below. |
severity | How much the finding matters; see below. |
category | A grouping label, such as temporal_integrity or bias.availability. |
evidence | A mapping of the figures behind the finding. |
State and severity answer different questions, and they are independent.
FindingState | Meaning |
|---|---|
PASS | The check ran and the evidence satisfies it. |
WARN | The check ran and the evidence is weak or borderline. |
FAIL | The check ran and the evidence violates it. |
UNKNOWN | The evidence needed to decide was not supplied or could not be established. This is never a pass. |
NOT_APPLICABLE | The check does not apply to this method or scope. |
Severity | Meaning |
|---|---|
INFO | Informational. The default. |
LOW, MEDIUM, HIGH | Increasing consequence if the finding is real. |
CRITICAL | The highest level. Lacuna uses it for the most serious findings, such as look-ahead data, a source confirmed to be survivorship-biased, and missing label intervals in an audit. |
State is what happened; severity is how much it would matter. A missing sector timestamp is UNKNOWN with HIGH severity. Too few periods is WARN with MEDIUM. A row that used data not yet available is FAIL with CRITICAL. Both enums are string enums, so finding.state == "WARN" and finding.severity == "high" compare as you would expect.
ic = lc.signal.ic(signal, labels, by=["observation_time", "sector"])
for f in ic.findings:
print(f"{f.state.value:<8} {f.severity.value:<7} {f.code}") UNKNOWN high GROUP_AVAILABILITY_UNKNOWN
WARN medium IC_PERIOD_SUPPORT_LOW Findings do not interrupt anything. Both numbers were computed, and the findings sit beside them. Whether a finding stops you is your decision, or the decision of an audit that turns findings into a score; see Audits and reports.
Findings and errors
The line between a finding and an error is the line between weak evidence and an invalid input.
| Situation | What you get |
|---|---|
| The input breaks a contract: duplicate keys, a null time, mismatched dtypes, an unknown parameter value | An exception. There is no meaningful result to describe. See Errors. |
| The input is valid but the evidence is thin, doubtful or incomplete: few periods, undeclared price adjustment, a group with no timestamp | A result with a WARN or UNKNOWN finding. |
| The input shows a violation that is itself the result you asked to measure | A result with a FAIL finding, such as the rows that used future data. |
Warnings
warnings are strings and are about the method, not the data. Most state an assumption or a limitation that applies every time you use the method, for instance that the IC’s t-statistic does not adjust for serial dependence. Some depend on your parameters: the bootstrap’s block-length warning appears only for the block methods, and sharpe_inference adds a note about treating trials as independent only when you omit independent_trials. Findings are about this input and carry a state you can act on.
Provenance
result.metadata is a ResultMetadata:
| Field | Meaning |
|---|---|
method | The method that produced the result, such as validation.bootstrap.moving. |
method_version | An integer that identifies the calculation and its assumptions. |
parameters | The configuration the method resolved: typically defaults filled in, policies chosen and how each input table was read. What is recorded varies by method. |
seed | The seed that made a random result, when one was used. |
input_fingerprint | A digest of the input, when the method computes one; None otherwise. |
created_at | When the result was made, as a timezone-aware UTC time. |
meta = result.metadata
print(meta.method, meta.method_version, meta.seed, meta.input_fingerprint)
print(sorted(meta.parameters)[:5]) validation.bootstrap.moving 1 11 None
['backend', 'batch_size', 'block_length', 'confidence_level', 'input'] parameters is where many of the defaults that applied are recorded, so it answers “what did this run assume?”. Coverage varies by method: some record every column and policy, others only those that changed the result. For example, ic records how each input frame was read but not which columns it selected. Most methods also record how each input was read (see copies and lazy inputs). Declared conventions, such as price_adjustment on labels, appear here too; these are statements you made and Lacuna cannot verify.
created_at makes two otherwise identical results unequal. Compare metrics, tables and findings when you want to know whether two runs agree.
Three versions
| Version | Where | What it identifies |
|---|---|---|
method_version | result.metadata.method_version | The mathematics: the estimator, its assumptions, how ties and missing data are handled. It changes when the meaning of the numbers changes, even if the layout does not. |
schema_version | result.schema_version | The serialized layout of the result: its fields and their types. from_json accepts only "1". |
| Package version | lc.__version__ | The installed release of Lacuna. |
A result does not record the package version. A reproducibility bundle does: its manifest names the producer and version. If you store results yourself and want to know which release made them, keep that alongside them. See Reproducibility bundles.
Immutability
A result cannot be changed after construction. The result and its metadata are frozen, the mappings are read-only views, and sequences are tuples. A result that has been handed to an audit, a report or a registry is the result that was computed.
result.metrics["observed"] = 1.0 TypeError: 'mappingproxy' object does not support item assignment result.metadata.seed = 0 FrozenInstanceError: cannot assign to field 'seed' JSON
to_json() writes the full result as JSON with sorted keys, and AnalysisResult.from_json reads it back. to_dict() returns the same content as a plain dictionary. The JSON never contains NaN or infinity, since results cannot hold them.
text = result.to_json()
restored = lc.AnalysisResult.from_json(text)
print(restored == result)
print(sorted(result.to_dict())) True
['findings', 'metadata', 'metrics', 'schema_version', 'tables', 'warnings'] The round trip is exact, including created_at. Reading is strict, and Lacuna does not evaluate anything in the document. from_json rejects non-finite constants, duplicate object keys, a missing or extra field, an unknown state or severity, and a schema version other than "1":
lc.AnalysisResult.from_json(text.replace('"schema_version": "1"', '"schema_version": "2"')) ValueError: unsupported result schema version '2' Parse errors are ordinary ValueError and TypeError exceptions, as with other constructors of value objects. from_json and from_dict exist only on AnalysisResult itself and raise TypeError on a subclass.
Seeds and determinism
A method that uses randomness takes a seed. Given the same seed, the same input, the same method version and the same environment, it produces the same numbers. The environment matters because results are reproducible, not bit-for-bit guaranteed across NumPy or platform versions, and the NumPy version is not recorded in a result. How the stream is built differs: bootstrap and permutation_test derive each replicate’s stream from the seed, the method version and the replicate’s own index, so the result does not depend on how replicates are batched or scheduled. event_response and fit_decay draw from one stream spawned from a root entropy, and continuous_perturbation from one generator seeded with seed.
first = lc.validation.bootstrap(returns, seed=11, resamples=500)
second = lc.validation.bootstrap(returns, seed=11, resamples=500)
same = first.metrics == second.metrics and first.tables == second.tables
print(same, first == second) True False The numbers are equal. The results are not, because created_at differs. That is why you compare metrics and tables.
When you do not pass a seed, the method draws one and records it, so even an unseeded run can be replayed:
unseeded = lc.validation.bootstrap(returns, resamples=500)
replay = lc.validation.bootstrap(returns, resamples=500, seed=unseeded.metadata.seed)
print(unseeded.metadata.seed is not None, unseeded.metrics == replay.metrics) True True How each method handles an omitted seed differs, and so does where the seed is recorded.
| Methods | If seed is omitted | Recorded in |
|---|---|---|
lc.validation.bootstrap, permutation_test, joint_stationary_bootstrap, reality_check, superior_predictive_ability | The seed set with lc.configure(seed=...) or lc.config(seed=...), otherwise fresh random entropy | metadata.seed |
lc.events.event_response, lc.signal.fit_decay | Fresh random entropy | metadata.seed when you pass one. Whenever the resampling runs, also metadata.parameters["root_entropy"], which equals the seed when you pass one. With no seed, metadata.seed stays None and the entropy is the only record. |
lc.robustness.continuous_perturbation | The default seed is 0, so it is deterministic unless you change it | metadata.seed and metadata.parameters |
SignalStudy.audit | Passes the value to its bootstrap, which then behaves as the first row. The bootstrap runs only when there are at least two non-overlapping IC values, so otherwise no seed is recorded | the metadata.seed of the audit’s bootstrap evidence |
Methods without a seed parameter do not draw random numbers. A global seed is convenient, but passing seed explicitly keeps the dependence visible in your code.
Typed containers
When a method produces a table of rows as well as evidence, it returns a small immutable container. The container holds the rows and an AnalysisResult in evidence. The evidence is where findings, parameters and coverage live; metadata is a shortcut to evidence.metadata.
| Container | Returned by | Holds | Also provides |
|---|---|---|---|
LabelResult | lc.labels.forward_returns, SignalStudy.labels() | frame: the label rows | metadata, to_json() |
SignalTransformResult | lc.signal.bucketize, neutralize | frame: the transformed signal | metadata, to_json() |
PortfolioProjectionResult | lc.signal.portfolio_projection | frame: the projected cohort | metadata, to_json() |
EventWindowResult | lc.events.event_windows | frame: the event paths | metadata, to_json() |
SplitResult | lc.cv.PurgedKFold.split, lc.cv.WalkForward.split | folds: a tuple of Fold | fold_table, to_json(); iterating yields (train, test) index arrays |
CombinatorialSplitResult | lc.cv.CombinatorialPurgedKFold.split | folds and paths | fold_table, path_table, to_json(); iterable like SplitResult |
PointInTimeJoinResult, MembershipResult | lc.bias.asof_join, membership_at | frame | metadata |
AdaptedFrame | lc.adapters.adapt_vendor, adapt_factor_panel, adapt_backtest, from_duckdb | frame, which may stay lazy | columns, lazy |
ActivatedPlugin | lc.plugins.activate_plugin | descriptor, implementation and the activation record | none beyond its fields |
The first four return frame as a shallow clone each time, so the stored rows cannot be replaced from outside. to_json() serializes the evidence only. A large frame stays columnar and is not written into the JSON. The bias containers keep their frame as a plain attribute and have no to_json(); serialize evidence instead.
print(type(labels).__name__, labels.frame.shape)
print(labels.metadata.method, labels.evidence.metrics["n_labels"])
print([f.code for f in labels.evidence.findings])
print(lc.AnalysisResult.from_json(labels.to_json()) == labels.evidence) LabelResult (30, 7)
labels.forward_returns 30
['PRICE_ADJUSTMENT_UNKNOWN', 'DELISTING_RETURNS_UNKNOWN']
True An AuditReport wraps an AnalysisResult the same way: the audit’s own result is report.result, and the evidence it was computed from sits in report.evidence, keyed by name. SignalStudy.ic(), quantiles(), turnover() and decay() return plain AnalysisResult values. A CostEstimate is not a container: it holds per-trade cost components, and to_result() converts it to an AnalysisResult.
Building your own
You rarely construct a result by hand, but you will when you supply your own evidence to an audit, or write a plugin. The three constructors validate what you give them: a method name that is empty, a method_version below 1, a negative seed, a naive datetime, an empty finding code, and any value that is not JSON-compatible all raise.
| Field | Meaning |
|---|---|
code | Stable identifier, uppercase by convention. Required, nonempty. |
title | Short label. Required. |
message | One sentence. Required. |
state | A FindingState. Required. |
severity | A Severity. Defaults to INFO. |
category | Grouping label. Defaults to general. |
evidence | Mapping of the figures behind the finding. |
| Field | Meaning |
|---|---|
metadata | A ResultMetadata. Required. |
metrics | Mapping of scalars. |
findings | A sequence of Finding. |
tables | Mapping of table names to lists of row mappings. |
warnings | Nonempty strings. |
schema_version | Leave as "1". |
mine = lc.AnalysisResult(
metadata=lc.ResultMetadata(method="custom.spread", parameters={"window": 20}),
metrics={"spread": 0.012},
findings=(
lc.Finding(
code="SPREAD_QUOTES_STALE",
title="Spread quotes are stale",
message="The newest quote is four days old.",
state=lc.FindingState.WARN,
severity=lc.Severity.MEDIUM,
evidence={"age_days": 4},
),
),
)
print(mine.findings[0].state, mine.metadata.method_version) WARN 1 Next
Time and data
The input contracts behind the errors and findings you see here.
Audits and reports
How findings become a score, and how to answer the UNKNOWN ones.
Experiments
Record every run, including the ones you discard.
Errors
Which exception means what.
The generated signatures for AnalysisResult, ResultMetadata, Finding, FindingState and Severity are on the lacuna API page.