Skip to Content

Preparing your data

Get pandas, Polars, NumPy, Arrow, DuckDB and vendor or backtest exports into the long-form tables Lacuna reads, and see what Lacuna records about the conversion.

Lacuna reads long-form tables: one row per instrument per observation. Your data rarely arrives that way. Factor research is often stored as a wide pandas frame with dates down the index and tickers across the columns, vendor files use their own column names, and a backtester exports a returns file with its own conventions. The conversion between those shapes is where quiet errors enter a study: a pandas index that is dropped, a date column whose type differs between two tables, a lazy query that runs again for every analysis, a vendor timestamp whose meaning nobody wrote down.

The lc.adapters module makes the conversion explicit. It turns supported containers into Polars frames, renames vendor columns to Lacuna’s names, and records the timing and pricing declarations that come with an export. It does not decide anything about methodology, and it cannot verify a declaration you make. This page covers each piece and ends with what the adapters deliberately leave to you.

A first example: wide pandas frames to long form

Two wide frames, dates by tickers: prices and a signal. to_polars with include_pandas_index=True promotes the named index to a column, and Polars unpivot makes the frame long.

import lacuna as lc
import numpy as np
import pandas as pd
import polars as pl

rng = np.random.default_rng(42)
dates = pd.bdate_range("2025-01-06", periods=40, name="date")
tickers = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"]
daily_returns = rng.normal(0.0003, 0.01, size=(len(dates), len(tickers)))
wide_prices = pd.DataFrame(100 * np.exp(daily_returns.cumsum(axis=0)), index=dates, columns=tickers)
wide_signal = pd.DataFrame(rng.normal(size=wide_prices.shape), index=dates, columns=tickers)


def to_long(wide: pd.DataFrame, value: str) -> pl.DataFrame:
    frame = lc.adapters.to_polars(wide, include_pandas_index=True)
    return frame.unpivot(index="date", variable_name="instrument", value_name=value).rename(
        {"date": "time"}
    )


prices = to_long(wide_prices, "close")
signal = to_long(wide_signal, "signal")
print(prices.head(3))
shape: (3, 3)
┌─────────────────────┬────────────┬────────────┐
│ time                ┆ instrument ┆ close      │
│ ---                 ┆ ---        ┆ ---        │
│ datetime[μs]        ┆ str        ┆ f64        │
╞═════════════════════╪════════════╪════════════╡
│ 2025-01-06 00:00:00 ┆ AAA        ┆ 100.335278 │
│ 2025-01-07 00:00:00 ┆ AAA        ┆ 100.493773 │
│ 2025-01-08 00:00:00 ┆ AAA        ┆ 100.590324 │
└─────────────────────┴────────────┴────────────┘

By default the pandas index is dropped, because Lacuna works with columns and will not guess which index levels matter. Without the flag the dates would vanish:

print(lc.adapters.to_polars(wide_prices).columns)
['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF']

The two long tables now match the defaults a SignalStudy expects: time, instrument, close and signal.

study = lc.SignalStudy(
    signal=signal,
    prices=prices,
    horizons=("1D", "5D"),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
)
ic = study.ic()
print(pl.DataFrame(ic.table("ic_by_horizon")).select("horizon", "mean_ic", "n_periods"))
shape: (2, 3)
┌─────────┬───────────┬───────────┐
│ horizon ┆ mean_ic   ┆ n_periods │
│ ---     ┆ ---       ┆ ---       │
│ str     ┆ f64       ┆ i64       │
╞═════════╪═══════════╪═══════════╡
│ 1D      ┆ 0.037363  ┆ 39        │
│ 5D      ┆ -0.066122 ┆ 35        │
└─────────┴───────────┴───────────┘

The signal here is random noise, so the mean IC is near zero. The point is the path: wide pandas in, long Polars out, an audited number at the end.

What Lacuna accepts

lc.adapters.to_polars is the normalizer behind the functions that read frames, such as those in lc.labels, lc.signal, lc.cv, lc.events, lc.bias, lc.costs and lc.regime. It accepts:

InputWhat happensCopy recorded
Polars DataFrameUsed as is.zero_copy
Polars LazyFrameKept lazy by to_polars and the adapters. Analytical functions collect it.potentially_zero_copy, then materializing when collected
Polars SeriesBecomes a one-column frame.zero_copy
pandas DataFrame or SeriesConverted with polars.from_pandas. The index is dropped unless you ask for it. NaN becomes null; this is the only input where it does.one_copy
NumPy arrayOne-dimensional becomes a single column named value, or the one name in schema. Two-dimensional needs schema with one name per column. NaN stays NaN.potentially_zero_copy
Mapping of columnspolars.DataFrame(mapping). NaN stays NaN.one_copy
Arrow tables and streamsAnything with __arrow_c_stream__, such as a pyarrow.Table, or anything polars.from_arrow accepts.potentially_zero_copy

Anything else, including a plain Python list of values or a list of dicts, raises a DataContractError. A few methods that take plain series are the exception: the return-series and permutation methods in lc.validation accept a plain sequence or a one-dimensional array, and lc.signal.ic accepts two aligned one-dimensional NumPy arrays of signal and return values.

ParameterMeaning
dataThe object to normalize.
schemaColumn names for NumPy input. Required for a two-dimensional array; optional for a one-dimensional one. Ignored for every other input type.
collectWhen True, a lazy input is collected and an eager frame returned. The default leaves a LazyFrame lazy.
include_pandas_indexWhen True, the pandas index (every level of a MultiIndex) becomes columns. Leave it False when the index is a meaningless row counter.

A NumPy array has one dtype, so a two-dimensional array cannot hold a string ticker next to a float price. Instrument identifiers in a NumPy array arrive as floats; Lacuna accepts floats only when they are whole numbers. For mixed columns, use a mapping or a Polars frame.

frame = lc.adapters.to_polars(np.arange(6.0).reshape(3, 2), schema=("time", "close"))
print(frame.columns)
['time', 'close']

A two-dimensional array without names raises:

lc.adapters.to_polars(np.zeros((2, 2)))
DataContractError: two-dimensional NumPy input requires an explicit schema

Names, keys and what Lacuna checks

Lacuna’s default column names are time, instrument, close for prices and signal for a signal. Labels use observation_time and forward_return. Most functions that read a table take the column names as parameters, so you can often leave your columns as they are. The analysis functions always drop a pandas index, so call reset_index() first or go through to_polars(..., include_pandas_index=True). If your identifier column has another name, pass it as instrument=, for example to SignalStudy; the labels and bucket frames that Lacuna produces always carry it under the canonical name instrument, and the later steps read it from there.

At the boundary Lacuna rejects what would make a result ambiguous rather than repairing it:

ConditionResult
A required column is missingDataContractError: missing required columns: ...
A null in the time or instrument columnDataContractError, with the count per column
An empty frameDataContractError: the frame must contain at least one row
Two rows with the same time and instrumentDataContractError; row order is never a tie-breaker
A time column that is not Date, Datetime, Duration or a whole-number index (for example a string)DataContractError
An instrument column that is not string, categorical, enum or integer (whole-number floats are accepted)DataContractError
Time or instrument dtypes that differ between two tables that must be joinedDataContractError naming both dtypes
In forward_returns: an infinite price, or an entry or exit price that is zero or negativeDataContractError

Duplicates are the case worth seeing. Resolve them before the call, for example by keeping the last revision, because Lacuna will not choose for you.

lc.labels.forward_returns(pl.concat([prices, prices.head(1)]), horizon="1D")
DataContractError: prices contains 2 duplicate rows for logical key (time, instrument)

Matching dtypes matter more often than people expect. A date column in one table and a datetime column in the other describe the same sessions but are different types, and Lacuna refuses to join them. Converting a Polars frame with to_pandas() turns a Date column into a datetime64 column, so a round trip through pandas is a common cause. Cast one side so both match:

mismatched = lc.SignalStudy(
    signal=signal.with_columns(pl.col("time").cast(pl.Datetime("us"))),
    prices=prices.with_columns(pl.col("time").cast(pl.Date)),
    horizons=("1D",),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
)
mismatched.ic()
DataContractError: aligned semantic keys must use matching dtypes: time=Datetime(time_unit='us', time_zone=None) vs observation_time=Date

Row order in the input does not matter to forward_returns: it sorts by instrument and time internally and records that step. It does not fill gaps. A null price keeps its place in the sequence as an observation with no price, and a label whose entry or exit lands on it is dropped and counted rather than bridged (under the default missing="drop"; missing="raise" raises instead when a source price is null or NaN, other than a null exit price on a row with a delisting return, or a label has entry and exit observations but no defined return, and it accepts the unavoidable labels at the end of each instrument’s history that have no exit). If you drop null rows before you pass the table, you change which observation a horizon lands on, because horizons count observations. Forward-return labels explains this.

Lazy frames and when Lacuna collects

A Polars LazyFrame passes through to_polars and every adapter without running. Analytical functions are different: they need the numbers, so they collect the plan, and they record that they did.

A SignalStudy keeps the lazy plans you give it. It builds the labels from the prices once and caches them, so the price plan runs once. The signal plan runs again for each method that reads the signal. A plan that reads a large file or runs a heavy query pays that cost every time. Count the executions with a function that counts its calls:

runs = []


def count_run(frame: pl.DataFrame) -> pl.DataFrame:
    runs.append(frame.height)
    return frame


lazy_study = lc.SignalStudy(
    signal=signal.lazy().map_batches(count_run),
    prices=prices,
    horizons=("1D",),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
)
print("after construction:", len(runs))
lazy_study.ic()
lazy_study.quantiles()
print("after ic and quantiles:", len(runs))
after construction: 0
after ic and quantiles: 2

Nothing ran at construction, and the signal plan ran once per method. Collect once yourself when the plan is expensive, then pass the eager frame:

eager_signal = lc.adapters.to_polars(signal.lazy().map_batches(count_run), collect=True)
print(type(eager_signal).__name__)
DataFrame

Lacuna collects the plan exactly as you wrote it. It does not push column selections or filters into it, so select the columns and rows you need before you hand the frame over.

Input provenance

The results of those functions record what happened to each frame in their metadata. For forward_returns the record is under input:

labels = lc.labels.forward_returns(
    prices.lazy(), horizon="1D", price_adjustment="total_return_adjusted"
)
record = labels.metadata.parameters["input"]
for key in ("source_type", "lazy_input", "materialized", "adapter_copy", "materialization_reason"):
    print(f"{key}: {record[key]}")
source_type: polars.LazyFrame
lazy_input: True
materialized: True
adapter_copy: materializing
materialization_reason: domain method requires an eager frame

The same record for the other inputs shows how each container was brought in:

FieldMeaning
source_typeThe container you passed, such as polars.DataFrame, polars.LazyFrame or pandas.DataFrame. The adapters’ own evidence (vendor, backtest, factor panel, DuckDB) records the same spelling.
rows, columnsShape of the frame the method actually used.
lazy_inputWhether you passed a lazy frame.
materializedWhether Lacuna had to collect a lazy plan.
materialization_reasonWhy, when it did.
adapter_copyzero_copy, potentially_zero_copy, one_copy or materializing. Whether an Arrow or NumPy buffer is truly shared depends on the producer; Lacuna labels the best case it can reach.
adapter_operationsThe conversion steps, such as pandas_to_polars.
execution_operationsThe result-affecting steps the method applied, such as sort(instrument,time).

Methods that read two tables record two entries under their own names. lc.signal.ic stores signal_input and label_input, lc.bias.asof_join stores left_frame and right_frame, and lc.events.event_windows stores event_input and price_input.

ic = lc.signal.ic(signal, labels.frame)
print(sorted(key for key in ic.metadata.parameters if key.endswith("_input")))
['label_input', 'signal_input']

Checking columns without collecting

require_columns and frame_summary look at a frame’s structure without running a lazy plan, which makes them cheap guards at the top of your own functions.

summary = lc.adapters.frame_summary(prices.lazy())
print(summary)
FrameSummary(columns=('time', 'instrument', 'close'), lazy=True, source_type='polars.LazyFrame')

require_columns returns the frame unchanged, or raises with every missing name:

lc.adapters.require_columns(prices.lazy(), ["time", "close", "volume", "bid"])
DataContractError: missing required columns: bid, volume

DuckDB

lc.adapters.from_duckdb reads a DuckDB result through its Arrow record-batch reader, so rows do not pass through pandas. Install the extra for DuckDB and PyArrow:

pip install "lacuna-quant[duckdb]"

Lacuna never imports DuckDB for this: the adapter works with any executed relation or connection that exposes to_arrow_reader(), and falls back to the older fetch_record_batch when that is missing, recording which it used. It does not accept SQL text and never builds any, so quoting and parameter binding are yours. Treat the connection as trusted code running in your process.

import duckdb

con = duckdb.connect()
con.register("prices", prices.to_arrow())
relation = con.sql(
    "SELECT time, instrument, CAST(close AS DOUBLE) AS close "
    "FROM prices WHERE instrument <> 'FFF' ORDER BY instrument, time"
)
adapted = lc.adapters.from_duckdb(relation, required=("time", "instrument", "close"))
print(adapted.columns)
print(adapted.evidence.metrics["row_count"])
print(adapted.evidence.metadata.parameters["reader_method"])
print(adapted.evidence.metadata.parameters["sql_generated"])
('time', 'instrument', 'close')
200
to_arrow_reader
False

Three details matter in practice. Cast DECIMAL columns to DOUBLE in the query, because DuckDB decimals arrive as Polars decimals rather than floats. Pass the relation from con.sql(...) instead of the result of con.execute(...): DuckDB copies rows on the DB-API path and warns about it. A bare connection stands for whatever statement ran last, so a fresh one raises DataContractError, and one whose last statement returned no rows gives an empty or meaningless frame unless you pass required; hand over the relation instead. And the result is an AdaptedFrame, not a table: pass adapted.frame to the analysis functions, not adapted.

ParameterMeaning
sourceAn executed DuckDB relation or connection.
batch_sizeRows per Arrow record batch. Positive integer; the default suits most results.
requiredColumn names that must be present. A missing one raises DataContractError.
collectMust stay True, the default. The Arrow stream is always read into an eager Polars DataFrame, so collect=False raises MethodContractError. The evidence records materialized.

Every adapt_* and from_* function returns an AdaptedFrame (to_polars, require_columns and frame_summary return frames or summaries) with two fields, frame (the Polars frame) and evidence (an AnalysisResult describing the conversion), and two properties, columns and lazy.

Vendor schemas

A vendor dataset comes with its own names and its own timing conventions. A VendorSchema states the mapping from Lacuna’s canonical names to the vendor’s columns, and the temporal facts about the dataset, in one versioned, immutable object. adapt_vendor applies it.

The example is a fundamentals export. The vendor records when each figure was published and when each restatement was made, in UTC, under its own column names. The file is written first, then scanned lazily.

from pathlib import Path

Path("fundamentals.csv").write_text(
    "SEC_ID,PERIOD_END,PUBLISHED_AT,REVISED_AT,EPS\n"
    "US0001,2024-12-31,2025-02-14T21:30:00+00:00,2025-02-14T21:30:00+00:00,1.10\n"
    "US0001,2024-12-31,2025-02-14T21:30:00+00:00,2025-04-02T13:00:00+00:00,1.04\n"
    "US0002,2024-12-31,2025-02-20T12:00:00+00:00,2025-02-20T12:00:00+00:00,0.52\n"
)
raw = pl.scan_csv("fundamentals.csv").with_columns(
    pl.col("PERIOD_END").str.to_date(),
    pl.col("PUBLISHED_AT").str.to_datetime(time_zone="UTC"),
    pl.col("REVISED_AT").str.to_datetime(time_zone="UTC"),
)

fundamentals_schema = lc.adapters.VendorSchema(
    schema_id="acme-fundamentals",
    schema_version=2,
    columns={
        "instrument": "SEC_ID",
        "effective_time": "PERIOD_END",
        "available_time": "PUBLISHED_AT",
        "revision_time": "REVISED_AT",
        "eps": "EPS",
    },
    required=("instrument", "available_time", "eps"),
    availability="point_in_time",
    revisions="versioned",
    timezone="UTC",
    timezone_columns=("available_time", "revision_time"),
)
fundamentals = lc.adapters.adapt_vendor(raw, fundamentals_schema)
print(fundamentals.lazy, fundamentals.columns)
print(fundamentals.frame.collect().select("instrument", "available_time", "revision_time", "eps"))
True ('instrument', 'effective_time', 'available_time', 'revision_time', 'eps')
shape: (3, 4)
┌────────────┬─────────────────────────┬─────────────────────────┬──────┐
│ instrument ┆ available_time          ┆ revision_time           ┆ eps  │
│ ---        ┆ ---                     ┆ ---                     ┆ ---  │
│ str        ┆ datetime[μs, UTC]       ┆ datetime[μs, UTC]       ┆ f64  │
╞════════════╪═════════════════════════╪═════════════════════════╪══════╡
│ US0001     ┆ 2025-02-14 21:30:00 UTC ┆ 2025-02-14 21:30:00 UTC ┆ 1.1  │
│ US0001     ┆ 2025-02-14 21:30:00 UTC ┆ 2025-04-02 13:00:00 UTC ┆ 1.04 │
│ US0002     ┆ 2025-02-20 12:00:00 UTC ┆ 2025-02-20 12:00:00 UTC ┆ 0.52 │
└────────────┴─────────────────────────┴─────────────────────────┴──────┘

The adapter renamed five columns and left the frame lazy. It checked that every column in required exists and that the two columns listed in timezone_columns are timezone-aware and in UTC. Nothing else about the data was examined. Columns the schema does not mention pass through unchanged, and a mapped column that is not listed in required may be absent from the data. The adapter skips it and records its canonical name in the evidence parameter absent_optional_columns, so a schema can describe a vendor’s full export while a given file carries only some of it.

The evidence records the declaration and the mapping:

parameters = fundamentals.evidence.metadata.parameters
print(parameters["schema_id"], parameters["schema_version"])
print(parameters["availability"], parameters["revisions"], parameters["timezone"])
print(fundamentals.evidence.metrics)
print(fundamentals.evidence.warnings[0])
acme-fundamentals 2
point_in_time versioned UTC
{'source_column_count': 5, 'normalized_column_count': 5, 'row_count': None}
Vendor timestamps and archive completeness are declarations supplied by the caller; Lacuna does not independently certify them.

row_count is None because the frame is lazy and counting rows would run it. Pass collect=True to get an eager frame and a row count.

The warning is always attached. A schema that leaves availability or revisions at unknown produces no finding of its own, so the gap is visible only in the recorded parameters.

A timestamp in the wrong zone is caught, because the zone is part of the column’s type:

new_york = raw.with_columns(pl.col("PUBLISHED_AT").dt.convert_time_zone("America/New_York"))
lc.adapters.adapt_vendor(new_york, fundamentals_schema)
DataContractError: vendor timestamp column 'available_time' uses timezone 'America/New_York', expected 'UTC'
FieldMeaning
schema_idA name for this dataset’s mapping, recorded in evidence.
columnsCanonical name to vendor column. Each vendor column may be used once. Copied and frozen at construction.
requiredA tuple of canonical names that must be present in the data. Each must also appear in columns. A list raises MethodContractError.
schema_versionPositive integer. Raise it when you change the mapping, so older evidence stays interpretable.
availabilityWhat the vendor’s timestamps mean. See below.
revisionsHow the vendor handles restatements. See below.
timezoneThe zone the timezone_columns are expected to use. Compared as a plain string with each column’s zone, so "Etc/UTC" does not match "UTC". Columns not listed in timezone_columns are never checked.
timezone_columnsA tuple of canonical names of the timestamp columns to check. Each must be timezone-aware, and equal to timezone when one is given; without timezone, only timezone-awareness is checked. Each must also appear in columns.
price_adjustmentFree text, recorded and not checked.
identifier_policyFree text, vendor_native by default. Record how the vendor’s identifiers map to a stable instrument key.

AvailabilityPolicy and RevisionPolicy are type aliases for the allowed strings, not classes. The glosses below say what each value is meant to declare. Lacuna attaches no behaviour to them beyond the two mapping checks described afterwards; they are recorded in the evidence for readers and reports.

availabilityDeclares
point_in_timeEach row carries the time it first became knowable. The schema must map available_time.
latest_onlyThe vendor serves only the current state of the data; history is restated.
unknownNot established. This is the default.
revisionsDeclares
versionedRestatements are kept as separate rows. The schema must map revision_time or revision_id.
latest_onlyOnly the latest revision is available.
not_applicableThe dataset is never revised.
unknownNot established. This is the default.

The constructor checks the declarations against each other, so a point_in_time schema without an available_time mapping fails when you build it, not when you analyse.

for caption, parameters in (
    ("availability", {"availability": "point_in_time"}),
    ("revisions", {"revisions": "versioned"}),
):
    try:
        lc.adapters.VendorSchema(
            schema_id="incomplete",
            columns={"instrument": "SEC_ID", "eps": "EPS"},
            required=("instrument",),
            **parameters,
        )
    except lc.MethodContractError as error:
        print(f"{caption}: {error}")
availability: point_in_time vendor schemas must map the canonical available_time column
revisions: versioned vendor schemas must map revision_time or revision_id

The same two declarations are checked against the data. A mapped column that is not in required may be absent from the file, and the adapter then skips it. It does not skip a column the declaration depends on: a point_in_time schema whose available_time source column is missing, or a versioned schema whose every mapped revision source column is missing, raises DataContractError, because point-in-time safety or the revision history cannot be established without it. In the example below available_time is not in required, so the check that catches its absence is the declaration check:

lenient_schema = lc.adapters.VendorSchema(
    schema_id="acme-fundamentals-lenient",
    columns=fundamentals_schema.columns,
    required=("instrument", "eps"),
    availability="point_in_time",
    revisions="versioned",
    timezone="UTC",
)
without_period = lc.adapters.adapt_vendor(raw.drop("PERIOD_END"), lenient_schema)
print(without_period.evidence.metadata.parameters["absent_optional_columns"])
('effective_time',)
lc.adapters.adapt_vendor(raw.drop("PUBLISHED_AT"), lenient_schema)
DataContractError: point_in_time vendor schema maps available_time to 'PUBLISHED_AT', but that source column is absent; point-in-time safety cannot be established without it
ParameterMeaning
dataThe vendor table: a Polars frame (eager or lazy), pandas, Arrow or a mapping. A pandas index is not promoted to a column; call reset_index() first.
schemaThe VendorSchema to apply.
collectWhen True, collect a lazy input and return an eager frame with a row count in the evidence.

availability="point_in_time" is a statement about the vendor, not a result. Lacuna records it and attaches a warning that vendor timestamps and archive completeness are your declarations. Whether available_time really is the first moment the figure was public is something neither this adapter nor the point-in-time functions can check: they use the column as you give it. Point-in-time data tests what follows from it, such as whether a record used at a decision had become available by then.

Factor panels

A factor panel is the shape most factor-research tools produce: one row per date and asset, with a signal, often forward returns for several horizons, and sometimes a group. adapt_factor_panel maps such a table to Lacuna’s names and, unlike the vendor adapter, requires you to describe the research conventions behind it.

The example is a pandas frame with a (date, asset) MultiIndex, a factor column, a one-day forward return in a column named 1D, and a sector group.

panel_index = pd.MultiIndex.from_product([dates, tickers], names=["date", "asset"])
legacy = pd.DataFrame(
    {
        "factor": rng.normal(size=len(panel_index)),
        "1D": rng.normal(0.0, 0.02, size=len(panel_index)),
        "group": [
            "tech" if ticker in ("AAA", "BBB", "CCC") else "other" for _, ticker in panel_index
        ],
    },
    index=panel_index,
)

semantics = lc.adapters.FactorPanelSemantics(
    signal_observation="close of session t",
    decision_time_rule="first tradable open after the observation",
    forward_return_entry="next session open",
    forward_return_exit="close of the next session",
    horizon_clock="trading observations",
    timezone="America/New_York",
    calendar="XNYS",
    adjustment_policy="unknown",
    group_availability="unknown",
    imported_bucket_definition="none imported",
)
panel_schema = lc.adapters.FactorPanelSchema(
    schema_id="legacy-factor-data",
    columns={
        "observation_time": "date",
        "instrument": "asset",
        "signal": "factor",
        "forward_return": "1D",
        "group": "group",
    },
    semantics=semantics,
)
panel = lc.adapters.adapt_factor_panel(legacy, panel_schema)
print(panel.frame.head(3))
print(panel.evidence.metrics)
shape: (3, 5)
┌─────────────────────┬────────────┬──────────┬────────────────┬───────┐
│ observation_time    ┆ instrument ┆ signal   ┆ forward_return ┆ group │
│ ---                 ┆ ---        ┆ ---      ┆ ---            ┆ ---   │
│ datetime[μs]        ┆ str        ┆ f64      ┆ f64            ┆ str   │
╞═════════════════════╪════════════╪══════════╪════════════════╪═══════╡
│ 2025-01-06 00:00:00 ┆ AAA        ┆ 0.22308  ┆ -0.001924      ┆ tech  │
│ 2025-01-06 00:00:00 ┆ BBB        ┆ 1.433215 ┆ 0.02256        ┆ tech  │
│ 2025-01-06 00:00:00 ┆ CCC        ┆ 0.09152  ┆ -0.045615      ┆ tech  │
└─────────────────────┴────────────┴──────────┴────────────────┴───────┘
{'source_column_count': 5, 'normalized_column_count': 5, 'row_count': 240, 'unknown_semantics': 2}

The named index levels date and asset became the columns observation_time and instrument, because the schema’s source names matched them. When the schema maps at least one named index level, the adapter promotes every named level of the pandas index to a column; it renames and records only the levels the schema maps, and an unnamed level is never promoted. If the index names do not match, it raises DataContractError listing the missing columns, so a MultiIndex without names is never guessed at. It keeps every other column and the original row order, and it runs no methodology: no sorting, filtering, joining, bucketing or return construction.

FieldMeaning
schema_idA name for this mapping, recorded in evidence.
columnsCanonical name to source column or index level. observation_time, instrument and signal are required. forward_return, horizon, group, bucket, available_time, entry_time and label_end are optional. Any other canonical name is rejected.
semanticsA FactorPanelSemantics describing the research conventions.
schema_versionPositive integer, recorded in evidence.

A mapped optional column that the data does not carry is skipped and listed under absent_optional_columns in the evidence parameters; a missing observation_time, instrument or signal raises DataContractError. The adapter checks that signal and forward_return are numeric and that bucket is an integer. An imported bucket is kept as a column; Lacuna does not treat it as though BucketSpec had produced it. For Lacuna’s own bucketing, and the attrition evidence that comes with it, bucket the signal column again.

The ten fields of FactorPanelSemantics are all required, non-empty strings. They are what the table leaves out and Lacuna refuses to infer:

FieldWhat to state
signal_observationWhen in the session the signal value is known.
decision_time_ruleThe earliest time a decision may use it.
forward_return_entry, forward_return_exitThe prices the imported return starts and ends at.
horizon_clockWhat one unit of horizon counts: trading observations, calendar days.
timezone, calendarThe zone and the exchange calendar behind the timestamps.
adjustment_policyWhat the prices include: splits, dividends.
group_availabilityWhen group labels, such as sectors, became known.
imported_bucket_definitionHow an imported bucket column was built, or that none was.

Write "unknown" when you do not know (the match ignores case). The adapter records one UNKNOWN finding that lists every field you left as "unknown", instead of letting the gap pass quietly. In this example two fields are unknown:

for finding in panel.evidence.findings:
    print(finding.code, finding.state.value, finding.severity.value)
    print(finding.evidence["unknown_fields"])
FACTOR_PANEL_SEMANTICS_UNKNOWN UNKNOWN medium
('adjustment_policy', 'group_availability')

Pass panel.frame to the analysis functions with the canonical names:

panel_ic = lc.signal.ic(
    panel.frame,
    panel.frame,
    signal_time="observation_time",
    label_time="observation_time",
    min_observations=3,
)
print(round(panel_ic.metrics["mean_ic"], 4), panel_ic.metrics["n_periods"])
0.0614 40

An imported return column carries no entry or exit times, so nothing downstream can verify how the returns were built, and the semantics you wrote are only your word. If your source has the times, you can map them as entry_time and label_end, but that alone does not make the panel usable as labels. lc.signal.ic wants interval columns label_start and label_end together and raises DataContractError: ... missing columns: label_start otherwise. The schema has no mapping for label_start, so add that column yourself, with the same dtype as observation_time, label_start before label_end, and entry_time between them.

ParameterMeaning
datapandas, Polars (eager or lazy) or Arrow input.
schemaThe FactorPanelSchema.
collectWhen True, a lazy input is collected. pandas and Arrow input always become an eager frame.

Backtest artifacts

A backtester’s export is meaningless without its conventions. A column named return could be gross or net of costs, daily or monthly, simple or log. adapt_backtest takes one of three artifact kinds and requires the conventions to travel with it.

artifactRequired canonical columns
returnstime, strategy, return
tradesdecision_time, execution_time, instrument, side, quantity, price
positionstime, instrument, position

BacktestArtifactKind is the type alias for those three strings. The trade columns are the names lc.costs.TradeColumns uses by default.

BacktestSemantics has fourteen fields. Four are constrained to a fixed set of values; the rest are non-empty free text.

FieldValues
returnsgross or net
compoundingsimple or log
costsincluded or excluded
borrowincluded, excluded or not_applicable
return_frequency, position_timing, execution_delay, price_field, price_adjustment, timezone, calendar, session, missing_instruments, delistingsFree text. Empty is rejected.
rng = np.random.default_rng(5)
export = pd.DataFrame(
    {
        "Date": pd.bdate_range("2024-01-02", periods=250),
        "Strategy": "momentum",
        "Daily P&L pct": rng.normal(0.0004, 0.01, size=250),
    }
)
backtest_semantics = lc.adapters.BacktestSemantics(
    returns="net",
    return_frequency="daily",
    compounding="simple",
    position_timing="positions held from the open",
    execution_delay="one session",
    price_field="close",
    price_adjustment="total_return_adjusted",
    costs="included",
    borrow="excluded",
    timezone="America/New_York",
    calendar="XNYS",
    session="regular",
    missing_instruments="dropped",
    delistings="not modelled",
)
backtest_schema = lc.adapters.BacktestSchema(
    schema_id="acme-backtester-returns",
    artifact="returns",
    columns={"time": "Date", "strategy": "Strategy", "return": "Daily P&L pct"},
    semantics=backtest_semantics,
)
returns = lc.adapters.adapt_backtest(export, backtest_schema)
print(returns.frame.head(2))
print(returns.evidence.metadata.parameters["semantics"]["costs"])
shape: (2, 3)
┌─────────────────────┬──────────┬───────────┐
│ time                ┆ strategy ┆ return    │
│ ---                 ┆ ---      ┆ ---       │
│ datetime[μs]        ┆ str      ┆ f64       │
╞═════════════════════╪══════════╪═══════════╡
│ 2024-01-02 00:00:00 ┆ momentum ┆ -0.007619 │
│ 2024-01-03 00:00:00 ┆ momentum ┆ -0.012844 │
└─────────────────────┴──────────┴───────────┘
included

The adapted frame feeds the return-series methods. sharpe_inference reads one column, so give it one strategy at a time:

momentum = returns.frame.filter(pl.col("strategy") == "momentum")
sharpe = lc.validation.sharpe_inference(momentum, value="return", annualization=252.0)
print(round(sharpe.metrics["observed_sharpe"], 3), sharpe.metrics["n_effective"])
-0.031 250

The annualization factor and the daily frequency are yours to keep consistent. The adapter stores return_frequency as text and does not check it against the annualization you pass later.

FieldMeaning
schema_idA name for this exporter’s mapping, recorded in evidence.
artifactreturns, trades or positions.
columnsCanonical name to the exporter’s column. Each exporter column may be used once. The artifact’s required canonical names must all be mapped.
semanticsThe BacktestSemantics that accompany the export.
schema_versionPositive integer, recorded in evidence.
ParameterMeaning
dataThe exported table: pandas, Polars, Arrow or a mapping. A pandas index is not promoted to a column; call reset_index() first.
schemaThe BacktestSchema to apply.
collectWhen True, a lazy input is collected.

A mapped column outside the artifact’s required set may be absent from the export; it is skipped and listed under absent_optional_columns. The backtest adapter does not turn "unknown" into a finding, and unlike the vendor and factor-panel adapters it attaches no warning at all, though it records methodology_executed as False. It rejects empty strings and unsupported values for the four fixed fields, and that is all; the evidence carries your declarations and nothing flags a vague one. If a convention is unknown to you, say so in the text and say so in the report you write.

Passing adapter evidence to an audit

Each adapter’s evidence is an ordinary AnalysisResult. Nothing reads it unless you hand it over. The standard audit, lc.standard_audit, has an optional adapter_provenance capability that recognises results from the adapters, and an optional plugin_provenance one for plugins.

report = lc.standard_audit(
    results={"fundamentals_import": fundamentals.evidence}, scope="signal"
)
for finding in report.findings:
    if finding.code == "EVIDENCE_ADAPTER_PROVENANCE":
        print(finding.state.value, finding.evidence["coverage_only"])
PASS True

The PASS is coverage only. It says evidence of that kind was supplied. It does not say the vendor’s timestamps are right or that the study is point-in-time safe. SignalStudy.audit also takes additional_evidence, and the evidence then travels inside the report, but none of the study’s own rules reads it; see Audits and reports.

What the adapters do not do

The adapters translate shape and record declarations. They do not decide or verify anything about the research.

  • They do not certify what you declare. availability, revisions, price_adjustment, the factor-panel semantics and the backtest semantics are recorded as given. The one structural check, timezone-aware timestamp columns, tests the column’s type and nothing more.
  • They do not sort, filter, join, deduplicate, fill, bucket, build returns or compute statistics. The factor-panel adapter says so in its evidence: methodology_executed is False and row_order_preserved is True. The vendor and backtest adapters rename columns and nothing else.
  • They do not infer an index, a calendar, a time zone or a horizon from the data.
  • They do not turn a latest-snapshot dataset into a point-in-time one. A table that was restated in place stays that way, whatever its schema says.
  • They do not silently overwrite columns. A rename that would collide with an existing column raises DataContractError. That includes a skipped optional mapping: if the data has a column already named like the canonical target (a group column when the schema maps group to an absent grp), the adapter refuses rather than mistake it for the mapped field.

The checks that test records against the availability times you supply live in Point-in-time data. How these tables become labels, and how horizons and entry timing are declared, is in Forward-return labels. For time, identity and missing-data conventions across the library, see Time and data.

For every signature, see the lacuna.adapters API reference.