Skip to Content

lacuna.adapters

Input normalization, DuckDB, scikit-learn, vendor, factor-panel and backtest adapters.

Generated from Lacuna 0.14.3. For what these do and when to use them, read the guide.

Classes

AdaptedFrame

class AdaptedFrame(frame: PolarsFrame, evidence: AnalysisResult)

A normalized frame together with inspectable adapter evidence.

FieldTypeDefault
framePolarsFramerequired
evidenceAnalysisResultrequired

AdaptedFrame.columns

columns: tuple[str, ...]

Return normalized columns without collecting a lazy frame.

AdaptedFrame.lazy

lazy: bool

Whether the normalized frame remains lazy.

BacktestSchema

class BacktestSchema(
    schema_id: str,
    artifact: BacktestArtifactKind,
    columns: Mapping[str, str],
    semantics: BacktestSemantics,
    schema_version: int = 1,
)

Canonical field mapping for one framework/artifact contract.

FieldTypeDefault
schema_idstrrequired
artifactBacktestArtifactKindrequired
columnsMapping[str, str]required
semanticsBacktestSemanticsrequired
schema_versionint1

BacktestSemantics

class BacktestSemantics(
    returns: Literal['gross', 'net'],
    return_frequency: str,
    compounding: Literal['simple', 'log'],
    position_timing: str,
    execution_delay: str,
    price_field: str,
    price_adjustment: str,
    costs: Literal['included', 'excluded'],
    borrow: Literal['included', 'excluded', 'not_applicable'],
    timezone: str,
    calendar: str,
    session: str,
    missing_instruments: str,
    delistings: str,
)

Backtester assumptions that must accompany imported artifacts.

FieldTypeDefault
returnsLiteral['gross', 'net']required
return_frequencystrrequired
compoundingLiteral['simple', 'log']required
position_timingstrrequired
execution_delaystrrequired
price_fieldstrrequired
price_adjustmentstrrequired
costsLiteral['included', 'excluded']required
borrowLiteral['included', 'excluded', 'not_applicable']required
timezonestrrequired
calendarstrrequired
sessionstrrequired
missing_instrumentsstrrequired
delistingsstrrequired

FactorPanelSchema

class FactorPanelSchema(
    schema_id: str,
    columns: Mapping[str, str],
    semantics: FactorPanelSemantics,
    schema_version: int = 1,
)

Immutable canonical-to-source mapping for a generic factor panel.

FieldTypeDefault
schema_idstrrequired
columnsMapping[str, str]required
semanticsFactorPanelSemanticsrequired
schema_versionint1

FactorPanelSemantics

class FactorPanelSemantics(
    signal_observation: str,
    decision_time_rule: str,
    forward_return_entry: str,
    forward_return_exit: str,
    horizon_clock: str,
    timezone: str,
    calendar: str,
    adjustment_policy: str,
    group_availability: str,
    imported_bucket_definition: str,
)

Research semantics that Lacuna refuses to infer from a factor panel.

FieldTypeDefault
signal_observationstrrequired
decision_time_rulestrrequired
forward_return_entrystrrequired
forward_return_exitstrrequired
horizon_clockstrrequired
timezonestrrequired
calendarstrrequired
adjustment_policystrrequired
group_availabilitystrrequired
imported_bucket_definitionstrrequired

FrameSummary

class FrameSummary(columns: tuple[str, ...], lazy: bool, source_type: str)

Cheap structural information that does not collect a lazy frame.

FieldTypeDefault
columnstuple[str, ...]required
lazyboolrequired
source_typestrrequired

SklearnCV

class SklearnCV(
    splitter: SupportedSplitter,
    data: object,
    *,
    time: str | None = None,
    label_start: str = 'label_start',
    label_end: str = 'label_end',
)

Immutable sklearn-style view over one precomputed Lacuna split result.

Precomputing freezes the row ordering and prevents a mutable interval table from changing folds between estimator evaluations. The class deliberately avoids importing scikit-learn; its split and get_n_splits methods satisfy the public cross-validator protocol.

Fold indices are positions in the rows of data as supplied here. split checks only that X (and y) have the same number of rows; it cannot check their order. The caller must pass X and y in exactly the row order of data, or the folds index the wrong observations and the temporal separation no longer holds.

SklearnCV.evidence

evidence: AnalysisResult

Return the original Lacuna fold evidence.

SklearnCV.split

def split(
    X: object,
    y: object | None = None,
    groups: object | None = None,
) -> Iterator[tuple[IndexArray, IndexArray]]

Yield independent integer index arrays in sklearn’s expected form.

SklearnCV.get_n_splits

def get_n_splits(
    X: object | None = None,
    y: object | None = None,
    groups: object | None = None,
) -> int

Return the frozen fold count after optional shape validation.

VendorSchema

class VendorSchema(
    schema_id: str,
    columns: Mapping[str, str],
    required: tuple[str, ...],
    schema_version: int = 1,
    availability: AvailabilityPolicy = 'unknown',
    revisions: RevisionPolicy = 'unknown',
    timezone: str | None = None,
    timezone_columns: tuple[str, ...] = (),
    price_adjustment: str | None = None,
    identifier_policy: str = 'vendor_native',
)

Explicit mapping and temporal semantics for one vendor dataset version.

FieldTypeDefault
schema_idstrrequired
columnsMapping[str, str]required
requiredtuple[str, ...]required
schema_versionint1
availabilityAvailabilityPolicy'unknown'
revisionsRevisionPolicy'unknown'
timezonestr | NoneNone
timezone_columnstuple[str, ...]()
price_adjustmentstr | NoneNone
identifier_policystr'vendor_native'

Functions

adapt_backtest

def adapt_backtest(
    data: object,
    schema: BacktestSchema,
    *,
    collect: bool = False,
) -> AdaptedFrame

Normalize one backtest artifact while preserving all declared assumptions.

adapt_factor_panel

def adapt_factor_panel(
    data: object,
    schema: FactorPanelSchema,
    *,
    collect: bool = False,
) -> AdaptedFrame

Normalize a factor panel without performing research methodology.

adapt_vendor

def adapt_vendor(
    data: object,
    schema: VendorSchema,
    *,
    collect: bool = False,
) -> AdaptedFrame

Apply a declared vendor mapping without hiding temporal assumptions.

as_sklearn_cv

def as_sklearn_cv(
    splitter: SupportedSplitter,
    data: object,
    *,
    time: str | None = None,
    label_start: str = 'label_start',
    label_end: str = 'label_end',
) -> SklearnCV

Freeze a Lacuna temporal splitter behind sklearn’s CV protocol.

frame_summary

def frame_summary(frame: PolarsFrame) -> FrameSummary

Describe a frame without materializing a lazy query.

from_duckdb

def from_duckdb(
    source: object,
    *,
    batch_size: int = 100000,
    required: Sequence[str] = (),
    collect: bool = True,
) -> AdaptedFrame

Normalize a trusted DuckDB result through its Arrow record-batch reader.

The adapter never accepts or generates SQL. Callers retain responsibility for query construction and parameter binding. The preferred DuckDB API is to_arrow_reader; the legacy fetch_record_batch path is recorded when required for compatibility.

The Arrow stream is always consumed eagerly into a polars.DataFrame; the result is never lazy. collect is kept for signature compatibility and must be True: collect=False raises :class:~lacuna.exceptions.MethodContractError instead of being silently ignored.

require_columns

def require_columns(frame: PolarsFrame, required: Sequence[str]) -> PolarsFrame

Validate required column names without collecting lazy input.

to_polars

def to_polars(
    data: object,
    *,
    schema: Sequence[str] | None = None,
    collect: bool = False,
    include_pandas_index: bool = False,
) -> PolarsFrame

Normalize a supported dataframe-like object to Polars.

Polars inputs stay on the preferred path. Lazy inputs are not materialized unless collect=True. NumPy, pandas, Arrow C Stream producers, mappings, and objects accepted by polars.from_arrow are supported at the edge.

Types and constants

AvailabilityPolicy

AvailabilityPolicy = Literal['point_in_time', 'latest_only', 'unknown']

BacktestArtifactKind

BacktestArtifactKind = Literal['returns', 'trades', 'positions']

PolarsFrame

PolarsFrame = polars.dataframe.frame.DataFrame | polars.lazyframe.frame.LazyFrame

RevisionPolicy

RevisionPolicy = Literal['versioned', 'latest_only', 'not_applicable', 'unknown']

SupportedSplitter

SupportedSplitter = lacuna.cv.WalkForward | lacuna.cv.PurgedKFold | lacuna.cv.CombinatorialPurgedKFold