Audits and reports
Run the signal audit, read its findings and score, supply the evidence it is missing, write your own rules, and render the result as JSON, Markdown or HTML.
A signal that looks good is rarely the whole story. The questions that decide whether a result can be trusted are the ones a notebook never answers on its own: was the validation split purged, were delisted instruments in the sample, how many variants were tried before this one. An audit turns those questions into checks that each end in an explicit state, so a missing answer shows up as a gap instead of as silence.
SignalStudy.audit computes the diagnostics for a signal, evaluates 13 rules against that evidence, and returns an AuditReport. Every rule ends in PASS, WARN, FAIL, UNKNOWN or NOT_APPLICABLE. An UNKNOWN is not a failure of the signal. It means Lacuna was never told, and this page shows how to tell it, and which answers Lacuna can verify and which it can only record.
A first audit
A synthetic panel of 30 instruments over 120 sessions. Yesterday’s signal weakly predicts today’s return, and one instrument, S29, delists on session 100 with a terminal return of −35%.
from datetime import date, timedelta
import lacuna as lc
import numpy as np
import polars as pl
rng = np.random.default_rng(1)
n_instruments, n_sessions = 30, 120
calendar = (date(2024, 1, 1) + timedelta(days=k) for k in range(200))
sessions = [day for day in calendar if day.weekday() < 5][:n_sessions]
instruments = [f"S{i:02d}" for i in range(n_instruments)]
signal_values = rng.normal(size=(n_sessions, n_instruments))
returns = rng.normal(scale=0.02, size=(n_sessions, n_instruments))
returns[1:] += 0.004 * signal_values[:-1]
close = 100 * np.cumprod(1 + returns, axis=0)
rows = [
(day, name, close[i, j], signal_values[i, j])
for i, day in enumerate(sessions)
for j, name in enumerate(instruments)
]
panel = pl.DataFrame(rows, schema=["time", "instrument", "close", "signal"], orient="row")
signal = panel.select("time", "instrument", "signal")
last_day = sessions[99]
prices = (
panel.select("time", "instrument", "close")
.filter(~((pl.col("instrument") == "S29") & (pl.col("time") > last_day)))
.with_columns(
pl.when((pl.col("instrument") == "S29") & (pl.col("time") == last_day))
.then(-0.35)
.otherwise(None)
.cast(pl.Float64)
.alias("delisting_return")
)
)
study_args = dict(
signal=signal,
prices=prices,
horizons=("1D", "5D", "10D"),
signal_observed_at="open",
entry="current_close",
price_adjustment="total_return_adjusted",
)
study = lc.SignalStudy(**study_args)
report = study.audit(bootstrap_resamples=200, seed=1)
print(report.summary()) {'robustness_score': 78.0, 'evidence_coverage': 0.78, 'failure_count': 0, 'warning_count': 0, 'unknown_count': 4, 'not_applicable_count': 1} for finding in report.findings:
print(f"{finding.state.value:<15} {finding.code:<32} {finding.severity.value}") PASS TURNOVER_MEASURED medium
NOT_APPLICABLE TRANSACTION_COST_EVIDENCE high
UNKNOWN DELISTING_HANDLING_DECLARED high
PASS PRICE_ADJUSTMENT_DECLARED high
UNKNOWN TRIAL_HISTORY_AVAILABLE high
PASS HORIZON_DECAY_COVERAGE medium
PASS BOOTSTRAP_INTERVAL high
PASS IC_DEFINED high
PASS IC_PERIOD_SUPPORT high
PASS QUANTILE_MONOTONICITY medium
UNKNOWN PURGED_VALIDATION_SUPPLIED high
UNKNOWN SURVIVORSHIP_HANDLING_DECLARED high
PASS LABEL_INTERVALS_PRESENT critical Nothing failed and nothing warned, yet the score is 78 and four checks are UNKNOWN. The signal’s own statistics are fine in this sample. What is missing is the context around it: the validation split, delisting handling, survivorship, and trial history. Supplying evidence answers each one.
The 200 resamples keep the example quick. The default is 1,000 and the minimum is 100.
What the audit computes
audit() builds up to seven named pieces of evidence, every one an AnalysisResult, and then runs the rules over them by name.
| Name | Method | Produced by |
|---|---|---|
labels | labels.forward_returns | study.labels(): the forward returns, with intervals and what was dropped. |
ic | signal.ic.spearman | study.ic(): the cross-sectional rank IC for every horizon. |
quantiles | signal.quantiles | study.quantiles(): quantile returns and their monotonicity. |
turnover | signal.turnover | study.turnover(): rank turnover between consecutive observations. |
decay | signal.decay | study.decay(): IC and top-minus-bottom spread across the study’s horizons. |
bootstrap | validation.bootstrap.iid | An IID bootstrap of the mean IC at the inference horizon. Omitted when fewer than two usable periods exist. |
split | the split’s own method | Only when you pass split=. |
The report keeps all of it. report.result is the audit itself, an AnalysisResult with method audit.v0_1. report.evidence maps each name above to its result, and report.table(name, source=...) reads any stored table:
print(sorted(report.evidence))
print(report.result.metadata.method, report.result.metadata.method_version)
print(report.table("ic_by_horizon", source="ic")[0]["horizon"]) ['bootstrap', 'decay', 'ic', 'labels', 'quantiles', 'turnover']
audit.v0_1 1
1D The inference horizon
A study can have several horizons, but the bootstrap needs one estimand. Pooling every (date, horizon) IC value into one series mixes horizons, and overlapping labels make neighbouring values dependent. So the audit infers on one declared horizon, the first in horizons unless you choose another, and resamples only the periods whose label intervals do not overlap.
Choose the horizon before you look at the results, with the inference_horizon policy:
ten_day = study.audit(
bootstrap_resamples=200, seed=1, policies={"inference_horizon": "10D"}
)
finding = next(f for f in ten_day.findings if f.code == "BOOTSTRAP_INTERVAL")
print(finding.state.value, "-", finding.message)
print({key: finding.evidence[key] for key in ("inference_horizon", "n_resampled")})
support = next(f for f in ten_day.findings if f.code == "IC_PERIOD_SUPPORT")
print(support.state.value, support.evidence["n_periods"]) WARN - Fewer than 30 periods were resampled, so the interval is too imprecise to support or reject the mean IC.
{'inference_horizon': '10D', 'n_resampled': 11}
PASS 110 Ten-day labels over 120 sessions leave only a handful of non-overlapping periods, so the rule warns instead of passing: an interval from fewer than 30 resampled periods cannot support or reject the mean IC. IC_PERIOD_SUPPORT counts every defined IC period at the horizon, and consecutive 10-day periods overlap, so it passes on 110 periods while only 11 independent ones exist. The bootstrap’s n_resampled is the independent sample size. When the two disagree, trust n_resampled. A horizon that is not one of the study’s horizons raises MethodContractError.
Reading the report
An AuditReport exposes the audit’s headline numbers and its findings. report.summary() returns the headline metrics that are present (the score, the coverage and the count of each state), and report.metrics returns all of the audit’s metrics. report.findings is the tuple of Finding objects, sorted by category, then state (FAIL, WARN, UNKNOWN, PASS, NOT_APPLICABLE), then severity, then code. Each finding carries what you need to act on it:
finding = next(f for f in report.findings if f.code == "PRICE_ADJUSTMENT_DECLARED")
print(finding.title)
print(finding.message)
print(finding.severity.value, finding.category)
print(dict(finding.evidence)) Price adjustment semantics are declared
Price adjustment semantics are explicitly declared.
high data_integrity
{'rule_version': 1, 'weight': 8.0, 'price_adjustment': 'total_return_adjusted'} State and severity are separate. The state says what the check found. The severity says how much the check matters: info, low, medium, high or critical. Every finding’s evidence carries the rule version and weight, so a stored audit says which version of each rule produced it.
| State | Meaning |
|---|---|
PASS | The check ran and the evidence satisfied it. |
WARN | The check ran and the evidence is weak or borderline. |
FAIL | The check ran and the evidence contradicts the claim. |
UNKNOWN | The evidence the check needs was not supplied, or could not support a verdict. |
NOT_APPLICABLE | The check does not apply to this kind of study. |
UNKNOWN and NOT_APPLICABLE are different. NOT_APPLICABLE is an assertion about the study. UNKNOWN is a gap in the evidence.
Scoring
The audit’s headline numbers are a weighted checklist. Each rule has a weight and a finding state . A state earns a credit :
| State | Credit |
|---|---|
PASS | 1 |
WARN | 0.5 |
FAIL | 0 |
UNKNOWN | 0 |
NOT_APPLICABLE | excluded |
Over the set of applicable rules, the score and the evidence coverage are
A missing answer earns no credit but still counts in the denominator, so incomplete evidence lowers the score instead of being ignored. Coverage separates the two causes of a low score: a FAIL lowers the score and leaves coverage unchanged, an UNKNOWN lowers both.
With no applicable rules the score is 0.0 and the coverage is 1.0. A run of lc.audit() with no evidence at all has every rule UNKNOWN, so both are 0.
The score is broken down by category in score_components. For each category, score is the same formula restricted to that category’s rules, and unknown_weight is the weight that had no evidence:
components = pl.DataFrame(report.table("score_components"))
print(components.select("category", "earned_weight", "possible_weight", "unknown_weight", "score"))
print({key: report.metrics[key] for key in ("earned_weight", "possible_weight", "unknown_weight")}) shape: (6, 5)
┌──────────────────────┬───────────────┬─────────────────┬────────────────┬───────────┐
│ category ┆ earned_weight ┆ possible_weight ┆ unknown_weight ┆ score │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════════════════════╪═══════════════╪═════════════════╪════════════════╪═══════════╡
│ costs_capacity ┆ 4.0 ┆ 4.0 ┆ 0.0 ┆ 100.0 │
│ data_integrity ┆ 8.0 ┆ 16.0 ┆ 8.0 ┆ 50.0 │
│ experiment_integrity ┆ 0.0 ┆ 2.0 ┆ 2.0 ┆ 0.0 │
│ robustness ┆ 10.0 ┆ 10.0 ┆ 0.0 ┆ 100.0 │
│ statistical_validity ┆ 46.0 ┆ 46.0 ┆ 0.0 ┆ 100.0 │
│ temporal_integrity ┆ 10.0 ┆ 22.0 ┆ 12.0 ┆ 45.454545 │
└──────────────────────┴───────────────┴─────────────────┴────────────────┴───────────┘
{'earned_weight': 78.0, 'possible_weight': 100.0, 'unknown_weight': 22.0} The audit records how it scored in report.result.metadata.parameters: score_version 1, unknown_credit 0.0, warn_credit 0.5 and not_applicable_policy "excluded", plus the version of every rule that ran. A report generated under a different score version or rule version is a different measurement. Compare scores only when those match.
The score is a measure of how much of the checklist was satisfied. It is not a probability that the signal works, and it does not rank research quality. A score of 100 means the 12 applicable rules all passed (TRANSACTION_COST_EVIDENCE is NOT_APPLICABLE for signal studies). Some of those rules test outcomes: the bootstrap interval and quantile monotonicity. Others test only that evidence exists or that something was declared, as The rules lists. It has not been shown to be profitable.
The rules
lc.default_rules() returns the ordered rule set. The weights sum to 104, of which 100 apply to a signal study because TRANSACTION_COST_EVIDENCE is NOT_APPLICABLE there.
| Code | Category | Severity | Weight | Reads | Rule |
|---|---|---|---|---|---|
IC_DEFINED | statistical_validity | high | 12 | ic | PASS if the inference horizon has a defined mean IC; FAIL if no IC period survives the sample and variance checks. UNKNOWN without ic evidence, or with multi-horizon evidence and no matching inference_horizon. |
IC_PERIOD_SUPPORT | statistical_validity | high | 12 | ic | Counts all defined IC periods at the inference horizon, overlapping ones included: PASS at 60 or more, WARN from 20 to 59, FAIL below 20. UNKNOWN in the same cases as IC_DEFINED. |
QUANTILE_MONOTONICITY | statistical_validity | medium | 10 | quantiles | Spearman correlation between quantile rank and mean quantile return: PASS at 0.7 or more, WARN at 0.4 or more, FAIL below 0.4, which includes inverted orderings. It scores the monotonicity table’s row for the inference horizon, not the headline metric, which belongs to the first declared horizon and can differ. UNKNOWN if the metric is missing, or with multi-horizon evidence and no matching inference_horizon. |
BOOTSTRAP_INTERVAL | statistical_validity | high | 12 | bootstrap | WARN if fewer than 30 periods were resampled. Otherwise PASS if the interval is strictly above zero, FAIL if strictly below, WARN if it contains zero. UNKNOWN if the bounds or the sample count are missing. |
HORIZON_DECAY_COVERAGE | robustness | medium | 10 | decay | Counts horizons whose ic_decay row has a defined mean IC: PASS at 3 or more, WARN at 2, FAIL below 2. It measures how many horizons you declared, not how the IC decays. One horizon records a FAIL and two can only WARN. UNKNOWN without the per-horizon table. |
LABEL_INTERVALS_PRESENT | temporal_integrity | critical | 10 | labels | PASS if the evidence is a labels.forward_returns result; otherwise UNKNOWN. A method-name check. |
PURGED_VALIDATION_SUPPLIED | temporal_integrity | high | 10 | split | Reads the evidence of a cv.purged_kfold or cv.combinatorial_purged_kfold split; any other method is UNKNOWN, as is a split that reports no purge count. WARN when the split purged nothing (purged_observations of 0) although the inference horizon, "ND" or the integer N with N of 2 or more, spans several observations. Otherwise PASS. A pass records data_identity_verified: false: split evidence carries no input fingerprint, so the rule cannot check that the split came from the audited labels. |
PRICE_ADJUSTMENT_DECLARED | data_integrity | high | 8 | labels | UNKNOWN if the labels carry PRICE_ADJUSTMENT_UNKNOWN; otherwise PASS. |
DELISTING_HANDLING_DECLARED | data_integrity | high | 8 | labels | UNKNOWN if the labels carry DELISTING_RETURNS_UNKNOWN; otherwise PASS. |
TURNOVER_MEASURED | costs_capacity | medium | 4 | turnover | PASS if mean rank turnover is a number; otherwise UNKNOWN. It has no threshold and never warns. |
SURVIVORSHIP_HANDLING_DECLARED | temporal_integrity | high | 2 | policy survivorship_safe | UNKNOWN if not declared; PASS if declared True; WARN for any other value. |
TRIAL_HISTORY_AVAILABLE | experiment_integrity | high | 2 | policy trial_history_available | Same rule as above. |
TRANSACTION_COST_EVIDENCE | costs_capacity | high | 4 | policy transaction_costs_available | NOT_APPLICABLE when the study_type policy is "signal". Otherwise the same rule as above. |
for rule in lc.default_rules():
print(f"{rule.rule_id:<32} v{rule.rule_version} {rule.category:<20} {rule.weight:>4.0f}")
print(sum(rule.weight for rule in lc.default_rules())) IC_DEFINED v2 statistical_validity 12
IC_PERIOD_SUPPORT v2 statistical_validity 12
QUANTILE_MONOTONICITY v2 statistical_validity 10
BOOTSTRAP_INTERVAL v2 statistical_validity 12
HORIZON_DECAY_COVERAGE v2 robustness 10
LABEL_INTERVALS_PRESENT v1 temporal_integrity 10
PURGED_VALIDATION_SUPPLIED v2 temporal_integrity 10
PRICE_ADJUSTMENT_DECLARED v1 data_integrity 8
DELISTING_HANDLING_DECLARED v1 data_integrity 8
TURNOVER_MEASURED v1 costs_capacity 4
SURVIVORSHIP_HANDLING_DECLARED v1 temporal_integrity 2
TRIAL_HISTORY_AVAILABLE v1 experiment_integrity 2
TRANSACTION_COST_EVIDENCE v1 costs_capacity 4
104.0 A few properties of these rules matter when you read a result.
Four rules read thresholds that you cannot change from the call: 60 and 20 periods, 0.7 and 0.4 monotonicity, 3 and 2 horizons with a defined IC, and 30 resampled periods. If your house standard differs, write a custom rule instead of reinterpreting the finding.
No rule tests the size of the IC. IC_DEFINED only checks that one exists, and strength enters only through the bootstrap interval and quantile monotonicity. The bootstrap rule treats a positive mean IC as the hypothesis: a signal with a reliably negative IC FAILs. If you expect an inverse relationship, flip the signal’s sign before the study.
Several checks are about what you declared, or about which method produced a result, rather than what Lacuna measured. LABEL_INTERVALS_PRESENT and PURGED_VALIDATION_SUPPLIED test the method name of the evidence, and the second also reads its purge count. Four more rest on declarations, and they are worth 20 of the 100 points. PRICE_ADJUSTMENT_DECLARED passes for any price_adjustment other than "unknown", including "raw", so it records that you made a declaration, not that the prices are adjusted correctly. DELISTING_HANDLING_DECLARED passes once you name a delisting_return column. SURVIVORSHIP_HANDLING_DECLARED and TRIAL_HISTORY_AVAILABLE pass on a single boolean.
A declared policy that is not True earns a WARN, which is half credit, and counts as supplied evidence. Declaring survivorship_safe=False raises the score and the coverage slightly, from 86.0 and 0.86 to 87.0 and 0.88 in the example above, so admitting a problem scores higher than saying nothing. The WARN is the only signal. Read warnings, not the score.
Supplying evidence
Every UNKNOWN points at a specific piece of missing context. There are four ways to supply it, and they differ in how much Lacuna can check.
| Question | Finding | You supply | Lacuna checks it? |
|---|---|---|---|
| Was the validation split purged? | PURGED_VALIDATION_SUPPLIED | split= with a PurgedKFold or CombinatorialPurgedKFold result | It checks that the evidence came from a purged split and that the purge count is consistent with the inference horizon. It does not check that the split came from the audited labels or that your model was validated on those folds. |
| How were delisted instruments handled? | DELISTING_HANDLING_DECLARED | A delisting_return column, named on the study | It uses the column in the labels. It does not check that the column is complete. |
| What do the prices include? | PRICE_ADJUSTMENT_DECLARED | price_adjustment= on the study | No. A caller assertion. |
| Was the universe survivorship-safe? | SURVIVORSHIP_HANDLING_DECLARED | policies={"survivorship_safe": True} | No. A caller assertion. |
| Is the full trial history available? | TRIAL_HISTORY_AVAILABLE | policies={"trial_history_available": True} | No. A caller assertion. |
| Are transaction costs evidenced? | TRANSACTION_COST_EVIDENCE | policies={"transaction_costs_available": True} | No. A caller assertion. |
Here is the audit above with each answer added in turn. A helper keeps the calls short:
def run(study, **kwargs):
return study.audit(bootstrap_resamples=200, seed=1, **kwargs)
def unknown_codes(report):
return [f.code for f in report.findings if f.state == lc.FindingState.UNKNOWN]
stages = {}
stages["baseline"] = run(study)
with_delisting = lc.SignalStudy(**study_args, delisting_return="delisting_return")
stages["+ delisting_return"] = run(with_delisting)
split = lc.cv.PurgedKFold(n_splits=5, embargo=2).split(with_delisting.labels().frame)
stages["+ purged split"] = run(with_delisting, split=split)
declared = {"survivorship_safe": True, "trial_history_available": True}
stages["+ declared policies"] = run(with_delisting, split=split, policies=declared)
for name, stage in stages.items():
summary = stage.summary()
print(
f"{name:<22} score {summary['robustness_score']:>5.1f} "
f"coverage {summary['evidence_coverage']:.2f} unknown {summary['unknown_count']}"
) baseline score 78.0 coverage 0.78 unknown 4
+ delisting_return score 86.0 coverage 0.86 unknown 3
+ purged split score 96.0 coverage 0.96 unknown 2
+ declared policies score 100.0 coverage 1.00 unknown 0 Validation split: split=
split= takes the SplitResult from PurgedKFold.split, the CombinatorialSplitResult from CombinatorialPurgedKFold.split, or any AnalysisResult such as a split’s .evidence. The audit stores it under the name split. PURGED_VALIDATION_SUPPLIED reads evidence whose method is cv.purged_kfold or cv.combinatorial_purged_kfold. Any other method gives UNKNOWN, including walk-forward splits, which do not purge. A split whose evidence has no purge count is also UNKNOWN.
walk_forward = lc.cv.WalkForward(train="60D", test="10D", step="10D")
splits = walk_forward.split(with_delisting.labels().frame, time="observation_time")
finding = next(f for f in run(with_delisting, split=splits).findings if f.code == "PURGED_VALIDATION_SUPPLIED")
print(finding.state.value, "-", finding.message) UNKNOWN - The supplied split evidence does not establish purged validation. A combinatorial split passes the same way. Below, a combinatorial split of every label passes. The second split covers only the one-day labels, whose intervals do not overlap and so purge nothing; audited against a five-day inference horizon, it warns:
labels_frame = with_delisting.labels().frame
combinatorial = lc.cv.CombinatorialPurgedKFold(n_groups=5, n_test_groups=2, embargo=2).split(labels_frame)
one_day = lc.cv.PurgedKFold(n_splits=5).split(labels_frame.filter(pl.col("horizon") == "1D"))
for name, evidence in (("combinatorial", combinatorial), ("one-day labels", one_day)):
report_5d = run(with_delisting, split=evidence, policies={"inference_horizon": "5D"})
finding = next(f for f in report_5d.findings if f.code == "PURGED_VALIDATION_SUPPLIED")
print(f"{name:<15}", finding.state.value, finding.evidence["purged_observations"], finding.evidence["data_identity_verified"]) combinatorial PASS 14307 False
one-day labels WARN 0 False A passing split must still be the right one, and the rule can only partly tell. It cannot verify that the split was built from this study’s labels, and a pass records data_identity_verified: false. It does compare the purge count with the inference horizon. If the horizon is "2D" or longer and the split purged nothing, the rule warns: consecutive labels of that horizon overlap, so a split purged against them removes at least one observation. A split of non-overlapping sampled labels legitimately purges nothing, and the rule cannot tell the two apart, hence a warning and not a failure. Split the labels the study built, filtered to the inference horizon, so the intervals the folds purge are the intervals the labels cover. Cross-validation explains purging and embargo.
Delisting and price basis: the study
These two answers are arguments to SignalStudy, not to audit(), because they change how the labels are built. price_adjustment takes "raw", "split_adjusted", "total_return_adjusted" or "unknown", and delisting_return names a column. Having a delisting column in your prices is not enough: until the study names it, DELISTING_HANDLING_DECLARED stays UNKNOWN. Forward-return labels covers how the column is used.
Policies: policies=
policies is a mapping of declared facts that the rules read. Lacuna records each one and cannot verify any of them. These are the keys the built-in rules read:
| Key | Type | Effect |
|---|---|---|
survivorship_safe | boolean | True passes SURVIVORSHIP_HANDLING_DECLARED. Any other value warns. |
trial_history_available | boolean | True passes TRIAL_HISTORY_AVAILABLE. Any other value warns. |
transaction_costs_available | boolean | True passes TRANSACTION_COST_EVIDENCE, which is only applicable when study_type is not "signal". |
inference_horizon | string or integer | The study horizon the IC rules, the monotonicity rule and the bootstrap evaluate, written as in the evidence, such as "5D". A positive integer N names the "ND" horizon. Defaults to the first study horizon. SignalStudy.audit converts an integer to its string form; lc.audit and run_audit keep it as given, so finding evidence records 5, not "5D". |
study_type | string | SignalStudy.audit sets "signal". Setting it to anything else makes the cost rule applicable. |
SignalStudy.audit also records ic_inference_sampling ("non_overlapping_label_intervals") and refuses to let you override it. Other keys are ignored by the built-in rules, though your own rules can read them and the standardized audit stores them in its metadata.
A policy that is declared but not True produces a WARN, not a FAIL: the declaration is on the record and does not confirm the safeguard.
doubtful = run(with_delisting, split=split, policies={"survivorship_safe": "probably"})
finding = next(f for f in doubtful.findings if f.code == "SURVIVORSHIP_HANDLING_DECLARED")
print(finding.state.value, "-", finding.message)
print(dict(finding.evidence)) WARN - The supplied policy does not confirm this safeguard.
{'rule_version': 1, 'weight': 2.0, 'policy': 'survivorship_safe', 'value': 'probably'} survivorship_safe=True is your word, and it earns the same credit as a verified universe. Back it with evidence (a point-in-time membership table, a survivorship diagnostic) and attach that evidence with additional_evidence= so a reviewer can see what the claim rests on.
Other evidence: additional_evidence=
additional_evidence maps names to AnalysisResult values you computed elsewhere. They are stored in the report, so they appear in report.evidence, in plotted panels and in bundles. The built-in rules do not read them. Attaching a survivorship diagnostic does not change SURVIVORSHIP_HANDLING_DECLARED; only the policy does.
membership = pl.DataFrame(
{
"index": ["UNIV"] * 3,
"instrument": ["S00", "S01", "S29"],
"valid_from": [date(2023, 12, 1)] * 3,
"valid_to": [None, None, date(2024, 5, 17)],
"available_time": [date(2023, 12, 1)] * 3,
"delisted": [False, False, True],
}
)
survivorship = lc.bias.survivorship_diagnostics(
membership, delisted="delisted", source_status="confirmed_safe", includes_delisted=True
)
attached = run(
with_delisting,
split=split,
policies=declared,
additional_evidence={"survivorship": survivorship},
)
print(sorted(attached.evidence))
print(attached.summary()["robustness_score"]) ['bootstrap', 'decay', 'ic', 'labels', 'quantiles', 'split', 'survivorship', 'turnover']
100.0 Names must be non-empty and must not collide with the study’s own evidence: labels, ic, quantiles, turnover, decay, bootstrap, and split when you pass split=. A collision raises MethodContractError, and the name audit is reserved and raises ReportError.
The standardized audit does read this evidence, by method rather than by name. It is the place where the survivorship result counts as survivorship evidence.
Auditing evidence you built yourself
SignalStudy.audit is a convenience over two functions. lc.run_audit(context) evaluates rules against an AuditContext of named results and declared policies and returns the audit as an AnalysisResult. lc.audit(results=..., policies=...) does the same and wraps the result in an AuditReport.
context = lc.AuditContext(
results={name: result for name, result in report.evidence.items()},
policies={"inference_horizon": "1D"},
)
audit_result = lc.run_audit(context)
print(audit_result.metadata.method, audit_result.metrics["robustness_score"])
manual = lc.audit(results=dict(report.evidence), policies={"inference_horizon": "1D"})
print(manual.summary())
print(sorted(manual.evidence)) audit.v0_1 75.0
{'robustness_score': 75.0, 'evidence_coverage': 0.75, 'failure_count': 0, 'warning_count': 0, 'unknown_count': 5, 'not_applicable_count': 0}
[] A few things differ from SignalStudy.audit. The context has no study_type, so TRANSACTION_COST_EVIDENCE is UNKNOWN, not NOT_APPLICABLE, and the score is lower. Evidence with more than one horizon needs an inference_horizon policy or IC_DEFINED, IC_PERIOD_SUPPORT and QUANTILE_MONOTONICITY are UNKNOWN. An integer policy such as 5 reads the "5D" horizon, as it does there, but the findings record it as 5 rather than "5D". And lc.audit does not retain the results in the report: manual.evidence is empty, which matters for bundles and Plotly views. Wrap them yourself with lc.AuditReport(audit_result, evidence=...) when you need them.
Custom rules
A rule is any object with the six attributes and two methods of the AuditRule protocol: rule_id, rule_version, title, category, severity and weight, plus applicable(context) and evaluate(context).
applicable returns an Applicability: APPLICABLE when the rule can run, UNKNOWN when the evidence it needs is missing, NOT_APPLICABLE when the rule does not apply. evaluate runs only for applicable rules and returns a Finding.
from dataclasses import dataclass
@dataclass(frozen=True)
class MinimumInstruments:
minimum: int = 40
rule_id: str = "MIN_INSTRUMENTS"
rule_version: int = 1
title: str = "Cross-section is wide enough"
category: str = "statistical_validity"
severity: lc.Severity = lc.Severity.MEDIUM
weight: float = 6.0
def applicable(self, context: lc.AuditContext) -> lc.Applicability:
if "labels" not in context.results:
return lc.Applicability(lc.ApplicabilityState.UNKNOWN, "label evidence was not supplied")
return lc.Applicability(lc.ApplicabilityState.APPLICABLE, "label evidence is available")
def evaluate(self, context: lc.AuditContext) -> lc.Finding:
count = context.results["labels"].metrics["n_instruments"]
state = lc.FindingState.PASS if count >= self.minimum else lc.FindingState.WARN
return lc.Finding(
code=self.rule_id,
title=self.title,
message=f"The panel has {count} instruments; the house minimum is {self.minimum}.",
state=state,
severity=self.severity,
category=self.category,
evidence={"rule_version": self.rule_version, "weight": self.weight, "n_instruments": count},
)
custom = run(with_delisting, split=split, policies=declared, rules=(*lc.default_rules(), MinimumInstruments()))
finding = next(f for f in custom.findings if f.code == "MIN_INSTRUMENTS")
print(finding.state.value, "-", finding.message)
print(custom.summary()["robustness_score"], custom.result.metadata.parameters["rule_versions"]["MIN_INSTRUMENTS"]) WARN - The panel has 30 instruments; the house minimum is 40.
97.16981132075472 1 rules= replaces the default set, so pass (*lc.default_rules(), MyRule()) to add to it. The engine enforces the contract before it trusts a rule:
| Requirement | If violated |
|---|---|
rule_id is non-empty and unique across the rule set. | ValueError |
rule_version is at least 1, and title and category are non-empty. | ValueError |
weight is positive and finite. | ValueError |
evaluate returns a finding whose code, category and severity match the rule’s own. | ValueError |
A rule that raises is not caught: the exception propagates and the audit fails, so a broken rule cannot masquerade as a passing check. Include the rule’s version and weight in the finding’s evidence, as the built-in rules do, and bump rule_version whenever its logic changes. The version is how a stored audit says which logic produced it.
A rule’s weight joins the denominator of the score. Adding rules changes every score the audit produces, so scores from different rule sets are not comparable.
Standardized audit
The signal audit is built around one study. Real research accumulates evidence from many methods: purged cross-validation, selection-aware inference, robustness, costs, point-in-time checks. The standardized audit answers a different question over that evidence: which of the capabilities a research claim needs have been evidenced at all?
lc.standard_audit(results=..., scope=...) takes any set of named AnalysisResult values, matches each one to a capability by its method name, and reports coverage against a profile. It does not compute a score. A single number across different methods would hide exactly the distinctions a review depends on.
standard = lc.standard_audit(results=dict(stages["+ purged split"].evidence), scope="signal")
print(standard.summary())
print(
pl.DataFrame(standard.table("evidence_requirements"))
.select("capability", "disposition", "present")
.filter(pl.col("disposition") == "required")
) {'evidence_coverage': 0.2727272727272727, 'required_evidence_coverage': 0.2727272727272727, 'optional_evidence_coverage': 0.0, 'required_evidence_complete': False, 'failure_count': 0, 'warning_count': 1, 'unknown_count': 8, 'not_applicable_count': 5}
shape: (11, 3)
┌──────────────────────┬─────────────┬─────────┐
│ capability ┆ disposition ┆ present │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ bool │
╞══════════════════════╪═════════════╪═════════╡
│ signal_diagnostics ┆ required ┆ true │
│ temporal_validation ┆ required ┆ true │
│ resampling_inference ┆ required ┆ true │
│ experiment_lineage ┆ required ┆ false │
│ multiple_testing ┆ required ┆ false │
│ … ┆ … ┆ … │
│ temporal_robustness ┆ required ┆ false │
│ universe_robustness ┆ required ┆ false │
│ regime_robustness ┆ required ┆ false │
│ point_in_time_data ┆ required ┆ false │
│ survivorship ┆ required ┆ false │
└──────────────────────┴─────────────┴─────────┘ Eleven capabilities are required for a signal scope, and this study evidenced three of them: signal diagnostics, temporal validation and resampling inference. Each of the other eight is an UNKNOWN finding.
Scopes and profiles
AuditScope is "signal", "strategy" or "options". lc.standard_profile(scope) returns the built-in AuditProfile for a scope, an immutable list of EvidenceRequirement values. The profile’s requirements are a tuple. Each requirement names a capability, whose identifier starts with a lowercase letter, the method patterns that count as evidence for it (one trailing * allowed), and a disposition:
| Disposition | With evidence | Without evidence |
|---|---|---|
required | PASS: recognized evidence is present | UNKNOWN |
optional | PASS | NOT_APPLICABLE |
not_applicable | WARN: evidence supplied for a capability this scope excludes | NOT_APPLICABLE |
The built-in profiles, by capability:
| Capability | Accepted methods | signal | strategy | options |
|---|---|---|---|---|
signal_diagnostics | labels.*, signal.* | required | optional | optional |
temporal_validation | cv.* | required | required | required |
resampling_inference | validation.bootstrap.*, validation.permutation.* | required | required | required |
advanced_inference | validation.sharpe_inference, validation.probability_of_backtest_overfitting, validation.joint_stationary_bootstrap, validation.white_reality_check, validation.hansen_spa | optional | required | required |
experiment_lineage | experiment.* | required | required | required |
multiple_testing | validation.multiple_testing.* | required | required | required |
parameter_robustness | validation.parameter_surface, robustness.continuous_perturbation | required | required | required |
temporal_robustness | robustness.subperiod_analysis | required | required | required |
universe_robustness | robustness.universe_perturbation | required | required | optional |
regime_robustness | regime.* | required | required | optional |
execution_realism | costs.* | not applicable | required | required |
point_in_time_data | bias.asof_join, bias.future_data_check, bias.revision_diagnostics, bias.validate_dataset | required | required | required |
survivorship | bias.survivorship_diagnostics, bias.membership_at, bias.universe_drift | required | required | optional |
adapter_provenance | adapters.* | optional | optional | optional |
plugin_provenance | plugins.* | optional | optional | optional |
options_evidence | options.* | not applicable | not applicable | required |
for scope in ("signal", "strategy", "options"):
profile = lc.standard_profile(scope)
counts = {}
for requirement in profile.requirements:
counts[requirement.disposition.value] = counts.get(requirement.disposition.value, 0) + 1
print(profile.profile_id, profile.profile_version, counts) standard.signal 1 {'required': 11, 'optional': 3, 'not_applicable': 2}
standard.strategy 1 {'optional': 3, 'required': 12, 'not_applicable': 1}
standard.options 1 {'optional': 6, 'required': 10} Findings in a standardized audit
A standardized audit has three kinds of findings.
Coverage findings have the code EVIDENCE_ plus the capability in upper case, for example EVIDENCE_TEMPORAL_VALIDATION. A PASS here means recognized evidence was supplied. It says nothing about what the evidence concluded, and each one is marked coverage_only in its evidence.
Domain findings have the code DOMAIN_, the capability, and a stable hash suffix. They are the findings of the supplied results, propagated with their original state, severity, category and thresholds, and tagged with the source name, method and finding code. The profile never reinterprets them, so a FAIL in a robustness result stays a FAIL. Findings inside an unrecognized result are not propagated. The audit reads only the results you pass it, so hand it report.evidence (or what you chose to keep); it does not find evidence on its own.
UNRECOGNIZED_EVIDENCE is a WARN raised when a supplied result’s method matches no capability in the profile. The result is kept in the evidence inventory but satisfies nothing. A result that matches more than one capability raises ValueError.
Coverage appears in the metrics as required_evidence_coverage (also reported as evidence_coverage), optional_evidence_coverage and the required_evidence_complete flag. The tables are category_coverage, evidence_requirements, evidence_inventory and domain_findings. The method is audit.standard. Declared policies are stored in metadata.parameters, and a study_type policy that disagrees with the requested scope raises ValueError.
required_evidence_coverage is the number of required capabilities with at least one matching result, divided by the number of required capabilities. It is unweighted and tests presence only, so it is not comparable with the signal audit’s evidence_coverage. required_evidence_complete can be True while domain findings are FAIL. With no optional capabilities the optional coverage is 1.0, and the required coverage is 1.0 if none are required.
Add the evidence a signal claim needs beyond the single study, and the coverage moves:
registry = lc.ExperimentRegistry("momentum")
for lookback, p_value in ((5, 0.20), (10, 0.04), (20, 0.01), (40, 0.30)):
registry.record(
parameters={"lookback": lookback},
metric=p_value,
metric_name="p_value",
data_fingerprint="panel-v1",
code_fingerprint="signal-v1",
)
adjusted = lc.validation.multiple_testing(registry, method="holm")
evidence = dict(stages["+ purged split"].evidence)
evidence["experiments"] = registry.to_result()
evidence["multiple_testing"] = adjusted
standard = lc.standard_audit(results=evidence, scope="signal")
print(standard.summary()["required_evidence_coverage"], standard.summary()["unknown_count"])
print([(f.evidence["source_name"], f.evidence["source_finding_code"]) for f in standard.findings if f.state == lc.FindingState.WARN]) 0.45454545454545453 7
[('bootstrap', 'BOOTSTRAP_IID_ASSUMPTION')] Experiments and fingerprints covers the registry. The remaining WARN is a domain finding: the bootstrap result carries its own warning that an IID resample assumes independent periods, and the standardized audit passes it through unchanged. The registry’s EXPERIMENT_SELECTION_MISSING appears as an UNKNOWN domain finding until a selection is recorded.
Custom profiles
A profile is data. Build one from EvidenceRequirement values, or load one from JSON with AuditProfile.from_json, which parses strictly (unknown fields, duplicate keys and non-finite numbers are errors) and never executes anything:
import json
profile = lc.AuditProfile(
profile_id="desk.signal",
profile_version=1,
scope=lc.AuditScope.SIGNAL,
requirements=(
lc.EvidenceRequirement(
"signal_diagnostics",
"Signal diagnostics",
"statistical_validity",
("labels.*", "signal.*"),
lc.EvidenceDisposition.REQUIRED,
),
lc.EvidenceRequirement(
"temporal_validation",
"Temporal validation",
"temporal_integrity",
("cv.*",),
lc.EvidenceDisposition.REQUIRED,
lc.Severity.CRITICAL,
),
),
)
desk = lc.standard_audit(results=evidence, scope="signal", profile=profile)
print(desk.summary()["required_evidence_complete"], desk.result.metadata.parameters["profile_id"])
print(lc.AuditProfile.from_json(json.dumps(profile.to_dict())) == profile) True desk.signal
True The profile’s scope must equal the scope you request. A capability identifier uses lowercase letters, digits and underscores. The portable form is described by the packaged standard-audit-profile-v1 schema; see Schemas.
Reports and renderers
An AuditReport renders stored results. It never recomputes a method, changes a threshold or reinterprets a state, so every format shows the same numbers. The Markdown and core HTML renderers show the audit result only: its findings, its own tables (score components and finding summary) and its provenance. They do not render the retained evidence tables, and any table they do show is capped at 50 rows. Only the Plotly renderer reads report.evidence. Source-derived text is escaped in Markdown and HTML.
| Method | Returns | Notes |
|---|---|---|
report.to_json() | str | The canonical record: the audit result in schema-v1 form with sorted keys. |
report.to_markdown() | str | A review-friendly summary, findings, the audit’s own tables and provenance. str(report) and report.show() give the same text. |
report.to_html() | str | One self-contained page with no scripts and no external requests. |
report.to_html(renderer="plotly") | str | Interactive panels built from the stored evidence tables. Needs lacuna-quant[report]. |
report.write(path) | Path | Writes JSON, Markdown or HTML, chosen by format= or by the file extension. |
report.bundle(path) | Path | A checksummed archive. See Reproducibility bundles. |
Each of to_json, to_markdown and to_html also accepts a path and writes the file instead of returning text. Writing never silently replaces a file: an existing destination raises ReportError unless you pass overwrite=True. An unrecognized extension or format raises ReportError.
text = report.to_markdown().splitlines()
print("\n".join(text[:10]))
print(report.write("audit.md"), report.write("audit.html"), report.to_json("audit.json"))
html = report.to_html()
print("<script" in html, "http" in html) # Lacuna audit
## Summary
- Robustness score: **78 / 100**
- Evidence coverage: **0.78**
- Failures: **0**
- Warnings: **0**
- Unknown checks: **4**
- Not applicable: **1**
audit.md audit.html audit.json
False False JSON is the record to keep: it round-trips through lc.AnalysisResult.from_json, which validates the schema-v1 envelope. Markdown and HTML are views. The JSON never contains NaN or infinity; results refuse them at construction.
Core and Plotly renderers
The core renderer, the default, is standard library only and produces a static page. The plotly renderer adds interactive panels for the tables it recognizes in the retained evidence: IC by period and horizon, quantile and bucket returns, spreads, turnover by lag, IC decay and its fit, data attrition, portfolio cohorts, and event responses. Each panel names its source result and table, plots every stored row (a table above 10,000 rows is omitted with a notice, never sampled), and the page embeds Plotly’s JavaScript, so it is several megabytes and works offline. It raises ReportError with the install command when jinja2 or plotly is missing.
view chooses which panels appear: "audit" shows only the audit’s own coverage and findings chart, "signal", "portfolio" and "event" add the panels from evidence of that kind, and "auto", the default, picks the first that applies from the retained evidence’s methods (event, then portfolio, then signal, then audit). lacuna.report.ReportView is the type of this argument.
import re
for view in ("audit", "auto"):
page = report.to_html(renderer="plotly", view=view)
print(view, re.findall(r"<h2>(.*?)</h2>", page)) audit ['Audit coverage and findings']
auto ['Audit coverage and findings', 'IC decay', 'IC by period', 'IC by horizon', 'Data attrition', 'Data attrition', 'Quantile returns', 'Top-minus-bottom spread', 'Data attrition', 'Turnover and autocorrelation by lag', 'Data attrition'] A report made by lc.audit retains no evidence, so its auto view is "audit". Use SignalStudy.audit, or build the report with evidence=, to get the data panels.
Parameters
SignalStudy.audit:
| Parameter | Default | Meaning |
|---|---|---|
bootstrap_resamples | 1000 | Resamples for the IC bootstrap. At least 100. The bootstrap’s Monte Carlo resolution is for resamples: more resamples reduce simulation noise in the interval, but cannot add information the periods do not contain. |
seed | None | Root seed for the bootstrap, recorded in the bootstrap evidence’s metadata. Fix it for a reproducible audit; non-negative. Without one, a runtime seed set with lc.configure is used, and failing that a random seed is drawn. |
min_observations | 3 | The fewest aligned signal and label pairs an observation’s cross-section needs to produce an IC. Narrower cross-sections are excluded and counted. At least 2. |
split | None | A SplitResult, CombinatorialSplitResult or AnalysisResult from a purged split. Stored as split. |
policies | None | Declared policies, as in Policies. ic_inference_sampling cannot be set. |
additional_evidence | None | Named AnalysisResult values to retain in the report. Not read by the built-in rules. |
rules | None | Replaces lc.default_rules(). |
use_native | True | Use the Rust kernels for IC, decay and the bootstrap. False runs the Python reference implementations. Only ic and bootstrap record the backend that ran (backend in their parameters); decay, quantiles, turnover and labels do not. |
lc.audit and lc.run_audit:
| Parameter | Default | Meaning |
|---|---|---|
results | None | Named AnalysisResult values: the evidence the rules read by name. |
policies | None | Declared policies. |
rules | None | Replaces lc.default_rules(). |
| Parameter | Default | Meaning |
|---|---|---|
context | required | An AuditContext holding results and policies. Both are copied into read-only mappings. |
rules | None | Replaces lc.default_rules(). |
lc.standard_audit and lc.run_standard_audit:
| Parameter | Default | Meaning |
|---|---|---|
results | None | Named AnalysisResult values. Each is matched to a capability by its method. |
policies | None | Declared policies, stored in the result’s metadata. |
scope | "strategy" | "signal", "strategy" or "options". Chooses the built-in profile. |
profile | None | A custom AuditProfile whose scope equals scope. |
| Parameter | Default | Meaning |
|---|---|---|
context | required | An AuditContext. |
scope | "strategy" | As above. |
profile | None | As above. |
AuditReport.write and AuditReport.to_html:
| Parameter | Default | Meaning |
|---|---|---|
path | required | Destination. Missing parent directories are created. |
format | None | "json", "md", "markdown" or "html". Taken from the file extension when omitted. |
renderer | "core" | "core" or "plotly", for HTML only. |
view | "auto" | "auto", "audit", "signal", "portfolio" or "event", for the Plotly renderer. |
overwrite | False | Replace an existing file. |
| Parameter | Default | Meaning |
|---|---|---|
path | None | Write to this path and return it, instead of returning the HTML. |
renderer | "core" | "core" or "plotly". |
view | "auto" | The Plotly panel set. |
overwrite | False | Replace an existing file. |
The full signatures are in the API reference for lacuna.audit, lacuna.audit_profiles and lacuna.report.