lacuna-options 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ """Optional empirical options-research extension for Lacuna."""
2
+
3
+ from lacuna_options._version import __version__
4
+ from lacuna_options.chain import (
5
+ OPTIONAL_CHAIN_COLUMNS,
6
+ REQUIRED_CHAIN_COLUMNS,
7
+ OptionChain,
8
+ OptionFrameResult,
9
+ delta_buckets,
10
+ empirical_residual,
11
+ validate_chain,
12
+ )
13
+
14
+ __all__ = [
15
+ "OPTIONAL_CHAIN_COLUMNS",
16
+ "REQUIRED_CHAIN_COLUMNS",
17
+ "OptionChain",
18
+ "OptionFrameResult",
19
+ "__version__",
20
+ "delta_buckets",
21
+ "empirical_residual",
22
+ "validate_chain",
23
+ ]
@@ -0,0 +1,3 @@
1
+ """Independent release identity for the optional options extension."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,375 @@
1
+ """Normalized empirical option-chain contracts and derived coordinates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Mapping, Sequence
7
+ from dataclasses import dataclass
8
+ from itertools import pairwise
9
+ from typing import TypeAlias, cast
10
+
11
+ import numpy as np
12
+ import numpy.typing as npt
13
+ import polars as pl
14
+ from lacuna.adapters import to_polars
15
+ from lacuna.exceptions import DataContractError, MethodContractError
16
+ from lacuna.types import AnalysisResult, JsonValue, ResultMetadata
17
+
18
+ FloatArray: TypeAlias = npt.NDArray[np.float64]
19
+
20
+ REQUIRED_CHAIN_COLUMNS = (
21
+ "time",
22
+ "instrument",
23
+ "underlying",
24
+ "expiration",
25
+ "strike",
26
+ "option_type",
27
+ "bid",
28
+ "ask",
29
+ "underlying_price",
30
+ "rate",
31
+ "dividend",
32
+ )
33
+ OPTIONAL_CHAIN_COLUMNS = (
34
+ "mid",
35
+ "iv",
36
+ "delta",
37
+ "gamma",
38
+ "vega",
39
+ "theta",
40
+ "open_interest",
41
+ "volume",
42
+ )
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class OptionFrameResult:
47
+ """A normalized options frame and its immutable evidence."""
48
+
49
+ frame: pl.DataFrame
50
+ evidence: AnalysisResult
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class OptionChain(OptionFrameResult):
55
+ """A chain that passed the `lacuna-options` normalized schema."""
56
+
57
+
58
+ def _mapping(columns: Mapping[str, str] | None) -> dict[str, str]:
59
+ resolved = {column: column for column in (*REQUIRED_CHAIN_COLUMNS, *OPTIONAL_CHAIN_COLUMNS)}
60
+ if columns is None:
61
+ return resolved
62
+ if not isinstance(columns, Mapping):
63
+ raise MethodContractError("columns must be a canonical-to-source mapping")
64
+ if any(
65
+ not isinstance(canonical, str) or not canonical or not isinstance(source, str) or not source
66
+ for canonical, source in columns.items()
67
+ ):
68
+ raise MethodContractError("column mappings must use non-empty string names")
69
+ unknown = sorted(set(columns).difference(resolved))
70
+ if unknown:
71
+ raise MethodContractError(f"unknown canonical option columns: {', '.join(unknown)}")
72
+ resolved.update(columns)
73
+ if len(set(resolved.values())) != len(resolved):
74
+ raise MethodContractError("option source columns must map uniquely")
75
+ return resolved
76
+
77
+
78
+ def _rename(frame: pl.DataFrame, columns: Mapping[str, str]) -> pl.DataFrame:
79
+ source_columns = set(frame.columns)
80
+ missing = sorted(
81
+ columns[column]
82
+ for column in REQUIRED_CHAIN_COLUMNS
83
+ if columns[column] not in source_columns
84
+ )
85
+ if missing:
86
+ raise DataContractError(f"option chain is missing required columns: {', '.join(missing)}")
87
+ present_mapping = {
88
+ source: canonical
89
+ for canonical, source in columns.items()
90
+ if source in source_columns and source != canonical
91
+ }
92
+ moving_sources = set(present_mapping)
93
+ collisions = sorted(
94
+ canonical
95
+ for source, canonical in present_mapping.items()
96
+ if canonical in source_columns and canonical not in moving_sources and canonical != source
97
+ )
98
+ if collisions:
99
+ raise DataContractError(
100
+ f"option normalization would overwrite existing columns: {', '.join(collisions)}"
101
+ )
102
+ return frame.rename(present_mapping)
103
+
104
+
105
+ def _require_numeric(frame: pl.DataFrame, columns: Sequence[str]) -> None:
106
+ invalid_dtypes = [column for column in columns if not frame.schema[column].is_numeric()]
107
+ if invalid_dtypes:
108
+ details = ", ".join(f"{column}={frame.schema[column]}" for column in invalid_dtypes)
109
+ raise DataContractError(f"option numeric columns have invalid dtypes: {details}")
110
+ invalid_values = [
111
+ column
112
+ for column in columns
113
+ if frame.get_column(column).null_count()
114
+ or not bool(frame.select(pl.col(column).is_finite().all()).item())
115
+ ]
116
+ if invalid_values:
117
+ raise DataContractError(
118
+ f"option numeric columns contain null or non-finite values: {', '.join(invalid_values)}"
119
+ )
120
+
121
+
122
+ def _maturity_expression(dtype: pl.DataType, year_basis: float) -> pl.Expr:
123
+ duration = pl.col("expiration") - pl.col("time")
124
+ if dtype == pl.Date:
125
+ return duration.dt.total_days().cast(pl.Float64) / year_basis
126
+ if isinstance(dtype, pl.Datetime):
127
+ seconds_per_year = year_basis * 24.0 * 60.0 * 60.0
128
+ return duration.dt.total_seconds().cast(pl.Float64) / seconds_per_year
129
+ raise DataContractError("option time and expiration must be Date or Datetime columns")
130
+
131
+
132
+ def validate_chain(
133
+ data: object,
134
+ *,
135
+ columns: Mapping[str, str] | None = None,
136
+ year_basis: float = 365.25,
137
+ ) -> OptionChain:
138
+ """Validate and normalize quotes, then derive forward coordinates.
139
+
140
+ ``forward`` uses continuously compounded carry,
141
+ :math:`S exp((r-q)T)`. ``log_moneyness`` is :math:`log(K/F)`. The caller
142
+ supplies rates, dividend yields, and the day-count denominator; Lacuna does
143
+ not infer them from vendor or market conventions.
144
+ """
145
+
146
+ if isinstance(year_basis, bool) or not isinstance(year_basis, int | float):
147
+ raise MethodContractError("year_basis must be a positive finite number")
148
+ resolved_basis = float(year_basis)
149
+ if not math.isfinite(resolved_basis) or resolved_basis <= 0.0:
150
+ raise MethodContractError("year_basis must be a positive finite number")
151
+ resolved_columns = _mapping(columns)
152
+ normalized = to_polars(data, collect=True)
153
+ if isinstance(normalized, pl.LazyFrame): # pragma: no cover - collect=True contract
154
+ normalized = normalized.collect()
155
+ frame = _rename(normalized, resolved_columns)
156
+ if frame.is_empty():
157
+ raise DataContractError("option chain must contain at least one quote")
158
+ if any(frame.get_column(column).null_count() for column in REQUIRED_CHAIN_COLUMNS):
159
+ raise DataContractError("required option-chain columns must not contain nulls")
160
+ if frame.schema["time"] != frame.schema["expiration"]:
161
+ raise DataContractError("time and expiration must use the same physical dtype and timezone")
162
+
163
+ numeric = ["strike", "bid", "ask", "underlying_price", "rate", "dividend"]
164
+ numeric.extend(column for column in OPTIONAL_CHAIN_COLUMNS if column in frame.columns)
165
+ _require_numeric(frame, numeric)
166
+ if bool(frame.select((pl.col("expiration") <= pl.col("time")).any()).item()):
167
+ raise DataContractError("every option expiration must be strictly after its quote time")
168
+ invalid_option_types = sorted(
169
+ set(frame.get_column("option_type").cast(pl.String).unique().to_list()).difference(
170
+ {"call", "put"}
171
+ )
172
+ )
173
+ if invalid_option_types:
174
+ raise DataContractError(
175
+ "option_type must contain only explicit 'call' or 'put' values; received "
176
+ + ", ".join(str(item) for item in invalid_option_types)
177
+ )
178
+ if bool(
179
+ frame.select(
180
+ (
181
+ (pl.col("strike") <= 0.0)
182
+ | (pl.col("underlying_price") <= 0.0)
183
+ | (pl.col("bid") < 0.0)
184
+ | (pl.col("ask") < pl.col("bid"))
185
+ ).any()
186
+ ).item()
187
+ ):
188
+ raise DataContractError(
189
+ "strikes and underlyings must be positive, quotes non-negative, and bid <= ask"
190
+ )
191
+
192
+ mid_computed = "mid" not in frame.columns
193
+ if mid_computed:
194
+ frame = frame.with_columns(((pl.col("bid") + pl.col("ask")) / 2.0).alias("mid"))
195
+ elif bool(
196
+ frame.select(
197
+ ((pl.col("mid") < pl.col("bid")) | (pl.col("mid") > pl.col("ask"))).any()
198
+ ).item()
199
+ ):
200
+ raise DataContractError("mid must lie inside the inclusive bid/ask interval")
201
+ if "iv" in frame.columns and bool(frame.select((pl.col("iv") <= 0.0).any()).item()):
202
+ raise DataContractError("implied volatility must be positive")
203
+ if "delta" in frame.columns and bool(frame.select((pl.col("delta").abs() > 1.0).any()).item()):
204
+ raise DataContractError("delta must lie in the closed interval [-1, 1]")
205
+ non_negative_optional = [
206
+ column for column in ("gamma", "vega", "open_interest", "volume") if column in frame.columns
207
+ ]
208
+ if any(
209
+ bool(frame.select((pl.col(column) < 0.0).any()).item()) for column in non_negative_optional
210
+ ):
211
+ raise DataContractError("gamma, vega, open interest, and volume must be non-negative")
212
+
213
+ maturity = _maturity_expression(frame.schema["time"], resolved_basis)
214
+ frame = (
215
+ frame.with_columns(maturity.alias("time_to_expiry_years"))
216
+ .with_columns(
217
+ (
218
+ pl.col("underlying_price")
219
+ * ((pl.col("rate") - pl.col("dividend")) * pl.col("time_to_expiry_years")).exp()
220
+ ).alias("forward")
221
+ )
222
+ .with_columns((pl.col("strike") / pl.col("forward")).log().alias("log_moneyness"))
223
+ )
224
+ _require_numeric(frame, ("mid", "time_to_expiry_years", "forward", "log_moneyness"))
225
+ if bool(frame.select((pl.col("time_to_expiry_years") <= 0.0).any()).item()):
226
+ raise DataContractError("time to expiry must be positive under the declared year basis")
227
+ if bool(frame.select((pl.col("forward") <= 0.0).any()).item()):
228
+ raise DataContractError("derived forwards must be positive")
229
+
230
+ evidence = AnalysisResult(
231
+ metadata=ResultMetadata(
232
+ method="options.validate_chain",
233
+ method_version=1,
234
+ parameters={
235
+ "source_type": f"{type(data).__module__}.{type(data).__name__}",
236
+ "column_mapping": cast(Mapping[str, JsonValue], resolved_columns),
237
+ "year_basis": resolved_basis,
238
+ "forward_convention": "S*exp((rate-dividend)*T)",
239
+ "moneyness_convention": "log(strike/forward)",
240
+ "option_type_values": ("call", "put"),
241
+ "mid_computed": mid_computed,
242
+ "materialized": True,
243
+ },
244
+ ),
245
+ metrics={
246
+ "quote_count": frame.height,
247
+ "instrument_count": frame.get_column("instrument").n_unique(),
248
+ "underlying_count": frame.get_column("underlying").n_unique(),
249
+ "expiration_count": frame.get_column("expiration").n_unique(),
250
+ },
251
+ )
252
+ return OptionChain(frame=frame, evidence=evidence)
253
+
254
+
255
+ def delta_buckets(
256
+ chain: OptionChain,
257
+ *,
258
+ edges: Sequence[float] = (0.0, 0.10, 0.25, 0.40, 0.60, 0.75, 0.90, 1.0),
259
+ ) -> OptionFrameResult:
260
+ """Assign deterministic left-closed buckets over absolute option delta."""
261
+
262
+ if not isinstance(chain, OptionChain):
263
+ raise MethodContractError("chain must be the result of validate_chain")
264
+ if "delta" not in chain.frame.columns:
265
+ raise DataContractError("delta_buckets requires a validated delta column")
266
+ try:
267
+ resolved_edges: FloatArray = np.asarray(edges, dtype=np.float64)
268
+ except (TypeError, ValueError) as error:
269
+ raise MethodContractError("edges must be finite numeric boundaries") from error
270
+ if (
271
+ resolved_edges.ndim != 1
272
+ or resolved_edges.size < 2
273
+ or not np.isfinite(resolved_edges).all()
274
+ or resolved_edges[0] != 0.0
275
+ or resolved_edges[-1] != 1.0
276
+ or bool(np.any(np.diff(resolved_edges) <= 0.0))
277
+ ):
278
+ raise MethodContractError(
279
+ "edges must be strictly increasing finite boundaries starting at 0 and ending at 1"
280
+ )
281
+ labels = tuple(
282
+ f"[{left:.2f},{right:.2f}{']' if index == resolved_edges.size - 2 else ')'}"
283
+ for index, (left, right) in enumerate(pairwise(resolved_edges))
284
+ )
285
+ delta: FloatArray = (
286
+ chain.frame.get_column("delta").abs().to_numpy().astype(np.float64, copy=False)
287
+ )
288
+ indices = np.searchsorted(resolved_edges, delta, side="right") - 1
289
+ indices = np.minimum(indices, len(labels) - 1)
290
+ bucket_values = np.asarray(labels, dtype=object)[indices]
291
+ frame = chain.frame.with_columns(pl.Series("delta_bucket", bucket_values))
292
+ counts = frame.group_by("delta_bucket").len(name="quotes").sort("delta_bucket").to_dicts()
293
+ evidence = AnalysisResult(
294
+ metadata=ResultMetadata(
295
+ method="options.delta_buckets",
296
+ method_version=1,
297
+ parameters={
298
+ "edges": tuple(float(value) for value in resolved_edges),
299
+ "closure": "left_closed_right_open_except_final_closed",
300
+ "coordinate": "absolute_delta",
301
+ },
302
+ ),
303
+ metrics={"quote_count": frame.height, "occupied_buckets": len(counts)},
304
+ tables={"bucket_counts": tuple(cast(dict[str, JsonValue], row) for row in counts)},
305
+ )
306
+ return OptionFrameResult(frame=frame, evidence=evidence)
307
+
308
+
309
+ def empirical_residual(
310
+ chain: OptionChain,
311
+ *,
312
+ observed: str = "iv",
313
+ expected: str = "expected_iv",
314
+ output: str = "iv_residual",
315
+ ) -> OptionFrameResult:
316
+ """Compute observed-minus-expected volatility with grouped evidence."""
317
+
318
+ if not isinstance(chain, OptionChain):
319
+ raise MethodContractError("chain must be the result of validate_chain")
320
+ if any(not isinstance(name, str) or not name for name in (observed, expected, output)):
321
+ raise MethodContractError("residual column names must be non-empty strings")
322
+ if output in chain.frame.columns and output not in {observed, expected}:
323
+ raise DataContractError(f"residual output column already exists: {output!r}")
324
+ missing = sorted({observed, expected}.difference(chain.frame.columns))
325
+ if missing:
326
+ raise DataContractError(f"residual inputs are missing: {', '.join(missing)}")
327
+ _require_numeric(chain.frame, (observed, expected))
328
+ if bool(
329
+ chain.frame.select(((pl.col(observed) <= 0.0) | (pl.col(expected) <= 0.0)).any()).item()
330
+ ):
331
+ raise DataContractError("observed and expected volatility must be positive")
332
+ frame = chain.frame.with_columns((pl.col(observed) - pl.col(expected)).alias(output))
333
+ residual: FloatArray = frame.get_column(output).to_numpy().astype(np.float64, copy=False)
334
+ groups = (
335
+ frame.group_by("time", "underlying", "expiration")
336
+ .agg(
337
+ pl.len().alias("quotes"),
338
+ pl.col(output).mean().alias("mean_residual"),
339
+ (pl.col(output).pow(2).mean().sqrt()).alias("rmse"),
340
+ )
341
+ .sort("time", "underlying", "expiration")
342
+ .to_dicts()
343
+ )
344
+ evidence = AnalysisResult(
345
+ metadata=ResultMetadata(
346
+ method="options.empirical_residual",
347
+ method_version=1,
348
+ parameters={
349
+ "observed_column": observed,
350
+ "expected_column": expected,
351
+ "output_column": output,
352
+ "definition": "observed_minus_expected",
353
+ },
354
+ ),
355
+ metrics={
356
+ "quote_count": residual.size,
357
+ "mean_residual": float(residual.mean()),
358
+ "median_residual": float(np.median(residual)),
359
+ "rmse": float(np.sqrt(np.mean(np.square(residual)))),
360
+ "positive_fraction": float(np.mean(residual > 0.0)),
361
+ },
362
+ tables={"surface_groups": tuple(cast(dict[str, JsonValue], row) for row in groups)},
363
+ )
364
+ return OptionFrameResult(frame=frame, evidence=evidence)
365
+
366
+
367
+ __all__ = [
368
+ "OPTIONAL_CHAIN_COLUMNS",
369
+ "REQUIRED_CHAIN_COLUMNS",
370
+ "OptionChain",
371
+ "OptionFrameResult",
372
+ "delta_buckets",
373
+ "empirical_residual",
374
+ "validate_chain",
375
+ ]
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.5
2
+ Name: lacuna-options
3
+ Version: 0.2.0
4
+ Summary: Optional empirical options-research contracts for Lacuna.
5
+ Project-URL: Changelog, https://github.com/eyenoticeall/Lacuna/blob/main/extensions/lacuna-options/CHANGELOG.md
6
+ Project-URL: Documentation, https://github.com/eyenoticeall/Lacuna/blob/main/docs/subsystems/options-extension.md
7
+ Project-URL: Repository, https://github.com/eyenoticeall/Lacuna
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: options,quantitative-research,validation,volatility
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: lacuna-quant<0.14,>=0.13
23
+ Requires-Dist: numpy>=2.0
24
+ Requires-Dist: polars>=1.30
25
+ Description-Content-Type: text/markdown
26
+
27
+ # lacuna-options
28
+
29
+ `lacuna-options` is the separately packaged empirical options-research extension for
30
+ [Lacuna](https://github.com/eyenoticeall/Lacuna). It does not add options, solver, or plotting
31
+ dependencies to Lacuna core.
32
+
33
+ The initial `0.1.x` contract provides:
34
+
35
+ - a normalized, point-in-time-conscious option-chain schema;
36
+ - validated bid/ask/mid and expiration invariants;
37
+ - carry-based forwards and log-forward moneyness;
38
+ - deterministic absolute-delta buckets; and
39
+ - structured empirical implied-volatility residual evidence.
40
+
41
+ Install the extension from PyPI. Its dependency resolves the compatible `lacuna-quant` core while
42
+ Python imports remain `lacuna_options` and `lacuna`:
43
+
44
+ ```bash
45
+ python -m pip install lacuna-options
46
+ ```
47
+
48
+ ```python
49
+ import lacuna_options as lo
50
+
51
+ chain = lo.validate_chain(option_quotes)
52
+ bucketed = lo.delta_buckets(chain)
53
+ residuals = lo.empirical_residual(chain, expected="fair_iv")
54
+ ```
55
+
56
+ The package does not claim a universal implied-volatility solver, Greeks model, surface fit, or
57
+ arbitrage-free calibration. Those depend on explicit model, day-count, exercise, settlement,
58
+ dividend, and numerical policies and belong in later separately versioned capabilities.
59
+
60
+ Version `0.2.0` preserves the exact `0.1.x` Python surface while moving dependency metadata to
61
+ `lacuna-quant>=0.13,<0.14`. The `0.2` fixture explicitly inherits the complete `0.1` contract.
62
+ Validated chain evidence is recognized by the required `options_evidence` capability in Lacuna's
63
+ standardized options audit profile.
@@ -0,0 +1,8 @@
1
+ lacuna_options/__init__.py,sha256=HuRav-4YPmcRIjipV1gESsDuJGRFxNzPIGjyWUcSueA,516
2
+ lacuna_options/_version.py,sha256=YEpgGuqb6l-NYsEQm3yeCh3Y57MMboEN6_RjggWLrJo,94
3
+ lacuna_options/chain.py,sha256=738jlCOi7wQjwnmiLoxqtjso7hqd-gymRAeUWfSJhE4,15212
4
+ lacuna_options/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
+ lacuna_options-0.2.0.dist-info/METADATA,sha256=F1sqBfWjudo4trju8-IWao0B1IEtv0dJg3cArr3Z40E,2687
6
+ lacuna_options-0.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ lacuna_options-0.2.0.dist-info/licenses/LICENSE,sha256=uEw4sKnvYq2lOINT71q9zvrue0ccv3Fr96KITev4ivg,1076
8
+ lacuna_options-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lacuna contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.