Options research
Validate option chains, derive forwards and moneyness under declared conventions, bucket by delta, measure implied-volatility residuals, and feed the evidence to Lacuna's standardized audit.
Option research fails quietly on data. A crossed quote, an expiry that falls on or before the quote time, a rate that was simple interest in the vendor file and continuous in your formula, a null implied volatility that a join dropped without a word: none of these raise an error in a spreadsheet or a dataframe, and all of them move a volatility surface.
lacuna-options is a separately versioned extension that sits below pricing. It validates a table of option quotes against an explicit contract, derives the forward and log-moneyness coordinates under conventions you declare, assigns absolute-delta buckets, and measures the gap between observed and expected implied volatility. Every step returns the transformed frame together with an AnalysisResult that records what was done. Lacuna’s standardized audit recognizes that evidence.
It does not invert prices to implied volatility, compute Greeks, fit a surface, detect arbitrage, or establish that a quote was available when you say you used it. Where it takes your word, this page says so.
Install
The extension is a separate distribution. It depends on lacuna-quant, so installing it pulls in a compatible core.
python -m pip install lacuna-options | Item | Value |
|---|---|
| Distribution | lacuna-options, import name lacuna_options |
| Version documented here | 0.2.2 |
| Compatible core | lacuna-quant>=0.13,<0.15 |
| Python | 3.11 or newer |
| Other dependencies | numpy>=2.0, polars>=1.30 |
The extension version is independent of the core version. A new core minor release outside that range needs a new extension release before the two install together. Core Lacuna imports without the extension, and the extension adds no options, solver or plotting library to core. It registers no plugin entry point, so you use it by importing it. The installation page covers the distribution-name collision with an unrelated PyPI project called lacuna.
A first example
The examples on this page share one synthetic chain: SPY-like quotes on two days and two expirations, five strikes, calls and puts. Prices come from the Black-Scholes formula with a skewed volatility plus noise, so the vendor iv differs from a smooth expected_iv. Replace this block with your own data.
from datetime import date
from math import erf, exp, log, sqrt
from pathlib import Path
import lacuna as lc
import lacuna_options as lo
import numpy as np
import polars as pl
def black_scholes(spot, strike, years, rate, dividend, vol, kind):
forward = spot * exp((rate - dividend) * years)
d1 = (log(forward / strike) + 0.5 * vol * vol * years) / (vol * sqrt(years))
d2 = d1 - vol * sqrt(years)
cdf = lambda x: 0.5 * (1.0 + erf(x / sqrt(2.0)))
discount = exp(-rate * years)
if kind == "call":
return discount * (forward * cdf(d1) - strike * cdf(d2)), exp(-dividend * years) * cdf(d1)
return discount * (strike * cdf(-d2) - forward * cdf(-d1)), -exp(-dividend * years) * cdf(-d1)
rng = np.random.default_rng(7)
rows = []
for day, spot in ((date(2025, 3, 3), 100.0), (date(2025, 3, 4), 101.5)):
for expiry in (date(2025, 4, 4), date(2025, 6, 20)):
years = (expiry - day).days / 365.25
for strike in (90.0, 95.0, 100.0, 105.0, 110.0):
smile = 0.20 + 0.0015 * (100.0 - strike)
for kind in ("call", "put"):
vol = smile + 0.01 * rng.standard_normal()
price, delta = black_scholes(spot, strike, years, 0.04, 0.01, vol, kind)
half_spread = max(0.05, 0.01 * price)
rows.append(
{
"time": day,
"instrument": f"SPY {expiry:%y%m%d}{kind[0].upper()}{int(strike)}",
"underlying": "SPY",
"expiration": expiry,
"strike": strike,
"option_type": kind,
"bid": round(price - half_spread, 2),
"ask": round(price + half_spread, 2),
"underlying_price": spot,
"rate": 0.04,
"dividend": 0.01,
"iv": round(vol, 4),
"delta": round(delta, 4),
"expected_iv": round(smile, 4),
}
)
quotes = pl.DataFrame(rows)
print(quotes.shape) (40, 14) validate_chain is the entry point. It checks the table, adds a mid price and three derived columns, and returns an OptionChain.
chain = lo.validate_chain(quotes)
print(chain.frame.select("instrument", "bid", "ask", "mid", "time_to_expiry_years", "log_moneyness").head(4))
print(dict(chain.evidence.metrics)) shape: (4, 6)
┌───────────────┬───────┬───────┬────────┬──────────────────────┬───────────────┐
│ instrument ┆ bid ┆ ask ┆ mid ┆ time_to_expiry_years ┆ log_moneyness │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞═══════════════╪═══════╪═══════╪════════╪══════════════════════╪═══════════════╡
│ SPY 250404C90 ┆ 10.23 ┆ 10.44 ┆ 10.335 ┆ 0.087611 ┆ -0.107989 │
│ SPY 250404P90 ┆ 0.07 ┆ 0.17 ┆ 0.12 ┆ 0.087611 ┆ -0.107989 │
│ SPY 250404C95 ┆ 5.79 ┆ 5.91 ┆ 5.85 ┆ 0.087611 ┆ -0.053922 │
│ SPY 250404P95 ┆ 0.51 ┆ 0.61 ┆ 0.56 ┆ 0.087611 ┆ -0.053922 │
└───────────────┴───────┴───────┴────────┴──────────────────────┴───────────────┘
{'quote_count': 40, 'instrument_count': 20, 'underlying_count': 1, 'expiration_count': 2} The frame keeps your rows in your order and your extra columns, such as expected_iv, and appends mid (when you did not supply one), time_to_expiry_years, forward and log_moneyness. The evidence counts the quotes, instruments, underlyings and expirations it saw.
Every other function takes that OptionChain. Bucket the quotes by absolute delta, then measure how far the vendor’s implied volatility sits from the expectation you supplied:
buckets = lo.delta_buckets(chain)
print(pl.DataFrame([dict(row) for row in buckets.evidence.tables["bucket_counts"]]))
residual = lo.empirical_residual(chain)
print({name: round(value, 5) for name, value in residual.evidence.metrics.items()}) shape: (7, 2)
┌──────────────┬────────┐
│ delta_bucket ┆ quotes │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════════════╪════════╡
│ [0.00,0.10) ┆ 4 │
│ [0.10,0.25) ┆ 8 │
│ [0.25,0.40) ┆ 5 │
│ [0.40,0.60) ┆ 6 │
│ [0.60,0.75) ┆ 6 │
│ [0.75,0.90) ┆ 7 │
│ [0.90,1.00] ┆ 4 │
└──────────────┴────────┘
{'quote_count': 40, 'mean_residual': -0.00395, 'median_residual': -0.0036, 'rmse': 0.00902, 'positive_fraction': 0.3} The residual is observed minus expected, so a negative mean says the vendor quotes sit below the expectation on average. Here the quotes are the expectation plus noise with a standard deviation of 0.01 by construction, so the small negative mean is sampling noise, not a finding. Whether that is a finding depends on where expected_iv came from, which is the subject of Empirical residuals.
What the extension adds
The package exports eight names.
| Name | Kind | Purpose |
|---|---|---|
lacuna_options.validate_chain | function | Validate and normalize quotes; derive mid, time to expiry, forward and log-moneyness. |
lacuna_options.delta_buckets | function | Assign absolute-delta buckets to a validated chain. |
lacuna_options.empirical_residual | function | Compute observed minus expected volatility with grouped evidence. |
lacuna_options.OptionChain | class | A frame that passed validate_chain, with its evidence. The only input the other functions accept. |
lacuna_options.OptionFrameResult | class | A frame plus evidence. The base class of OptionChain and the return type of the two analysis functions. |
lacuna_options.REQUIRED_CHAIN_COLUMNS | constant | The eleven canonical column names every chain needs. |
lacuna_options.OPTIONAL_CHAIN_COLUMNS | constant | The eight canonical column names that are validated when present. |
lacuna_options.__version__ | constant | The installed extension version. |
OptionChain and OptionFrameResult are frozen dataclasses with two fields, frame (a Polars DataFrame) and evidence (an lc.AnalysisResult). OptionChain is a subclass of OptionFrameResult. delta_buckets and empirical_residual check that their input is an OptionChain, and validate_chain is the function that produces one after checking the contract.
lo.empirical_residual(buckets) MethodContractError: chain must be the result of validate_chain The check is on the type, not on whether validation ran. validate_chain is the validated entry point. The OptionChain constructor is public but is a plain frozen container: OptionChain(frame=..., evidence=...) validates nothing, derives nothing and does not check the evidence, so a chain you build by hand from an unchecked frame passes straight through and skips the contract. Obtain chains from validate_chain.
Both analysis functions return an OptionFrameResult, not an OptionChain, so you cannot pass one’s result to the other. Call both on the same chain and combine the frames yourself. They preserve row order, so the combination is a column copy, shown in Residuals by delta bucket.
The chain contract
validate_chain accepts anything lacuna.adapters.to_polars accepts: a Polars frame or lazy frame, a pandas frame, an Arrow table, or a dict of columns. It always materializes the input, because it validates whole columns, and records materialized=True in the evidence. It does not modify your input.
| Parameter | Meaning |
|---|---|
data | The quotes: a Polars frame or lazy frame, a pandas frame, an Arrow table or a dict of columns. Lazy input is collected. |
columns | Canonical-to-source column names, for the columns whose names differ from the canonical ones. Must map to distinct sources. See Vendor column names. |
year_basis | The day-count denominator for time to expiry, in days: calendar duration divided by it. A Python int or float, positive and finite; booleans, strings and NumPy integer scalars are rejected. Change it to match the convention behind your Greeks. |
Required columns
| Column | Contract |
|---|---|
time | Quote observation time, Date or Datetime. No nulls. |
instrument | Contract identity. No nulls; any dtype. |
underlying | Underlying identity. No nulls; any dtype. |
expiration | The same dtype and time zone as time, and strictly later than time on every row. |
strike | Numeric, finite, strictly positive. |
option_type | Exactly the lowercase strings call or put. A categorical column holding those values is accepted. |
bid, ask | Numeric, finite, bid >= 0, and ask >= bid. A zero bid and a locked market (bid == ask) are valid. |
underlying_price | Numeric, finite, strictly positive. |
rate, dividend | Numeric, finite. Negative values are valid. |
Optional columns
Each optional column is validated only when present. A present column may not contain a null, NaN or infinity.
| Column | Additional rule |
|---|---|
mid | Within [bid, ask], inclusive. When absent it is computed as (bid + ask) / 2. |
iv | Strictly positive. |
delta | Within [-1, 1]. |
gamma, vega | Non-negative. |
theta | Any finite value; its sign is a model convention. |
open_interest, volume | Non-negative. |
Any other column passes through unchanged and unvalidated. That includes expected_iv, which empirical_residual validates when you use it. The exceptions are the columns the extension derives, which are never overwritten. If your input already has forward, time_to_expiry_years or log_moneyness, validate_chain raises lc.DataContractError naming them, and if the chain already has delta_bucket, delta_buckets does. Rename or drop such columns first. This also means a chain cannot be validated twice: passing chain.frame back to validate_chain fails until you drop the derived columns, so keep the raw quotes and validate those.
lo.validate_chain(chain.frame) DataContractError: option chain input columns collide with derived columns: forward, time_to_expiry_years, log_moneyness; rename or drop them before validation A null in one optional column rejects the entire chain. If your vendor leaves iv empty for deep out-of-the-money quotes, filter or fill those rows before validating, and decide on purpose which one you are doing.
What is rejected, and how
Every rejection of the data raises lc.DataContractError with a message naming the problem, so a bad chain never produces a partial result. Only integer and float columns of any width are accepted for the numeric fields. A Decimal column raises lc.DataContractError naming the column and its dtype (invalid dtypes: strike=Decimal(...)). It is not cast for you, because a cast to Float64 could change the quoted values. Cast it yourself, in the query or with Polars, once you have decided that is acceptable. A bad argument (columns or year_basis) raises lc.MethodContractError. A crossed market:
lo.validate_chain(quotes.with_columns((pl.col("bid") + 1.0).alias("bid"))) DataContractError: strikes and underlyings must be positive, quotes non-negative, and bid <= ask A Datetime quote time against a Date expiry, which is a common shape when a vendor ships timestamps and calendar expiries:
lo.validate_chain(quotes.with_columns(pl.col("time").cast(pl.Datetime("us")))) DataContractError: time and expiration must use the same physical dtype and timezone Cast one side so both share a dtype and time zone. Casting the expiry to the quote’s timestamp type means choosing the expiry’s time of day, which is a decision about settlement that the extension will not make for you.
Capitalized option types are not normalized. "Call", "C" and "p" all raise, and the message lists the values it received. Map them yourself before validating.
What is not checked
The extension checks the shape and ranges of one table. It does not check the following, and a chain that passes can still be wrong in these ways.
| Not checked | Consequence |
|---|---|
| Duplicate keys | Two quotes for the same time and instrument are both kept. Row order is preserved and never used to pick one. Deduplicate before downstream work. |
| Sort order | The frame keeps your order. Nothing is sorted. |
| Availability | time is the quote’s observation time. Nothing verifies that the quote, the rate or the dividend was known at the time you decide. See Point-in-time data. |
| Stale or one-sided quotes | A zero bid passes. Quote quality filters are yours to apply. |
| Put-call parity, monotonicity, butterfly or calendar arbitrage | No arbitrage test is performed. |
iv, delta, gamma, vega, theta against prices | They are range-checked, not recomputed. Whatever model or convention produced them is yours to know. |
| Exercise style, settlement, dividend events, calendars | American options and discrete dividends are outside the contract. |
| Consistency across rows | underlying_price, rate and dividend need not agree across rows that share a time and underlying, and an instrument may carry different strikes, expiries or types on different rows. Each row gets its own forward. Nothing checks that underlying_price was observed at the same moment as the quote. |
Declared inputs
Several columns carry conventions Lacuna records but cannot verify. They are your declarations.
| Input | What Lacuna checks | What you are asserting |
|---|---|---|
rate, dividend | Finite, no nulls. | Continuously compounded, annualized, and appropriate for the expiry (a curve point, not one flat number by accident). |
year_basis | Positive and finite. | The day-count denominator you want applied to the calendar duration. |
iv, delta and other Greeks | Ranges. | The pricing model, day count and dividend treatment behind them match the forward and moneyness this page derives. |
expected_iv | Positive, finite. | It was not fitted on the quotes you are about to judge. |
The evidence stores year_basis, the forward and moneyness conventions and the column mapping, so a reviewer can see what you declared.
Vendor column names
columns maps canonical names to your source names. You only list the columns that differ.
vendor = quotes.rename({"time": "quote_date", "strike": "strike_price", "option_type": "cp_flag"})
mapped = lo.validate_chain(
vendor,
columns={"time": "quote_date", "strike": "strike_price", "option_type": "cp_flag"},
)
print(mapped.frame.columns[:6])
print(dict(mapped.evidence.metadata.parameters["column_mapping"])["strike"]) ['time', 'instrument', 'underlying', 'expiration', 'strike', 'option_type']
strike_price The mapping must use known canonical names and map them to distinct source columns, and the rename must not overwrite a column that already has the canonical name. Violations raise lc.MethodContractError or lc.DataContractError. A missing required source column raises an error that names the source column it expected.
A mapping entry for an optional column whose source is absent is ignored, and a column that already carries the canonical name is then used as it is. The evidence still records the mapping you passed. If you map mid to a source column that does not exist and the frame has its own mid, that mid is validated and used.
Derived coordinates
With quote time , expiration , year basis , spot , strike , continuously compounded rate and dividend yield :
The columns are time_to_expiry_years for , forward for and log_moneyness for . Negative means the strike is below the forward. Each row’s comes from that row’s own underlying_price, rate and dividend, so the call and the put at a strike share a coordinate only when those inputs agree. Nothing enforces that.
For Date inputs the duration is a whole number of calendar days divided by year_basis. For Datetime inputs it is the duration in whole seconds, truncated, divided by year_basis * 86400. A quote less than one second before its expiry therefore fails, because its maturity truncates to zero. For time-zone-aware datetimes this is elapsed time, not wall-clock time, so across a daylight-saving change a Datetime maturity differs slightly from the Date maturity for the same days. year_basis defaults to 365.25 calendar days. It is a stated convention, not a claim about any exchange or model; use 365 or 360 if that is what your model uses, and keep it the same as the one behind your vendor’s Greeks. year_basis divides calendar days, so a trading-day count such as 252 would overstate every maturity by about 45%.
first = chain.frame.row(0, named=True)
days = (first["expiration"] - first["time"]).days
tau = days / 365.25
forward = first["underlying_price"] * np.exp((first["rate"] - first["dividend"]) * tau)
print(days, round(forward, 4), round(first["forward"], 4))
print(round(float(np.log(first["strike"] / forward)), 6), round(first["log_moneyness"], 6)) 32 100.2632 100.2632
-0.107989 -0.107989 The extension also requires the derived columns to be finite, the maturity positive and the forward positive. A rate large enough to overflow the exponential, or to underflow the forward to zero, raises lc.DataContractError instead of passing infinities downstream.
Delta buckets
delta_buckets groups quotes by the absolute value of delta. The chain must contain a validated delta column, and must not already have a delta_bucket column. Either problem raises lc.DataContractError.
| Parameter | Meaning |
|---|---|
chain | A result of validate_chain. A plain frame or the result of another function raises lc.MethodContractError. |
edges | Bucket boundaries on absolute delta. Strictly increasing, finite, beginning at exactly 0 and ending at exactly 1. The default is (0.0, 0.10, 0.25, 0.40, 0.60, 0.75, 0.90, 1.0). |
Buckets are left-closed and right-open, except that the last is closed, so every in lands in exactly one bucket and lands in the last. A put with delta and a call with delta share the bucket . The comparison is exact floating point: a delta stored as 0.09999999999999999 falls in the lower bucket, so round your deltas to the precision you mean before bucketing.
print(buckets.frame.select("instrument", "delta", "delta_bucket").head(4))
coarse = lo.delta_buckets(chain, edges=(0.0, 0.25, 0.5, 0.75, 1.0))
print([(row["delta_bucket"], row["quotes"]) for row in coarse.evidence.tables["bucket_counts"]])
print(dict(coarse.evidence.metrics)) shape: (4, 3)
┌───────────────┬─────────┬──────────────┐
│ instrument ┆ delta ┆ delta_bucket │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ str │
╞═══════════════╪═════════╪══════════════╡
│ SPY 250404C90 ┆ 0.9572 ┆ [0.90,1.00] │
│ SPY 250404P90 ┆ -0.044 ┆ [0.00,0.10) │
│ SPY 250404C95 ┆ 0.8205 ┆ [0.75,0.90) │
│ SPY 250404P95 ┆ -0.1717 ┆ [0.10,0.25) │
└───────────────┴─────────┴──────────────┘
[('[0.00,0.25)', 12), ('[0.25,0.50)', 8), ('[0.50,0.75)', 9), ('[0.75,1.00]', 11)]
{'quote_count': 40, 'occupied_buckets': 4} The bucket_counts table lists only occupied buckets, sorted by label text, and occupied_buckets counts them. A bucket with no quotes is absent, not zero.
Labels print edges with two decimals, so they are rounded for display; an edge of 0.125 appears as 0.12. The exact edges are in the evidence’s parameters. When two edges would print the same at two decimals, every label widens to the fewest decimals that separate all the edges, so distinct edges always get distinct labels and bucket_counts never merges buckets. The default edges and any edges at least 0.01 apart keep the two-decimal labels, so existing output is unchanged.
fine = lo.delta_buckets(chain, edges=(0.0, 0.1, 0.1001, 1.0))
print(sorted(set(fine.frame.get_column("delta_bucket")))) ['[0.0000,0.1000)', '[0.1001,1.0000]'] The function buckets the delta you supplied. It does not compute or redefine delta.
Empirical residuals
empirical_residual computes, for each quote,
and summarizes it. The observed and expected columns are in the same units as the volatility inputs: if iv is a decimal, 0.01 is one volatility point.
The estimand is the average vertical gap between a market surface and a reference surface that you provide. The extension does not produce the reference. It can be a smooth fit from earlier data, a model’s fair value, or another vendor’s surface. If you fit it on the same quotes you then measure, the residual is in-sample and understates the gap you would see on new data.
| Parameter | Meaning |
|---|---|
chain | A result of validate_chain. It must hold the observed and expected columns; pass extra columns through the validator and they stay in the frame. |
observed | The column of observed volatility. Defaults to iv. |
expected | The column of expected volatility. Defaults to expected_iv. A chain without it raises lc.DataContractError. |
output | The name of the residual column added to the returned frame. Defaults to iv_residual. |
Both input columns must be numeric, with no nulls and no non-finite values, and strictly positive. The output name must not already exist in the frame. If it equals observed or expected, the call raises lc.MethodContractError rather than replacing that input column, and any other existing name raises lc.DataContractError. Naming the same column for observed and expected is allowed and gives zero residuals.
print(residual.frame.select("instrument", "iv", "expected_iv", "iv_residual").head(3))
groups = pl.DataFrame([dict(row) for row in residual.evidence.tables["surface_groups"]])
print(groups.select("time", "expiration", "quotes", pl.col("mean_residual").round(5), pl.col("rmse").round(5))) shape: (3, 4)
┌───────────────┬────────┬─────────────┬─────────────┐
│ instrument ┆ iv ┆ expected_iv ┆ iv_residual │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═══════════════╪════════╪═════════════╪═════════════╡
│ SPY 250404C90 ┆ 0.215 ┆ 0.215 ┆ 0.0 │
│ SPY 250404P90 ┆ 0.218 ┆ 0.215 ┆ 0.003 │
│ SPY 250404C95 ┆ 0.2048 ┆ 0.2075 ┆ -0.0027 │
└───────────────┴────────┴─────────────┴─────────────┘
shape: (4, 5)
┌────────────┬────────────┬────────┬───────────────┬─────────┐
│ time ┆ expiration ┆ quotes ┆ mean_residual ┆ rmse │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 ┆ f64 │
╞════════════╪════════════╪════════╪═══════════════╪═════════╡
│ 2025-03-03 ┆ 2025-04-04 ┆ 10 ┆ -0.00201 ┆ 0.00675 │
│ 2025-03-03 ┆ 2025-06-20 ┆ 10 ┆ -0.00429 ┆ 0.0095 │
│ 2025-03-04 ┆ 2025-04-04 ┆ 10 ┆ -0.00611 ┆ 0.01088 │
│ 2025-03-04 ┆ 2025-06-20 ┆ 10 ┆ -0.00339 ┆ 0.00842 │
└────────────┴────────────┴────────┴───────────────┴─────────┘ | Metric | Definition |
|---|---|
quote_count | Number of quotes. |
mean_residual | Arithmetic mean of . |
median_residual | Median of . |
rmse | . This is a root mean square, not centered on the mean residual. |
positive_fraction | Share of quotes with . |
The surface_groups table repeats quotes, the mean and the root mean square per (time, underlying, expiration) group. Calls and puts are pooled in a group, and every quote has equal weight. Nothing weights by vega, open interest or spread, and nothing attaches a standard error or an interval. On real data the residuals within one surface are typically strongly correlated, so a mean over 40 quotes carries far less information than 40 independent observations; do not read the metrics as a t-statistic’s numerator. In this synthetic chain the residuals are independent noise by construction, so the bucket means in the next section fluctuate only because each bucket holds a handful of quotes.
Residuals by delta bucket
The residual and the buckets are separate results over the same rows in the same order, so combine them by column.
combined = residual.frame.with_columns(buckets.frame.get_column("delta_bucket"))
by_bucket = (
combined.group_by("delta_bucket")
.agg(pl.len().alias("quotes"), pl.col("iv_residual").mean().round(5).alias("mean_residual"))
.sort("delta_bucket")
)
print(by_bucket) shape: (7, 3)
┌──────────────┬────────┬───────────────┐
│ delta_bucket ┆ quotes ┆ mean_residual │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 │
╞══════════════╪════════╪═══════════════╡
│ [0.00,0.10) ┆ 4 ┆ -0.0012 │
│ [0.10,0.25) ┆ 8 ┆ -0.00496 │
│ [0.25,0.40) ┆ 5 ┆ -0.01158 │
│ [0.40,0.60) ┆ 6 ┆ 0.00013 │
│ [0.60,0.75) ┆ 6 ┆ 0.00037 │
│ [0.75,0.90) ┆ 7 ┆ -0.00501 │
│ [0.90,1.00] ┆ 4 ┆ -0.00588 │
└──────────────┴────────┴───────────────┘ Results and evidence
All three functions return evidence as an lc.AnalysisResult, described in Results and evidence.
| Result | method | Parameters recorded | Metrics | Tables |
|---|---|---|---|---|
validate_chain | options.validate_chain | source type, column mapping, year_basis, forward and moneyness conventions, option-type values, whether mid was computed, materialized | quote_count, instrument_count, underlying_count, expiration_count | none |
delta_buckets | options.delta_buckets | edges, closure rule, absolute_delta coordinate | quote_count, occupied_buckets | bucket_counts |
empirical_residual | options.empirical_residual | observed, expected and output column names, observed_minus_expected definition | the five metrics above | surface_groups |
Each has method_version 1. None uses randomness, so none records a seed. None records an input fingerprint, so a result does not identify the data it came from. If you need that identity, record it yourself, for example with lc.experiment.fingerprint on the table and the attempt’s data fingerprint in an experiment (see Experiments). None adds findings or warnings: the extension reports what it computed and rejects what it cannot, but it does not judge the numbers. Each evidence object serializes with to_json() like any other result.
The dataclasses are frozen, so frame and evidence cannot be reassigned, and the extension’s functions never modify a frame in place. A Polars DataFrame is itself mutable, though: changing chain.frame yourself can invalidate the chain without any error.
Audits
The standardized audit recognizes these results by method name. Any result whose method starts with options. is matched to the capability options_evidence, “Options-extension evidence”, which has high severity and sits in the statistical_validity category. Its disposition depends on the audit scope:
| Scope | options_evidence |
|---|---|
options | required |
signal | not applicable |
strategy | not applicable |
Supply any one of the three results to an options audit and the capability’s finding is a PASS. Supply none and it is UNKNOWN. Supply options evidence to a signal or strategy audit and you get a WARN, saying that evidence arrived for a capability that scope does not use, which usually means you chose the wrong scope.
results = {
"chain": chain.evidence,
"delta_buckets": buckets.evidence,
"iv_residual": residual.evidence,
}
report = lc.standard_audit(results=results, scope="options")
metrics = report.result.metrics
print(metrics["required_capability_present_count"], "of", metrics["required_capability_count"], "required capabilities present")
print("coverage", metrics["required_evidence_coverage"])
for finding in report.result.findings:
if finding.code == "EVIDENCE_OPTIONS_EVIDENCE":
print(finding.code, finding.state.value, finding.severity.value)
wrong_scope = lc.standard_audit(results=results, scope="signal")
print([f.state.value for f in wrong_scope.result.findings if f.code == "EVIDENCE_OPTIONS_EVIDENCE"]) 1 of 10 required capabilities present
coverage 0.1
EVIDENCE_OPTIONS_EVIDENCE PASS high
['WARN'] Read that coverage figure carefully. The chain evidence satisfies one of ten required capabilities in the options scope, so required coverage is 0.1. The options scope still requires temporal validation, inference, experiment lineage, multiple-testing, parameter and subperiod robustness, execution realism and point-in-time evidence. These stay UNKNOWN until you supply results for them:
unknown = sorted(f.code for f in report.result.findings if f.state.value == "UNKNOWN")
print(unknown) ['EVIDENCE_ADVANCED_INFERENCE', 'EVIDENCE_EXECUTION_REALISM', 'EVIDENCE_EXPERIMENT_LINEAGE', 'EVIDENCE_MULTIPLE_TESTING', 'EVIDENCE_PARAMETER_ROBUSTNESS', 'EVIDENCE_POINT_IN_TIME_DATA', 'EVIDENCE_RESAMPLING_INFERENCE', 'EVIDENCE_TEMPORAL_ROBUSTNESS', 'EVIDENCE_TEMPORAL_VALIDATION'] The PASS is a coverage pass. It says recognized evidence was supplied, and it certifies nothing about the chain, because the options results carry no findings for the audit to propagate. In particular it does not establish point-in-time safety. The options scope requires that as its own capability, point_in_time_data, with evidence such as lc.bias.future_data_check. Audits and reports shows how to supply the rest.
The command line takes the same evidence as JSON files:
Path("chain.json").write_text(chain.evidence.to_json())
Path("residual.json").write_text(residual.evidence.to_json()) lacuna audit --evidence chain=chain.json --evidence residual=residual.json --scope options --out options-audit.md
grep -A3 "Options-extension evidence" options-audit.md | head -4 ### PASS · Options-extension evidence
- Code: `EVIDENCE_OPTIONS_EVIDENCE`
- Severity: `high` API reference
The package has no generated reference page, so the public names and signatures follow. Import them as import lacuna_options as lo.
validate_chain
def validate_chain(
data: object,
*,
columns: Mapping[str, str] | None = None,
year_basis: float = 365.25,
) -> OptionChain Validate and normalize quotes, then derive forward coordinates. A lazy frame is collected in full. Raises lc.DataContractError for invalid data, including Decimal columns and input columns that collide with the derived ones, and lc.MethodContractError for invalid arguments.
delta_buckets
def delta_buckets(
chain: OptionChain,
*,
edges: Sequence[float] = (0.0, 0.1, 0.25, 0.4, 0.6, 0.75, 0.9, 1.0),
) -> OptionFrameResult Assign deterministic left-closed buckets over absolute option delta.
empirical_residual
def empirical_residual(
chain: OptionChain,
*,
observed: str = 'iv',
expected: str = 'expected_iv',
output: str = 'iv_residual',
) -> OptionFrameResult Compute observed-minus-expected volatility with grouped evidence.
OptionChain
class OptionChain(frame: pl.DataFrame, evidence: AnalysisResult) A chain produced by validate_chain under the lacuna-options schema. Constructing it directly performs no validation. Subclass of OptionFrameResult; frozen.
OptionFrameResult
class OptionFrameResult(frame: pl.DataFrame, evidence: AnalysisResult) A normalized options frame and its immutable evidence. Frozen.
REQUIRED_CHAIN_COLUMNS
REQUIRED_CHAIN_COLUMNS = ('time', 'instrument', 'underlying', 'expiration', 'strike', 'option_type', 'bid', 'ask', 'underlying_price', 'rate', 'dividend') The canonical names of the columns every chain must have.
OPTIONAL_CHAIN_COLUMNS
OPTIONAL_CHAIN_COLUMNS = ('mid', 'iv', 'delta', 'gamma', 'vega', 'theta', 'open_interest', 'volume') The canonical names of the columns that are validated when present.
__version__
__version__ = '0.2.2' The installed lacuna-options version.