Skip to Content

lacuna

The package root: results, findings, configuration, errors and the study workflow.

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

The root re-exports the names below for everyday use. It also exposes these modules, each with its own page: lacuna.adapters, lacuna.audit, lacuna.bias, lacuna.bundle, lacuna.costs, lacuna.cv, lacuna.diagnostics, lacuna.events, lacuna.experiment, lacuna.labels, lacuna.plugins, lacuna.regime, lacuna.robustness, lacuna.signal, lacuna.validation.

Also available at the root, documented on their module’s page:

Applicability, ApplicabilityState, AuditContext, AuditProfile, AuditReport, AuditRule, AuditScope, BenchmarkCase, BenchmarkConfig, BenchmarkSuite, BundleArtifact, BundleManifest, BundleVerification, DiagnosticCheck, DiagnosticState, EventWindowResult, EvidenceDisposition, EvidenceRequirement, ExperimentRegistry, InstallationDiagnostics, LabelResult, benchmark_config_for_tier, create_bundle, default_rules, diagnose_installation, run_audit, run_benchmarks, run_standard_audit, standard_audit, standard_profile, verify_bundle.

Classes

AnalysisResult

class AnalysisResult(
    metadata: ResultMetadata,
    metrics: Mapping[str, JsonValue] = {},
    findings: tuple[Finding, ...] = (),
    tables: Mapping[str, JsonValue] = {},
    warnings: tuple[str, ...] = (),
    schema_version: str = '1',
)

Versioned structured output shared by future analysis modules.

FieldTypeDefault
metadataResultMetadatarequired
metricsMapping[str, JsonValue]{}
findingstuple[Finding, ...]()
tablesMapping[str, JsonValue]{}
warningstuple[str, ...]()
schema_versionstr'1'

AnalysisResult.to_dict

def to_dict() -> dict[str, object]

Return a JSON-compatible representation.

AnalysisResult.table

def table(name: str) -> object

Return the thawed source data for a named result table.

AnalysisResult.to_json

def to_json(*, indent: int | None = 2) -> str

Serialize the result without unsafe Python object serialization.

AnalysisResult.from_dict

@classmethod
def from_dict(cls, value: Mapping[str, object]) -> AnalysisResult

Parse the strict supported v1 result envelope without executing content.

AnalysisResult.from_json

@classmethod
def from_json(cls, value: str) -> AnalysisResult

Parse strict finite JSON with duplicate-key rejection into a v1 result.

BucketSpec

class BucketSpec(
    kind: BucketKind,
    count: int | None = None,
    boundaries: tuple[float, ...] = (),
    tie_policy: TiePolicy = 'balanced',
    split_at: float | None = None,
    equal_to: EqualToPolicy = 'upper',
    out_of_range: OutOfRangePolicy = 'raise',
)

Validated, immutable signal-bucket assignment policy.

FieldTypeDefault
kindBucketKindrequired
countint | NoneNone
boundariestuple[float, ...]()
tie_policyTiePolicy'balanced'
split_atfloat | NoneNone
equal_toEqualToPolicy'upper'
out_of_rangeOutOfRangePolicy'raise'

BucketSpec.quantiles

@classmethod
def quantiles(
    cls,
    count: int = 10,
    *,
    edges: Sequence[float] | None = None,
    tie_policy: TiePolicy = 'balanced',
    split_at: float | None = None,
    equal_to: EqualToPolicy = 'upper',
) -> BucketSpec

Create count- or probability-edge-based quantile buckets.

BucketSpec.equal_width

@classmethod
def equal_width(cls, count: int) -> BucketSpec

Create equal-width buckets within each declared group.

BucketSpec.edges

@classmethod
def edges(
    cls,
    edges: Sequence[float],
    *,
    out_of_range: OutOfRangePolicy = 'raise',
) -> BucketSpec

Create fixed numeric-edge buckets.

BucketSpec.threshold

@classmethod
def threshold(
    cls,
    value: float,
    *,
    equal_to: EqualToPolicy = 'upper',
) -> BucketSpec

Create two buckets separated by one explicit threshold.

BucketSpec.to_parameters

def to_parameters() -> Mapping[str, JsonValue]

Return the canonical result-affecting bucket policy.

Config

class Config(
    threads: ThreadCount = 'auto',
    seed: int | None = None,
    memory_limit: str | None = None,
    cache_dir: str | None = None,
    log_level: str = 'warning',
)

Runtime settings that affect execution and reproducibility.

FieldTypeDefault
threadsThreadCount'auto'
seedint | NoneNone
memory_limitstr | NoneNone
cache_dirstr | NoneNone
log_levelstr'warning'

Config.from_environment

@classmethod
def from_environment(cls) -> Self

Build configuration from Lacuna’s documented environment variables.

Finding

class Finding(
    code: str,
    title: str,
    message: str,
    state: FindingState,
    severity: Severity = Severity.INFO,
    category: str = 'general',
    evidence: Mapping[str, JsonValue] = {},
)

A single explicit piece of audit evidence.

FieldTypeDefault
codestrrequired
titlestrrequired
messagestrrequired
stateFindingStaterequired
severitySeveritySeverity.INFO
categorystr'general'
evidenceMapping[str, JsonValue]{}

Finding.to_dict

def to_dict() -> dict[str, object]

Return a JSON-compatible representation.

PortfolioProjectionResult

class PortfolioProjectionResult(evidence: AnalysisResult)

Immutable projected cohort rows plus structured diagnostic evidence.

FieldTypeDefault
evidenceAnalysisResultrequired

PortfolioProjectionResult.frame

frame: pl.DataFrame

Return a shallow clone of result-owned projection rows.

PortfolioProjectionResult.metadata

metadata: ResultMetadata

Expose projection provenance.

PortfolioProjectionResult.to_json

def to_json(*, indent: int | None = 2) -> str

Serialize compact evidence without embedding the projection frame.

ResultMetadata

class ResultMetadata(
    method: str,
    method_version: int = 1,
    parameters: Mapping[str, JsonValue] = {},
    seed: int | None = None,
    input_fingerprint: str | None = None,
    created_at: datetime = ...,
)

Provenance attached to a computed result.

FieldTypeDefault
methodstrrequired
method_versionint1
parametersMapping[str, JsonValue]{}
seedint | NoneNone
input_fingerprintstr | NoneNone
created_atdatetimeset when created

ResultMetadata.to_dict

def to_dict() -> dict[str, object]

Return a JSON-compatible representation.

SignalStudy

class SignalStudy(
    *,
    signal: object,
    prices: object,
    horizons: Sequence[Horizon] = ('1D', '5D', '20D'),
    signal_schema: Sequence[str] | None = None,
    price_schema: Sequence[str] | None = None,
    signal_time: str = 'time',
    price_time: str = 'time',
    instrument: str = 'instrument',
    signal_value: str = 'signal',
    price: str = 'close',
    entry: str | None = None,
    exit: str = 'close',
    signal_observed_at: Literal['open', 'close'] | None = None,
    price_adjustment: PriceAdjustment = 'unknown',
    delisting_return: str | None = None,
    missing: Literal['drop', 'raise'] = 'drop',
    allow_same_close: bool = False,
    quantiles: int = 5,
)

Reusable v0.1 workflow for a cross-sectional signal and price panel.

SignalStudy.labels

def labels() -> LabelResult

Construct and cache explicit forward labels.

SignalStudy.ic

def ic(
    *,
    method: Literal['pearson', 'spearman'] = 'spearman',
    by: str | Sequence[str] | None = 'observation_time',
    min_observations: int = 3,
    group_available_time: str | None = None,
    use_native: bool = True,
) -> AnalysisResult

Delegate to the functional IC implementation.

SignalStudy.bucketize

def bucketize(
    *,
    spec: signal_api.BucketSpec | None = None,
    by: str | Sequence[str] | None = None,
    available_time: str | None = None,
    ascending: bool = True,
    small_group_policy: Literal['raise', 'drop'] = 'raise',
) -> signal_api.SignalTransformResult

Create an explicit immutable signal transformation.

SignalStudy.bucket_returns

def bucket_returns(
    bucketed: signal_api.SignalTransformResult,
    *,
    by: str | Sequence[str] | None = 'observation_time',
) -> AnalysisResult

Summarize labels for a caller-selected bucket transformation.

SignalStudy.neutralize

def neutralize(
    *,
    exposures: Sequence[str],
    exposure_data: object | None = None,
    categorical: Sequence[str] = (),
    by: str | Sequence[str] | None = None,
    weight: str | None = None,
    available_time: str | None = None,
    intercept: bool = True,
    min_residual_df: int = 2,
    insufficient_policy: Literal['raise', 'drop'] = 'raise',
) -> signal_api.SignalTransformResult

Residualize the study signal using explicitly aligned exposures.

SignalStudy.quantiles

def quantiles(
    *,
    quantiles: int | None = None,
    by: str | Sequence[str] | None = 'observation_time',
    group_available_time: str | None = None,
) -> AnalysisResult

Delegate to deterministic quantile-return analysis.

SignalStudy.turnover

def turnover(
    *,
    quantiles: int | None = None,
    lags: Sequence[int] = (1,),
) -> AnalysisResult

Measure exact observation-lag signal turnover.

SignalStudy.decay

def decay(
    *,
    min_observations: int = 3,
    quantiles: int | None = None,
    use_native: bool = True,
) -> AnalysisResult

Evaluate IC and spread across the study horizons.

SignalStudy.fit_decay

def fit_decay(
    *,
    metric: str = 'mean_ic',
    expected_direction: Literal['positive', 'negative'] = 'positive',
    confidence: float = 0.95,
    resamples: int = 2000,
    expected_block_length: float | None = None,
    seed: int | None = None,
    minimum_r_squared: float = 0.5,
    min_observations: int = 3,
    quantiles: int | None = None,
    use_native: bool = True,
) -> AnalysisResult

Fit validated decay inference over this study’s retained horizon rows.

SignalStudy.portfolio_projection

def portfolio_projection(
    bucketed: signal_api.SignalTransformResult,
    *,
    horizon: str,
    long_buckets: Sequence[int],
    short_buckets: Sequence[int],
    weighting: Literal['equal', 'rank', 'absolute_signal'] = 'equal',
    gross_exposure: float = 1.0,
    net_exposure: float = 0.0,
    group_neutral: str | Sequence[str] | None = None,
    incomplete_group_policy: Literal['raise', 'drop'] = 'raise',
) -> signal_api.PortfolioProjectionResult

Project explicit bucket selections into independent diagnostic cohorts.

SignalStudy.audit

def audit(
    *,
    bootstrap_resamples: int = 1000,
    seed: int | None = None,
    min_observations: int = 3,
    split: SplitResult | CombinatorialSplitResult | AnalysisResult | None = None,
    policies: Mapping[str, JsonValue] | None = None,
    additional_evidence: Mapping[str, AnalysisResult] | None = None,
    rules: Sequence[AuditRule] | None = None,
    use_native: bool = True,
) -> AuditReport

Compute the v0.1 diagnostics and renderable structured audit.

SignalTransformResult

class SignalTransformResult(evidence: AnalysisResult)

Owned canonical signal frame plus compact transformation evidence.

FieldTypeDefault
evidenceAnalysisResultrequired

SignalTransformResult.frame

frame: pl.DataFrame

Return a shallow clone of the result-owned frame.

SignalTransformResult.metadata

metadata: ResultMetadata

Expose transformation provenance.

SignalTransformResult.to_json

def to_json(*, indent: int | None = 2) -> str

Serialize compact evidence while keeping the signal frame columnar.

Functions

config

def config(**changes: Unpack[_ConfigChanges]) -> Iterator[Config]

Temporarily apply configuration within a with block.

configure

def configure(**changes: Unpack[_ConfigChanges]) -> Config

Replace selected settings in the current execution context.

Use :func:config when a temporary, automatically restored scope is safer.

get_config

def get_config() -> Config

Return the configuration active in the current execution context.

Enums

FindingState

class FindingState(StrEnum)

Outcome of an audit check.

MemberValue
PASS'PASS'
WARN'WARN'
FAIL'FAIL'
UNKNOWN'UNKNOWN'
NOT_APPLICABLE'NOT_APPLICABLE'

Severity

class Severity(StrEnum)

Materiality of a finding, independent of its state.

MemberValue
INFO'info'
LOW'low'
MEDIUM'medium'
HIGH'high'
CRITICAL'critical'

Types and constants

BUNDLE_FORMAT

BUNDLE_FORMAT = 'lacuna.reproducibility-bundle'

BUNDLE_VERSION

BUNDLE_VERSION = 1

DIAGNOSTIC_VERSION

DIAGNOSTIC_VERSION = 1

Exceptions

ConfigurationError

class ConfigurationError(LacunaError, ValueError)

Raised when runtime configuration is invalid.

DataContractError

class DataContractError(LacunaError, ValueError)

Raised when input data does not satisfy a declared semantic contract.

LacunaError

class LacunaError(Exception)

Base class for errors raised by Lacuna.

MethodContractError

class MethodContractError(LacunaError, ValueError)

Raised when an analytical method or its configuration is undefined.

NativeExtensionError

class NativeExtensionError(LacunaError, RuntimeError)

Reserved for a required native capability that is unavailable.

No current code path raises it: native kernels fall back to the reference implementation and record the backend used.

PluginError

class PluginError(LacunaError, RuntimeError)

Raised when plugin discovery, negotiation, or explicit activation fails.

ReportError

class ReportError(LacunaError, RuntimeError)

Raised when a report cannot be rendered or persisted safely.