lacuna-options 0.2.0__tar.gz
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.
- lacuna_options-0.2.0/.gitignore +26 -0
- lacuna_options-0.2.0/CHANGELOG.md +68 -0
- lacuna_options-0.2.0/LICENSE +21 -0
- lacuna_options-0.2.0/PKG-INFO +63 -0
- lacuna_options-0.2.0/README.md +37 -0
- lacuna_options-0.2.0/pyproject.toml +74 -0
- lacuna_options-0.2.0/src/lacuna_options/__init__.py +23 -0
- lacuna_options-0.2.0/src/lacuna_options/_version.py +3 -0
- lacuna_options-0.2.0/src/lacuna_options/chain.py +375 -0
- lacuna_options-0.2.0/src/lacuna_options/py.typed +1 -0
- lacuna_options-0.2.0/tests/fixtures/public-api-v0.1.json +21 -0
- lacuna_options-0.2.0/tests/fixtures/public-api-v0.2.json +22 -0
- lacuna_options-0.2.0/tests/test_chain.py +241 -0
- lacuna_options-0.2.0/tests/test_properties.py +82 -0
- lacuna_options-0.2.0/tests/test_public_api.py +67 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
.DS_Store
|
|
2
|
+
|
|
3
|
+
# Python
|
|
4
|
+
__pycache__/
|
|
5
|
+
*.py[cod]
|
|
6
|
+
*.so
|
|
7
|
+
*.pyd
|
|
8
|
+
.coverage
|
|
9
|
+
.hypothesis/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
.ruff_cache/
|
|
13
|
+
.venv/
|
|
14
|
+
htmlcov/
|
|
15
|
+
|
|
16
|
+
# Rust and packaging
|
|
17
|
+
target/
|
|
18
|
+
dist/
|
|
19
|
+
|
|
20
|
+
# Documentation
|
|
21
|
+
site/
|
|
22
|
+
|
|
23
|
+
# Editors
|
|
24
|
+
.idea/
|
|
25
|
+
.vscode/
|
|
26
|
+
*.swp
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## [0.2.0] - 2026-08-27
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- Depend on `lacuna-quant>=0.13,<0.14`, preserving the `lacuna_options` import and the complete
|
|
10
|
+
`0.1.x` public API while severing dependency resolution from the unrelated PyPI `lacuna` project.
|
|
11
|
+
- License future `lacuna-options` distributions under MIT only and include the MIT text in wheel
|
|
12
|
+
and source archives. Previously published versions retain their original license grants.
|
|
13
|
+
|
|
14
|
+
## [0.1.6] - 2026-08-26
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.13` after the additive Lacuna `0.12`
|
|
19
|
+
factor-panel interoperability milestone passed the unchanged extension API and joint-install
|
|
20
|
+
gates.
|
|
21
|
+
|
|
22
|
+
## [0.1.5] - 2026-08-26
|
|
23
|
+
|
|
24
|
+
### Changed
|
|
25
|
+
|
|
26
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.12` after the additive Lacuna `0.11`
|
|
27
|
+
decay, diagnostic-projection, and event-study milestone passed the unchanged extension API,
|
|
28
|
+
property, packaging, and joint-install gates.
|
|
29
|
+
|
|
30
|
+
## [0.1.4] - 2026-08-26
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.11` after the additive Lacuna `0.10`
|
|
35
|
+
signal-transformation and evidence-rendering milestone passed the unchanged extension API,
|
|
36
|
+
property, packaging, and joint-install gates.
|
|
37
|
+
|
|
38
|
+
## [0.1.3] - 2026-08-26
|
|
39
|
+
|
|
40
|
+
### Changed
|
|
41
|
+
|
|
42
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.10` after the additive Lacuna `0.9`
|
|
43
|
+
migration, diagnostics, benchmark, and reference-coverage release passed the unchanged extension
|
|
44
|
+
API, property, coverage, profile-integration, packaging, and joint-install gates.
|
|
45
|
+
|
|
46
|
+
## [0.1.2] - 2026-08-26
|
|
47
|
+
|
|
48
|
+
### Changed
|
|
49
|
+
|
|
50
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.9` after the additive Lacuna `0.8`
|
|
51
|
+
standardized-audit release recognized real options evidence under the required options-profile
|
|
52
|
+
capability and passed the unchanged extension API, property, coverage, and joint-install gates.
|
|
53
|
+
|
|
54
|
+
## [0.1.1] - 2026-08-26
|
|
55
|
+
|
|
56
|
+
### Changed
|
|
57
|
+
|
|
58
|
+
- Expand the compatible core range to `lacuna>=0.5,<0.8` after the additive Lacuna `0.7` bundle
|
|
59
|
+
release passed the unchanged options API, property, coverage, and clean joint-install gates.
|
|
60
|
+
|
|
61
|
+
## [0.1.0] - 2026-08-26
|
|
62
|
+
|
|
63
|
+
### Added
|
|
64
|
+
|
|
65
|
+
- Add normalized option-chain validation with explicit quote, expiration, temporal, and optional
|
|
66
|
+
field contracts.
|
|
67
|
+
- Add carry-based forward and log-forward-moneyness derivation under a declared year basis.
|
|
68
|
+
- Add deterministic absolute-delta buckets and empirical implied-volatility residual evidence.
|
|
@@ -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.
|
|
@@ -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,37 @@
|
|
|
1
|
+
# lacuna-options
|
|
2
|
+
|
|
3
|
+
`lacuna-options` is the separately packaged empirical options-research extension for
|
|
4
|
+
[Lacuna](https://github.com/eyenoticeall/Lacuna). It does not add options, solver, or plotting
|
|
5
|
+
dependencies to Lacuna core.
|
|
6
|
+
|
|
7
|
+
The initial `0.1.x` contract provides:
|
|
8
|
+
|
|
9
|
+
- a normalized, point-in-time-conscious option-chain schema;
|
|
10
|
+
- validated bid/ask/mid and expiration invariants;
|
|
11
|
+
- carry-based forwards and log-forward moneyness;
|
|
12
|
+
- deterministic absolute-delta buckets; and
|
|
13
|
+
- structured empirical implied-volatility residual evidence.
|
|
14
|
+
|
|
15
|
+
Install the extension from PyPI. Its dependency resolves the compatible `lacuna-quant` core while
|
|
16
|
+
Python imports remain `lacuna_options` and `lacuna`:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
python -m pip install lacuna-options
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import lacuna_options as lo
|
|
24
|
+
|
|
25
|
+
chain = lo.validate_chain(option_quotes)
|
|
26
|
+
bucketed = lo.delta_buckets(chain)
|
|
27
|
+
residuals = lo.empirical_residual(chain, expected="fair_iv")
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The package does not claim a universal implied-volatility solver, Greeks model, surface fit, or
|
|
31
|
+
arbitrage-free calibration. Those depend on explicit model, day-count, exercise, settlement,
|
|
32
|
+
dividend, and numerical policies and belong in later separately versioned capabilities.
|
|
33
|
+
|
|
34
|
+
Version `0.2.0` preserves the exact `0.1.x` Python surface while moving dependency metadata to
|
|
35
|
+
`lacuna-quant>=0.13,<0.14`. The `0.2` fixture explicitly inherits the complete `0.1` contract.
|
|
36
|
+
Validated chain evidence is recognized by the required `options_evidence` capability in Lacuna's
|
|
37
|
+
standardized options audit profile.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "lacuna-options"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Optional empirical options-research contracts for Lacuna."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
keywords = ["options", "quantitative-research", "volatility", "validation"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"lacuna-quant>=0.13,<0.14",
|
|
28
|
+
"numpy>=2.0",
|
|
29
|
+
"polars>=1.30",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Changelog = "https://github.com/eyenoticeall/Lacuna/blob/main/extensions/lacuna-options/CHANGELOG.md"
|
|
34
|
+
Documentation = "https://github.com/eyenoticeall/Lacuna/blob/main/docs/subsystems/options-extension.md"
|
|
35
|
+
Repository = "https://github.com/eyenoticeall/Lacuna"
|
|
36
|
+
|
|
37
|
+
[tool.uv.sources]
|
|
38
|
+
lacuna-quant = { workspace = true }
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["src/lacuna_options"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.sdist]
|
|
44
|
+
include = [
|
|
45
|
+
"CHANGELOG.md",
|
|
46
|
+
"LICENSE",
|
|
47
|
+
"README.md",
|
|
48
|
+
"src/lacuna_options",
|
|
49
|
+
"tests",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
target-version = "py311"
|
|
54
|
+
line-length = 100
|
|
55
|
+
src = ["src", "tests"]
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint]
|
|
58
|
+
select = ["B", "E", "F", "I", "RUF", "SIM", "UP"]
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint.per-file-ignores]
|
|
61
|
+
"tests/**/*.py" = ["S101"]
|
|
62
|
+
|
|
63
|
+
[tool.mypy]
|
|
64
|
+
python_version = "3.12"
|
|
65
|
+
strict = true
|
|
66
|
+
files = ["src/lacuna_options"]
|
|
67
|
+
|
|
68
|
+
[[tool.mypy.overrides]]
|
|
69
|
+
module = ["numpy", "numpy.*"]
|
|
70
|
+
follow_imports = "skip"
|
|
71
|
+
|
|
72
|
+
[tool.pytest.ini_options]
|
|
73
|
+
addopts = "-ra --strict-config --strict-markers"
|
|
74
|
+
testpaths = ["tests"]
|
|
@@ -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,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,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"callables": [
|
|
3
|
+
{"module": "lacuna_options", "qualname": "OptionFrameResult", "signature": "(frame, evidence)"},
|
|
4
|
+
{"module": "lacuna_options", "qualname": "OptionChain", "signature": "(frame, evidence)"},
|
|
5
|
+
{"module": "lacuna_options", "qualname": "validate_chain", "signature": "(data, *, columns=None, year_basis=365.25)"},
|
|
6
|
+
{"module": "lacuna_options", "qualname": "delta_buckets", "signature": "(chain, *, edges=(0.0, 0.1, 0.25, 0.4, 0.6, 0.75, 0.9, 1.0))"},
|
|
7
|
+
{"module": "lacuna_options", "qualname": "empirical_residual", "signature": "(chain, *, observed='iv', expected='expected_iv', output='iv_residual')"}
|
|
8
|
+
],
|
|
9
|
+
"contract": "lacuna-options-public-api-v0.1",
|
|
10
|
+
"module_exports": [
|
|
11
|
+
"OPTIONAL_CHAIN_COLUMNS",
|
|
12
|
+
"REQUIRED_CHAIN_COLUMNS",
|
|
13
|
+
"OptionChain",
|
|
14
|
+
"OptionFrameResult",
|
|
15
|
+
"__version__",
|
|
16
|
+
"delta_buckets",
|
|
17
|
+
"empirical_residual",
|
|
18
|
+
"validate_chain"
|
|
19
|
+
],
|
|
20
|
+
"package_series": "0.1"
|
|
21
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"callables": [
|
|
3
|
+
{"module": "lacuna_options", "qualname": "OptionFrameResult", "signature": "(frame, evidence)"},
|
|
4
|
+
{"module": "lacuna_options", "qualname": "OptionChain", "signature": "(frame, evidence)"},
|
|
5
|
+
{"module": "lacuna_options", "qualname": "validate_chain", "signature": "(data, *, columns=None, year_basis=365.25)"},
|
|
6
|
+
{"module": "lacuna_options", "qualname": "delta_buckets", "signature": "(chain, *, edges=(0.0, 0.1, 0.25, 0.4, 0.6, 0.75, 0.9, 1.0))"},
|
|
7
|
+
{"module": "lacuna_options", "qualname": "empirical_residual", "signature": "(chain, *, observed='iv', expected='expected_iv', output='iv_residual')"}
|
|
8
|
+
],
|
|
9
|
+
"contract": "lacuna-options-public-api-v0.2",
|
|
10
|
+
"inherited_contracts": ["lacuna-options-public-api-v0.1"],
|
|
11
|
+
"module_exports": [
|
|
12
|
+
"OPTIONAL_CHAIN_COLUMNS",
|
|
13
|
+
"REQUIRED_CHAIN_COLUMNS",
|
|
14
|
+
"OptionChain",
|
|
15
|
+
"OptionFrameResult",
|
|
16
|
+
"__version__",
|
|
17
|
+
"delta_buckets",
|
|
18
|
+
"empirical_residual",
|
|
19
|
+
"validate_chain"
|
|
20
|
+
],
|
|
21
|
+
"package_series": "0.2"
|
|
22
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from datetime import UTC, date, datetime
|
|
5
|
+
|
|
6
|
+
import polars as pl
|
|
7
|
+
import pytest
|
|
8
|
+
from lacuna import standard_audit
|
|
9
|
+
from lacuna.exceptions import DataContractError, MethodContractError
|
|
10
|
+
|
|
11
|
+
from lacuna_options import OptionChain, delta_buckets, empirical_residual, validate_chain
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _chain_records() -> dict[str, list[object]]:
|
|
15
|
+
return {
|
|
16
|
+
"time": [date(2026, 1, 1), date(2026, 1, 1)],
|
|
17
|
+
"instrument": ["A-C", "A-P"],
|
|
18
|
+
"underlying": ["A", "A"],
|
|
19
|
+
"expiration": [date(2026, 7, 2), date(2026, 7, 2)],
|
|
20
|
+
"strike": [100.0, 90.0],
|
|
21
|
+
"option_type": ["call", "put"],
|
|
22
|
+
"bid": [4.0, 2.0],
|
|
23
|
+
"ask": [6.0, 4.0],
|
|
24
|
+
"underlying_price": [95.0, 95.0],
|
|
25
|
+
"rate": [0.05, 0.05],
|
|
26
|
+
"dividend": [0.01, 0.01],
|
|
27
|
+
"iv": [0.24, 0.30],
|
|
28
|
+
"delta": [0.45, -0.20],
|
|
29
|
+
"expected_iv": [0.20, 0.32],
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_validate_chain_derives_mid_forward_and_log_moneyness() -> None:
|
|
34
|
+
result = validate_chain(pl.DataFrame(_chain_records()), year_basis=365.25)
|
|
35
|
+
|
|
36
|
+
assert isinstance(result, OptionChain)
|
|
37
|
+
assert result.frame.get_column("mid").to_list() == [5.0, 3.0]
|
|
38
|
+
maturity = 182.0 / 365.25
|
|
39
|
+
expected_forward = 95.0 * math.exp((0.05 - 0.01) * maturity)
|
|
40
|
+
assert result.frame.get_column("time_to_expiry_years").to_list() == pytest.approx(
|
|
41
|
+
[maturity, maturity]
|
|
42
|
+
)
|
|
43
|
+
assert result.frame.get_column("forward").to_list() == pytest.approx(
|
|
44
|
+
[expected_forward, expected_forward]
|
|
45
|
+
)
|
|
46
|
+
assert result.frame.get_column("log_moneyness").to_list() == pytest.approx(
|
|
47
|
+
[math.log(100.0 / expected_forward), math.log(90.0 / expected_forward)]
|
|
48
|
+
)
|
|
49
|
+
assert result.evidence.metadata.parameters["mid_computed"] is True
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_validated_chain_enters_the_options_standardized_audit_profile() -> None:
|
|
53
|
+
chain = validate_chain(_chain_records())
|
|
54
|
+
|
|
55
|
+
report = standard_audit(results={"chain": chain.evidence}, scope="options")
|
|
56
|
+
requirement_rows = report.table("evidence_requirements")
|
|
57
|
+
assert isinstance(requirement_rows, list)
|
|
58
|
+
options_row = next(row for row in requirement_rows if row["capability"] == "options_evidence")
|
|
59
|
+
assert options_row["disposition"] == "required"
|
|
60
|
+
assert options_row["present"] is True
|
|
61
|
+
assert report.metrics["recognized_result_count"] == 1
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_validate_chain_supports_explicit_mapping_and_timezone_preservation() -> None:
|
|
65
|
+
source = pl.DataFrame(
|
|
66
|
+
{
|
|
67
|
+
"quote_time": [datetime(2026, 1, 1, tzinfo=UTC)],
|
|
68
|
+
"contract": ["A-C"],
|
|
69
|
+
"root": ["A"],
|
|
70
|
+
"expiry": [datetime(2026, 2, 1, tzinfo=UTC)],
|
|
71
|
+
"k": [100.0],
|
|
72
|
+
"right": ["call"],
|
|
73
|
+
"best_bid": [1.0],
|
|
74
|
+
"best_ask": [2.0],
|
|
75
|
+
"spot": [99.0],
|
|
76
|
+
"risk_free": [0.03],
|
|
77
|
+
"yield": [0.0],
|
|
78
|
+
}
|
|
79
|
+
).lazy()
|
|
80
|
+
mapping = {
|
|
81
|
+
"time": "quote_time",
|
|
82
|
+
"instrument": "contract",
|
|
83
|
+
"underlying": "root",
|
|
84
|
+
"expiration": "expiry",
|
|
85
|
+
"strike": "k",
|
|
86
|
+
"option_type": "right",
|
|
87
|
+
"bid": "best_bid",
|
|
88
|
+
"ask": "best_ask",
|
|
89
|
+
"underlying_price": "spot",
|
|
90
|
+
"rate": "risk_free",
|
|
91
|
+
"dividend": "yield",
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
result = validate_chain(source, columns=mapping)
|
|
95
|
+
|
|
96
|
+
assert result.frame.schema["time"].time_zone == "UTC" # type: ignore[union-attr]
|
|
97
|
+
assert result.frame.schema["expiration"].time_zone == "UTC" # type: ignore[union-attr]
|
|
98
|
+
assert result.evidence.metadata.parameters["materialized"] is True
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.parametrize(
|
|
102
|
+
("column", "value", "message"),
|
|
103
|
+
[
|
|
104
|
+
("expiration", date(2026, 1, 1), "strictly after"),
|
|
105
|
+
("strike", 0.0, "strikes and underlyings"),
|
|
106
|
+
("bid", -1.0, "quotes non-negative"),
|
|
107
|
+
("ask", 3.0, "bid <= ask"),
|
|
108
|
+
("option_type", "CALL", "explicit 'call' or 'put'"),
|
|
109
|
+
("iv", 0.0, "implied volatility must be positive"),
|
|
110
|
+
("delta", 1.1, "delta must lie"),
|
|
111
|
+
],
|
|
112
|
+
)
|
|
113
|
+
def test_validate_chain_rejects_invalid_market_contracts(
|
|
114
|
+
column: str,
|
|
115
|
+
value: object,
|
|
116
|
+
message: str,
|
|
117
|
+
) -> None:
|
|
118
|
+
records = _chain_records()
|
|
119
|
+
records[column][0] = value
|
|
120
|
+
if column == "ask":
|
|
121
|
+
records["bid"][0] = 4.0
|
|
122
|
+
with pytest.raises(DataContractError, match=message):
|
|
123
|
+
validate_chain(records)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_validate_chain_rejects_bad_mid_and_mixed_temporal_dtypes() -> None:
|
|
127
|
+
records = _chain_records()
|
|
128
|
+
records["mid"] = [10.0, 3.0]
|
|
129
|
+
with pytest.raises(DataContractError, match="inclusive bid/ask"):
|
|
130
|
+
validate_chain(records)
|
|
131
|
+
|
|
132
|
+
records = _chain_records()
|
|
133
|
+
records["expiration"] = [
|
|
134
|
+
datetime(2026, 7, 2, tzinfo=UTC),
|
|
135
|
+
datetime(2026, 7, 2, tzinfo=UTC),
|
|
136
|
+
]
|
|
137
|
+
with pytest.raises(DataContractError, match="same physical dtype"):
|
|
138
|
+
validate_chain(records)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_validate_chain_rejects_mapping_schema_and_physical_defects() -> None:
|
|
142
|
+
with pytest.raises(MethodContractError, match="canonical-to-source mapping"):
|
|
143
|
+
validate_chain(_chain_records(), columns=[("time", "date")]) # type: ignore[arg-type]
|
|
144
|
+
with pytest.raises(MethodContractError, match="non-empty string"):
|
|
145
|
+
validate_chain(_chain_records(), columns={"time": ""})
|
|
146
|
+
with pytest.raises(MethodContractError, match="unknown canonical"):
|
|
147
|
+
validate_chain(_chain_records(), columns={"unknown": "source"})
|
|
148
|
+
with pytest.raises(MethodContractError, match="map uniquely"):
|
|
149
|
+
validate_chain(_chain_records(), columns={"time": "instrument"})
|
|
150
|
+
|
|
151
|
+
records = _chain_records()
|
|
152
|
+
records.pop("strike")
|
|
153
|
+
with pytest.raises(DataContractError, match="missing required columns"):
|
|
154
|
+
validate_chain(records)
|
|
155
|
+
|
|
156
|
+
records = _chain_records()
|
|
157
|
+
records["strike"] = ["100", "90"]
|
|
158
|
+
with pytest.raises(DataContractError, match="invalid dtypes"):
|
|
159
|
+
validate_chain(records)
|
|
160
|
+
|
|
161
|
+
records = _chain_records()
|
|
162
|
+
records["strike"][0] = None
|
|
163
|
+
with pytest.raises(DataContractError, match="must not contain nulls"):
|
|
164
|
+
validate_chain(records)
|
|
165
|
+
|
|
166
|
+
records = _chain_records()
|
|
167
|
+
records["time"] = [1, 1]
|
|
168
|
+
records["expiration"] = [2, 2]
|
|
169
|
+
with pytest.raises(DataContractError, match="Date or Datetime"):
|
|
170
|
+
validate_chain(records)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_validate_chain_rejects_invalid_optional_nonnegative_fields_and_empty_input() -> None:
|
|
174
|
+
records = _chain_records()
|
|
175
|
+
records["gamma"] = [-0.1, 0.1]
|
|
176
|
+
with pytest.raises(DataContractError, match="must be non-negative"):
|
|
177
|
+
validate_chain(records)
|
|
178
|
+
|
|
179
|
+
with pytest.raises(DataContractError, match="at least one quote"):
|
|
180
|
+
validate_chain(pl.DataFrame(_chain_records()).clear())
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_delta_buckets_use_absolute_delta_and_closed_final_boundary() -> None:
|
|
184
|
+
records = _chain_records()
|
|
185
|
+
records["delta"] = [0.0, -1.0]
|
|
186
|
+
chain = validate_chain(records)
|
|
187
|
+
|
|
188
|
+
result = delta_buckets(chain, edges=(0.0, 0.25, 0.5, 1.0))
|
|
189
|
+
|
|
190
|
+
assert result.frame.get_column("delta_bucket").to_list() == ["[0.00,0.25)", "[0.50,1.00]"]
|
|
191
|
+
assert result.evidence.metrics["occupied_buckets"] == 2
|
|
192
|
+
with pytest.raises(MethodContractError, match="starting at 0 and ending at 1"):
|
|
193
|
+
delta_buckets(chain, edges=(0.1, 1.0))
|
|
194
|
+
with pytest.raises(MethodContractError, match="finite numeric boundaries"):
|
|
195
|
+
delta_buckets(chain, edges=(0.0, "middle", 1.0)) # type: ignore[arg-type]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_delta_buckets_require_validated_delta_evidence() -> None:
|
|
199
|
+
records = _chain_records()
|
|
200
|
+
records.pop("delta")
|
|
201
|
+
chain = validate_chain(records)
|
|
202
|
+
with pytest.raises(DataContractError, match="requires a validated delta"):
|
|
203
|
+
delta_buckets(chain)
|
|
204
|
+
with pytest.raises(MethodContractError, match="result of validate_chain"):
|
|
205
|
+
delta_buckets(object()) # type: ignore[arg-type]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def test_empirical_residual_reports_exact_observed_minus_expected_values() -> None:
|
|
209
|
+
chain = validate_chain(_chain_records())
|
|
210
|
+
|
|
211
|
+
result = empirical_residual(chain, expected="expected_iv")
|
|
212
|
+
|
|
213
|
+
assert result.frame.get_column("iv_residual").to_list() == pytest.approx([0.04, -0.02])
|
|
214
|
+
assert result.evidence.metrics["mean_residual"] == pytest.approx(0.01)
|
|
215
|
+
assert result.evidence.metrics["median_residual"] == pytest.approx(0.01)
|
|
216
|
+
assert result.evidence.metrics["rmse"] == pytest.approx(math.sqrt(0.001))
|
|
217
|
+
assert result.evidence.metrics["positive_fraction"] == 0.5
|
|
218
|
+
assert len(result.evidence.table("surface_groups")) == 1
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def test_empirical_residual_rejects_missing_nonpositive_and_overwrite_contracts() -> None:
|
|
222
|
+
chain = validate_chain(_chain_records())
|
|
223
|
+
with pytest.raises(DataContractError, match="inputs are missing"):
|
|
224
|
+
empirical_residual(chain, expected="missing")
|
|
225
|
+
with pytest.raises(DataContractError, match="already exists"):
|
|
226
|
+
empirical_residual(chain, expected="expected_iv", output="forward")
|
|
227
|
+
|
|
228
|
+
records = _chain_records()
|
|
229
|
+
records["expected_iv"][0] = 0.0
|
|
230
|
+
with pytest.raises(DataContractError, match="must be positive"):
|
|
231
|
+
empirical_residual(validate_chain(records), expected="expected_iv")
|
|
232
|
+
with pytest.raises(MethodContractError, match="result of validate_chain"):
|
|
233
|
+
empirical_residual(object()) # type: ignore[arg-type]
|
|
234
|
+
with pytest.raises(MethodContractError, match="non-empty strings"):
|
|
235
|
+
empirical_residual(chain, expected="")
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@pytest.mark.parametrize("year_basis", [True, 0.0, float("nan")])
|
|
239
|
+
def test_validate_chain_rejects_invalid_year_basis(year_basis: object) -> None:
|
|
240
|
+
with pytest.raises(MethodContractError, match="positive finite"):
|
|
241
|
+
validate_chain(_chain_records(), year_basis=year_basis) # type: ignore[arg-type]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from datetime import date, timedelta
|
|
5
|
+
|
|
6
|
+
import polars as pl
|
|
7
|
+
import pytest
|
|
8
|
+
from hypothesis import given
|
|
9
|
+
from hypothesis import strategies as st
|
|
10
|
+
|
|
11
|
+
from lacuna_options import empirical_residual, validate_chain
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@given(
|
|
15
|
+
spot=st.floats(min_value=1.0, max_value=10_000.0, allow_nan=False, allow_infinity=False),
|
|
16
|
+
strike=st.floats(min_value=1.0, max_value=10_000.0, allow_nan=False, allow_infinity=False),
|
|
17
|
+
rate=st.floats(min_value=-0.1, max_value=0.25, allow_nan=False, allow_infinity=False),
|
|
18
|
+
dividend=st.floats(min_value=-0.05, max_value=0.2, allow_nan=False, allow_infinity=False),
|
|
19
|
+
days=st.integers(min_value=1, max_value=3650),
|
|
20
|
+
)
|
|
21
|
+
def test_forward_and_log_moneyness_match_the_declared_equations(
|
|
22
|
+
spot: float,
|
|
23
|
+
strike: float,
|
|
24
|
+
rate: float,
|
|
25
|
+
dividend: float,
|
|
26
|
+
days: int,
|
|
27
|
+
) -> None:
|
|
28
|
+
start = date(2026, 1, 1)
|
|
29
|
+
frame = pl.DataFrame(
|
|
30
|
+
{
|
|
31
|
+
"time": [start],
|
|
32
|
+
"instrument": ["contract"],
|
|
33
|
+
"underlying": ["asset"],
|
|
34
|
+
"expiration": [start + timedelta(days=days)],
|
|
35
|
+
"strike": [strike],
|
|
36
|
+
"option_type": ["call"],
|
|
37
|
+
"bid": [1.0],
|
|
38
|
+
"ask": [2.0],
|
|
39
|
+
"underlying_price": [spot],
|
|
40
|
+
"rate": [rate],
|
|
41
|
+
"dividend": [dividend],
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
chain = validate_chain(frame)
|
|
46
|
+
expected_forward = spot * math.exp((rate - dividend) * days / 365.25)
|
|
47
|
+
|
|
48
|
+
assert chain.frame.item(0, "forward") == pytest.approx(expected_forward)
|
|
49
|
+
assert chain.frame.item(0, "log_moneyness") == pytest.approx(
|
|
50
|
+
math.log(strike / expected_forward)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@given(
|
|
55
|
+
observed=st.floats(min_value=0.01, max_value=5.0, allow_nan=False, allow_infinity=False),
|
|
56
|
+
expected=st.floats(min_value=0.01, max_value=5.0, allow_nan=False, allow_infinity=False),
|
|
57
|
+
)
|
|
58
|
+
def test_empirical_residual_is_exactly_observed_minus_expected(
|
|
59
|
+
observed: float,
|
|
60
|
+
expected: float,
|
|
61
|
+
) -> None:
|
|
62
|
+
start = date(2026, 1, 1)
|
|
63
|
+
chain = validate_chain(
|
|
64
|
+
{
|
|
65
|
+
"time": [start],
|
|
66
|
+
"instrument": ["contract"],
|
|
67
|
+
"underlying": ["asset"],
|
|
68
|
+
"expiration": [start + timedelta(days=30)],
|
|
69
|
+
"strike": [100.0],
|
|
70
|
+
"option_type": ["call"],
|
|
71
|
+
"bid": [1.0],
|
|
72
|
+
"ask": [2.0],
|
|
73
|
+
"underlying_price": [100.0],
|
|
74
|
+
"rate": [0.0],
|
|
75
|
+
"dividend": [0.0],
|
|
76
|
+
"iv": [observed],
|
|
77
|
+
"fair_iv": [expected],
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
result = empirical_residual(chain, expected="fair_iv")
|
|
82
|
+
assert result.frame.item(0, "iv_residual") == pytest.approx(observed - expected)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import inspect
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import lacuna_options
|
|
9
|
+
|
|
10
|
+
CONTRACT_PATH = Path(__file__).parent / "fixtures" / "public-api-v0.2.json"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _contract() -> dict[str, object]:
|
|
14
|
+
return json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _resolve(module_name: str, qualname: str) -> object:
|
|
18
|
+
value: object = importlib.import_module(module_name)
|
|
19
|
+
for part in qualname.split("."):
|
|
20
|
+
value = getattr(value, part)
|
|
21
|
+
return value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _signature(value: object) -> str:
|
|
25
|
+
signature = inspect.signature(value)
|
|
26
|
+
parameters = [
|
|
27
|
+
parameter.replace(annotation=inspect.Parameter.empty)
|
|
28
|
+
for parameter in signature.parameters.values()
|
|
29
|
+
]
|
|
30
|
+
return str(
|
|
31
|
+
signature.replace(
|
|
32
|
+
parameters=parameters,
|
|
33
|
+
return_annotation=inspect.Signature.empty,
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_root_exports_exactly_match_the_v0_2_contract() -> None:
|
|
39
|
+
expected = _contract()["module_exports"]
|
|
40
|
+
assert isinstance(expected, list)
|
|
41
|
+
assert lacuna_options.__all__ == expected
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_public_call_signatures_match_the_v0_2_contract() -> None:
|
|
45
|
+
callables = _contract()["callables"]
|
|
46
|
+
assert isinstance(callables, list)
|
|
47
|
+
observed = []
|
|
48
|
+
for item in callables:
|
|
49
|
+
assert isinstance(item, dict)
|
|
50
|
+
module_name = item["module"]
|
|
51
|
+
qualname = item["qualname"]
|
|
52
|
+
assert isinstance(module_name, str)
|
|
53
|
+
assert isinstance(qualname, str)
|
|
54
|
+
observed.append(
|
|
55
|
+
{
|
|
56
|
+
"module": module_name,
|
|
57
|
+
"qualname": qualname,
|
|
58
|
+
"signature": _signature(_resolve(module_name, qualname)),
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
assert observed == callables
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_v0_2_contract_inherits_the_complete_v0_1_api() -> None:
|
|
65
|
+
contract = _contract()
|
|
66
|
+
assert contract["package_series"] == "0.2"
|
|
67
|
+
assert contract["inherited_contracts"] == ["lacuna-options-public-api-v0.1"]
|