Skip to Content

Quickstart

Audit a signal against a price panel, read the findings, and write a report, in about forty lines of Python.

This walks through one complete signal audit. It builds a small synthetic panel so it runs anywhere, with nothing but the core install. Every output below is what the code prints.

Build a price panel and a signal

Lacuna reads long-form tables: one row per instrument per observation. Prices need a time, an instrument and a price column. The signal needs a time, an instrument and a value. Times must be dates, datetimes, durations or integers; string dates are rejected. Rows need not be sorted, but each (time, instrument) pair must appear once and no key may be null.

quickstart.py
from datetime import date, timedelta

import lacuna as lc
import polars as pl

instruments = ("A", "B", "C", "D", "E", "F")
days = (date(2025, 1, 2) + timedelta(days=n) for n in range(50))
sessions = [day for day in days if day.weekday() < 5][:35]

prices = pl.DataFrame(
    {
        "time": [s for _ in instruments for s in sessions],
        "instrument": [i for i in instruments for _ in sessions],
        "close": [
            100.0 + 4.0 * a + d * (0.3 + 0.05 * a) + 0.2 * ((d + a) % 3)
            for a in range(len(instruments))
            for d in range(len(sessions))
        ],
    }
)
signal = pl.DataFrame(
    {
        "time": [s for s in sessions for _ in instruments],
        "instrument": [i for _ in sessions for i in instruments],
        "signal": [
            float(((d + 2 * a) % 11) - 5)
            for d in range(len(sessions))
            for a in range(len(instruments))
        ],
    }
)
print(prices.head(3))
shape: (3, 3)
┌────────────┬────────────┬───────┐
│ time       ┆ instrument ┆ close │
│ ---        ┆ ---        ┆ ---   │
│ date       ┆ str        ┆ f64   │
╞════════════╪════════════╪═══════╡
│ 2025-01-02 ┆ A          ┆ 100.0 │
│ 2025-01-03 ┆ A          ┆ 100.5 │
│ 2025-01-06 ┆ A          ┆ 101.0 │
└────────────┴────────────┴───────┘

The columns are named time, instrument, signal and close because those are Lacuna’s defaults. If your time, signal or price columns are named differently, pass the names instead of renaming: SignalStudy takes signal_time, price_time, signal_value and price.

If your identifier column has another name, pass instrument="ticker" (or whatever it is called) to SignalStudy, or --instrument on the command line. The same name is read in both tables. The labels Lacuna builds always call the column instrument, and the diagnostics read that.

pandas DataFrames and Arrow tables work too. Lacuna converts them to Polars on the way in.

Describe the study

A SignalStudy holds the two tables and the facts Lacuna cannot infer from them: when the signal was known, when you could trade on it, and what the prices include.

study = lc.SignalStudy(
    signal=signal,
    prices=prices,
    horizons=("1D", "5D", "20D"),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
    quantiles=5,
)
  • horizons are counts of observations per instrument, not calendar days. A "5D" label ends at the fifth observation after the one the signal belongs to. Lacuna never infers a trading calendar from your dates.
  • signal_observed_at="open" says the signal is known at the open of each session, so entering at that session’s close is possible. A signal observed at the close cannot also enter at that close; the first calculation raises an error unless you choose entry="next_open" or "next_close", or pass allow_same_close=True. Both settings are optional, and leaving them out raises no finding: Lacuna then enters at the observation’s own price and has nothing to check, so always set them.
  • price_adjustment records whether prices include dividends and splits. Leave it out and the audit reports the price basis as UNKNOWN.

Forward-return labels covers every timing option.

Measure the signal

The information coefficient is the cross-sectional rank correlation between the signal and the forward return, computed for each observation and summarized per horizon.

ic = study.ic()
print(pl.DataFrame(ic.table("ic_by_horizon")))
shape: (3, 7)
┌─────────┬───────────┬───────────┬──────────┬───────────┬────────────────┬──────────────────────┐
│ horizon ┆ mean_ic   ┆ median_ic ┆ std_ic   ┆ n_periods ┆ n_observations ┆ ic_information_ratio │
│ ---     ┆ ---       ┆ ---       ┆ ---      ┆ ---       ┆ ---            ┆ ---                  │
│ str     ┆ f64       ┆ f64       ┆ f64      ┆ i64       ┆ i64            ┆ f64                  │
╞═════════╪═══════════╪═══════════╪══════════╪═══════════╪════════════════╪══════════════════════╡
│ 1D      ┆ -0.040336 ┆ -0.028571 ┆ 0.384172 ┆ 34        ┆ 204            ┆ -0.104995            │
│ 5D      ┆ -0.051429 ┆ -0.028571 ┆ 0.442525 ┆ 30        ┆ 180            ┆ -0.116216            │
│ 20D     ┆ -0.013333 ┆ 0.142857  ┆ 0.487974 ┆ 15        ┆ 90             ┆ -0.027324            │
└─────────┴───────────┴───────────┴──────────┴───────────┴────────────────┴──────────────────────┘

ic is an AnalysisResult. ic.table(name) returns one of its tables as a list of rows, which any dataframe library can read. ic.metrics summarizes one horizon, the first you declared (1D here, recorded as ic.metadata.parameters["headline_horizon"]), so read the other horizons from ic_by_horizon. ic.warnings holds caveats about the method:

for warning in ic.warnings:
    print(warning)
The reported t-statistic is the ordinary time-series statistic and does not adjust for serial dependence.

Quantile returns ask the same question a different way: do higher signal values sort into higher returns?

quantiles = study.quantiles()
print(quantiles.metrics["mean_top_bottom_spread"], quantiles.metrics["spearman_monotonicity"])
-0.00023478435748410862 -0.9

On this synthetic signal, the top quantile earns less than the bottom one and the ordering runs backwards. The audit will say so. Like ic.metrics, both numbers describe the first declared horizon, 1D. The monotonicity table has one row per horizon, ordered by horizon length, for the others.

Run the audit

audit() computes labels, IC, quantiles, turnover, decay and a bootstrap interval for the IC, then runs every rule against that evidence. The IC checks judge one horizon, the first you declared (1D here) unless you name another with policies={"inference_horizon": "5D"}, and the bootstrap uses only that horizon’s periods whose labels do not overlap.

report = study.audit(bootstrap_resamples=200, seed=42)
print(report.summary())
{'robustness_score': 56.0, 'evidence_coverage': 0.78, 'failure_count': 1, 'warning_count': 2, 'unknown_count': 4, 'not_applicable_count': 1}

The 200 resamples keep the example quick. Use more for real work; the default is 1,000. The seed makes the bootstrap reproducible, and Lacuna records it on the bootstrap evidence, report.evidence["bootstrap"].metadata.seed.

robustness_score runs from 0 to 100. Each rule carries a weight; a PASS earns all of it, a WARN half, and a FAIL or UNKNOWN nothing. NOT_APPLICABLE rules leave the calculation entirely. So missing evidence pulls the score down instead of being ignored. evidence_coverage is the share of the applicable weight that had evidence to assess. Audits and reports explains the weighting.

The findings are where the detail is:

for finding in report.findings:
    print(f"{finding.state:<15} {finding.code}")
PASS            TURNOVER_MEASURED
NOT_APPLICABLE  TRANSACTION_COST_EVIDENCE
UNKNOWN         DELISTING_HANDLING_DECLARED
PASS            PRICE_ADJUSTMENT_DECLARED
UNKNOWN         TRIAL_HISTORY_AVAILABLE
PASS            HORIZON_DECAY_COVERAGE
FAIL            QUANTILE_MONOTONICITY
WARN            BOOTSTRAP_INTERVAL
WARN            IC_PERIOD_SUPPORT
PASS            IC_DEFINED
UNKNOWN         PURGED_VALIDATION_SUPPLIED
UNKNOWN         SURVIVORSHIP_HANDLING_DECLARED
PASS            LABEL_INTERVALS_PRESENT

Read them by state:

  • FAIL: quantile returns run the wrong way, as the spread showed.
  • WARN: the bootstrap interval for the mean 1D IC includes zero, and the 1D IC has 34 defined periods, between the rule’s thresholds of 20 (below which it fails) and 60 (at which it passes).
  • UNKNOWN: four things this study never said. How delisted instruments were handled, whether the universe includes instruments that no longer exist, how many variants were tried before this one, and whether the signal was validated with purged splits. Each one is a question a reviewer would ask. Audits and reports shows how to answer them.
  • NOT_APPLICABLE: transaction costs need trades or a simulated portfolio, and a signal study has neither.

Each finding also carries a title, a message, a severity and the evidence behind it:

finding = next(f for f in report.findings if f.code == "BOOTSTRAP_INTERVAL")
print(finding.message)
print(finding.severity)
The bootstrap confidence interval includes zero.
high

Write the report

path = report.write("lacuna-audit.html")
print(path.name)
lacuna-audit.html

The HTML report is one self-contained file with no scripts or external requests. write picks the format from the extension: .html, .md or .json. JSON is the canonical record; the HTML and Markdown are views of it. write refuses to replace an existing file unless you pass overwrite=True.

The same audit from the command line

The lacuna signal command runs this workflow on files: Parquet, Arrow IPC, Feather or CSV. Parquet and Arrow keep column types. A CSV time column may hold whole-number observation indices or ISO 8601 text (2025-01-02 or 2025-01-02T09:30:00), which the command parses to dates or datetimes. Save the two tables as Parquet:

signal.write_parquet("signal.parquet")
prices.write_parquet("prices.parquet")

Then run the audit, and write a reproducibility bundle alongside the report:

lacuna signal \
  --signal signal.parquet \
  --prices prices.parquet \
  --horizon 1D --horizon 5D --horizon 20D \
  --signal-observed-at open \
  --entry current_close \
  --price-adjustment total_return_adjusted \
  --seed 42 \
  --out audit.html \
  --bundle study.lacuna
lacuna bundle verify study.lacuna

The bundle is a single archive holding the report in each format, the evidence behind it, Lacuna’s runtime settings and a description of the environment. It does not contain your data or your command line, so it identifies a result rather than letting someone re-run it. lacuna bundle verify checks every file in it against the SHA-256 recorded in the archive’s manifest, without running any of your code. That catches corruption and careless edits; it does not prove who made the archive. Reproducibility bundles covers what goes in it.

Add --fail-on fail or --fail-on warn to make the command exit with code 3 when a finding has that state, which turns the audit into a CI gate. Missing evidence never trips it: a study whose only problems are UNKNOWN exits 0, so gate on the unknown_count in the JSON report if that matters to you. The CLI reference lists every option.

Next