Skip to Content

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

AttributeTypeHolds
metadataResultMetadataThe method name and version, the resolved parameters, the seed, an input fingerprint when the method computes one, and the creation time.
metricsread-only mappingNamed scalars: the numbers you usually want.
tablesread-only mappingNamed tables of rows, for results that have more than one value per period, group or horizon.
findingstuple of FindingStructured statements about this data: checks passed, failed, doubtful or not possible.
warningstuple of stringsCaveats about the method itself, such as an assumption it makes.
schema_versionstringThe 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:

FieldMeaning
codeA stable machine-readable identifier, such as IC_PERIOD_SUPPORT_LOW. Code that reacts to a finding should match on this.
titleA short human-readable label.
messageOne sentence saying what was found.
stateThe outcome of the check; see below.
severityHow much the finding matters; see below.
categoryA grouping label, such as temporal_integrity or bias.availability.
evidenceA mapping of the figures behind the finding.

State and severity answer different questions, and they are independent.

FindingStateMeaning
PASSThe check ran and the evidence satisfies it.
WARNThe check ran and the evidence is weak or borderline.
FAILThe check ran and the evidence violates it.
UNKNOWNThe evidence needed to decide was not supplied or could not be established. This is never a pass.
NOT_APPLICABLEThe check does not apply to this method or scope.
SeverityMeaning
INFOInformational. The default.
LOW, MEDIUM, HIGHIncreasing consequence if the finding is real.
CRITICALThe 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.

SituationWhat you get
The input breaks a contract: duplicate keys, a null time, mismatched dtypes, an unknown parameter valueAn 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 timestampA result with a WARN or UNKNOWN finding.
The input shows a violation that is itself the result you asked to measureA 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:

FieldMeaning
methodThe method that produced the result, such as validation.bootstrap.moving.
method_versionAn integer that identifies the calculation and its assumptions.
parametersThe configuration the method resolved: typically defaults filled in, policies chosen and how each input table was read. What is recorded varies by method.
seedThe seed that made a random result, when one was used.
input_fingerprintA digest of the input, when the method computes one; None otherwise.
created_atWhen 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

VersionWhereWhat it identifies
method_versionresult.metadata.method_versionThe 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_versionresult.schema_versionThe serialized layout of the result: its fields and their types. from_json accepts only "1".
Package versionlc.__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.

MethodsIf seed is omittedRecorded in
lc.validation.bootstrap, permutation_test, joint_stationary_bootstrap, reality_check, superior_predictive_abilityThe seed set with lc.configure(seed=...) or lc.config(seed=...), otherwise fresh random entropymetadata.seed
lc.events.event_response, lc.signal.fit_decayFresh random entropymetadata.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_perturbationThe default seed is 0, so it is deterministic unless you change itmetadata.seed and metadata.parameters
SignalStudy.auditPasses 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 recordedthe 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.

ContainerReturned byHoldsAlso provides
LabelResultlc.labels.forward_returns, SignalStudy.labels()frame: the label rowsmetadata, to_json()
SignalTransformResultlc.signal.bucketize, neutralizeframe: the transformed signalmetadata, to_json()
PortfolioProjectionResultlc.signal.portfolio_projectionframe: the projected cohortmetadata, to_json()
EventWindowResultlc.events.event_windowsframe: the event pathsmetadata, to_json()
SplitResultlc.cv.PurgedKFold.split, lc.cv.WalkForward.splitfolds: a tuple of Foldfold_table, to_json(); iterating yields (train, test) index arrays
CombinatorialSplitResultlc.cv.CombinatorialPurgedKFold.splitfolds and pathsfold_table, path_table, to_json(); iterable like SplitResult
PointInTimeJoinResult, MembershipResultlc.bias.asof_join, membership_atframemetadata
AdaptedFramelc.adapters.adapt_vendor, adapt_factor_panel, adapt_backtest, from_duckdbframe, which may stay lazycolumns, lazy
ActivatedPluginlc.plugins.activate_plugindescriptor, implementation and the activation recordnone 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.

FieldMeaning
codeStable identifier, uppercase by convention. Required, nonempty.
titleShort label. Required.
messageOne sentence. Required.
stateA FindingState. Required.
severityA Severity. Defaults to INFO.
categoryGrouping label. Defaults to general.
evidenceMapping of the figures behind the finding.
FieldMeaning
metadataA ResultMetadata. Required.
metricsMapping of scalars.
findingsA sequence of Finding.
tablesMapping of table names to lists of row mappings.
warningsNonempty strings.
schema_versionLeave 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

The generated signatures for AnalysisResult, ResultMetadata, Finding, FindingState and Severity are on the lacuna API page.