openqdata 0.3.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.
- openqdata/README.md +5 -0
- openqdata/__init__.py +15 -0
- openqdata/arbfree/README.md +5 -0
- openqdata/arbfree/__init__.py +9 -0
- openqdata/arbfree/arbfree.py +1494 -0
- openqdata/arbfree/sanos.py +316 -0
- openqdata/arbfree/sanos_tools.py +958 -0
- openqdata/arbfree/tridiag.py +85 -0
- openqdata/benchmark/README.md +5 -0
- openqdata/benchmark/__init__.py +4 -0
- openqdata/biz_calendar.py +506 -0
- openqdata/cli.py +91 -0
- openqdata/env.py +112 -0
- openqdata/fred/README.md +5 -0
- openqdata/fred/__init__.py +14 -0
- openqdata/fred/client.py +57 -0
- openqdata/fred/rates.py +162 -0
- openqdata/massive/README.md +5 -0
- openqdata/massive/__init__.py +15 -0
- openqdata/massive/client.py +1183 -0
- openqdata/massive/expiries.py +242 -0
- openqdata/massive/options/README.md +5 -0
- openqdata/massive/options/__init__.py +6 -0
- openqdata/massive/options/contracts.py +610 -0
- openqdata/massive/processing.py +447 -0
- openqdata/massive/testing/README.md +5 -0
- openqdata/massive/testing/__init__.py +8 -0
- openqdata/massive/testing/generate.py +61 -0
- openqdata/massive/testing/scope.py +8 -0
- openqdata/massive/tickers/README.md +5 -0
- openqdata/massive/tickers/__init__.py +5 -0
- openqdata/massive/tickers/basics.py +66 -0
- openqdata/massive/tickers/data.py +362 -0
- openqdata/massive/tickers/filtered_history.py +260 -0
- openqdata/massive/trade_conds.py +324 -0
- openqdata/models/README.md +5 -0
- openqdata/models/__init__.py +4 -0
- openqdata/pool.py +34 -0
- openqdata/tickers/README.md +5 -0
- openqdata/tickers/__init__.py +13 -0
- openqdata/tickers/ticker_calendar.py +370 -0
- openqdata/utils/README.md +3 -0
- openqdata/utils/__init__.py +35 -0
- openqdata/utils/cvxpy.py +47 -0
- openqdata/utils/pd.py +125 -0
- openqdata/utils/pl.py +114 -0
- openqdata/vixdata/README.md +5 -0
- openqdata/vixdata/__init__.py +6 -0
- openqdata/vixdata/cboe.py +119 -0
- openqdata/vixdata/client.py +44 -0
- openqdata/vixdata/formula.py +132 -0
- openqdata/widb/README.md +5 -0
- openqdata/widb/__init__.py +25 -0
- openqdata/widb/arbfree.py +581 -0
- openqdata/widb/bad.py +69 -0
- openqdata/widb/client.py +517 -0
- openqdata/widb/connection.py +72 -0
- openqdata/widb/day.py +1098 -0
- openqdata/widb/fitstats.py +328 -0
- openqdata/widb/options_filter.py +338 -0
- openqdata/widb/sanos.py +96 -0
- openqdata/widb/testing/README.md +5 -0
- openqdata/widb/testing/__init__.py +0 -0
- openqdata/widb/testing/generate.py +45 -0
- openqdata/widb/testing/scope.py +8 -0
- openqdata/widb/timeseries.py +434 -0
- openqdata/yahoo/README.md +5 -0
- openqdata/yahoo/__init__.py +8 -0
- openqdata/yahoo/client.py +229 -0
- openqdata-0.3.0.dist-info/METADATA +103 -0
- openqdata-0.3.0.dist-info/RECORD +75 -0
- openqdata-0.3.0.dist-info/WHEEL +5 -0
- openqdata-0.3.0.dist-info/licenses/LICENSE +131 -0
- openqdata-0.3.0.dist-info/licenses/NOTICE +1 -0
- openqdata-0.3.0.dist-info/top_level.txt +1 -0
openqdata/utils/pl.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Polars Utilities
|
|
3
|
+
================
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import polars as pl
|
|
13
|
+
from cdxcore.err import verify_inp
|
|
14
|
+
from cdxcore.util import fmt_list
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def create_empty_df(schema: Mapping[str, Any]) -> pl.DataFrame:
|
|
18
|
+
"""
|
|
19
|
+
Creates an empty :class:`polars.DataFrame` from a schema.
|
|
20
|
+
|
|
21
|
+
A schema is a dictionary of the form::
|
|
22
|
+
|
|
23
|
+
{
|
|
24
|
+
"col_a": pl.Float32,
|
|
25
|
+
"col_b": pl.Int64,
|
|
26
|
+
}
|
|
27
|
+
"""
|
|
28
|
+
assert isinstance(schema, Mapping), "schema must be a mapping of column name -> dtype"
|
|
29
|
+
return pl.DataFrame(schema=dict(schema))
|
|
30
|
+
|
|
31
|
+
def _as_polars_dtype(dtype: Any, *, col: str) -> pl.DataType:
|
|
32
|
+
try:
|
|
33
|
+
return pl.Series(col, [], dtype=dtype).dtype
|
|
34
|
+
except (TypeError, ValueError) as exc:
|
|
35
|
+
verify_inp(False, f"Invalid dtype for column {col!r}: {dtype!r}. Error: {exc}")
|
|
36
|
+
|
|
37
|
+
def verify_schema(
|
|
38
|
+
df: pl.DataFrame,
|
|
39
|
+
schema: Mapping[str, Any],
|
|
40
|
+
header: str | callable[[], str] | None = None,
|
|
41
|
+
*,
|
|
42
|
+
allow_extra_columns: bool = False,
|
|
43
|
+
) -> pl.DataFrame:
|
|
44
|
+
"""
|
|
45
|
+
Validate a :class:`polars.DataFrame` against a schema of the form::
|
|
46
|
+
|
|
47
|
+
{
|
|
48
|
+
"col_a": pl.Float32,
|
|
49
|
+
"col_b": pl.Int64,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
Checks:
|
|
53
|
+
- all schema columns exist
|
|
54
|
+
- no extra columns, unless allow_extra_columns=True
|
|
55
|
+
- exact dtype match
|
|
56
|
+
|
|
57
|
+
Returns df unchanged, so it can be used inline.
|
|
58
|
+
Raises :class:`ValueError` if validation fails. The error message will be
|
|
59
|
+
preceeded by ``header`` which can either be a string or a callable returning
|
|
60
|
+
a string (to avoid expensive message construction if validation passes).
|
|
61
|
+
|
|
62
|
+
Parameters
|
|
63
|
+
----------
|
|
64
|
+
df : :class:`polars.DataFrame`
|
|
65
|
+
Data frame to validate.
|
|
66
|
+
schema : Mapping[str, Any]
|
|
67
|
+
Mapping of column name to expected dtype.
|
|
68
|
+
header : str|callable[[],str]| None, optional
|
|
69
|
+
Header for error messages. Can be a string or a callable returning a string. Using a callable delays string composition to avoid unnecessary overhead when validation passes.
|
|
70
|
+
allow_extra_columns : bool, default False
|
|
71
|
+
Whether to allow columns in the DataFrame that are not in the schema.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def real_header():
|
|
75
|
+
if header is None:
|
|
76
|
+
return ""
|
|
77
|
+
elif isinstance(header, str):
|
|
78
|
+
return header + ": "
|
|
79
|
+
else:
|
|
80
|
+
return header() + ": "
|
|
81
|
+
|
|
82
|
+
assert isinstance(df, pl.DataFrame), f"{real_header()} must be a polars DataFrame"
|
|
83
|
+
assert isinstance(schema, Mapping), f"{real_header()}schema must be a mapping of column name -> dtype"
|
|
84
|
+
|
|
85
|
+
expected_cols = set(schema.keys())
|
|
86
|
+
actual_cols = set(df.columns)
|
|
87
|
+
|
|
88
|
+
missing = sorted(expected_cols - actual_cols)
|
|
89
|
+
extra = sorted(actual_cols - expected_cols)
|
|
90
|
+
|
|
91
|
+
if len(missing) > 0:
|
|
92
|
+
if len(extra) > 0:
|
|
93
|
+
raise ValueError(f"{real_header()}is missing columns: {fmt_list(missing)} and has extra columns: {fmt_list(extra)}.")
|
|
94
|
+
raise ValueError(f"{real_header()}is missing columns {fmt_list(missing)}.")
|
|
95
|
+
if len(extra) > 0 and not allow_extra_columns:
|
|
96
|
+
raise ValueError(f"{real_header()}has extra columns {fmt_list(extra)}.")
|
|
97
|
+
|
|
98
|
+
dtype_errors: list[str] = []
|
|
99
|
+
for col, expected_dtype_raw in schema.items():
|
|
100
|
+
if col not in df.columns:
|
|
101
|
+
continue
|
|
102
|
+
|
|
103
|
+
expected_dtype = _as_polars_dtype(expected_dtype_raw, col=col)
|
|
104
|
+
actual_dtype = df.schema[col]
|
|
105
|
+
|
|
106
|
+
if actual_dtype != expected_dtype:
|
|
107
|
+
dtype_errors.append(
|
|
108
|
+
f"{col!r}: expected {expected_dtype!r}, got {actual_dtype!r}"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
if dtype_errors:
|
|
112
|
+
raise ValueError(f"{real_header()} has schema mismatches: {fmt_list(dtype_errors)}.")
|
|
113
|
+
|
|
114
|
+
return df
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Download, validate, and cache official Cboe end-of-day VIX observations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import date, datetime, timezone
|
|
6
|
+
|
|
7
|
+
import polars as pl
|
|
8
|
+
import requests
|
|
9
|
+
from cdxcore.err import verify_inp
|
|
10
|
+
|
|
11
|
+
from openqdata import SubDir, env
|
|
12
|
+
|
|
13
|
+
CBOE_VIX_HISTORY_URL = "https://cdn.cboe.com/api/global/us_indices/daily_prices/VIX_History.csv"
|
|
14
|
+
_CACHE_VERSION = "1.0"
|
|
15
|
+
_locations = env.locations("vixdata", fmt_raw=SubDir.POLARS_PARQUET)
|
|
16
|
+
_raw_cache = _locations.raw
|
|
17
|
+
_DATA_FILE = "cboe/vix_eod"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _as_date(value: date | str | None, *, name: str) -> date | None:
|
|
21
|
+
if value is None or isinstance(value, date):
|
|
22
|
+
return value
|
|
23
|
+
try:
|
|
24
|
+
return date.fromisoformat(value)
|
|
25
|
+
except ValueError as error:
|
|
26
|
+
raise ValueError(f"{name} must be an ISO date, found {value!r}") from error
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def parse_cboe_vix_csv(content: bytes) -> pl.DataFrame:
|
|
30
|
+
"""Parse Cboe's daily OHLC CSV into ascending, validated observations."""
|
|
31
|
+
frame = pl.read_csv(content, try_parse_dates=False)
|
|
32
|
+
expected = ["DATE", "OPEN", "HIGH", "LOW", "CLOSE"]
|
|
33
|
+
if frame.columns != expected:
|
|
34
|
+
raise ValueError(f"unexpected Cboe VIX schema: {frame.columns}")
|
|
35
|
+
values = (
|
|
36
|
+
frame.with_columns(
|
|
37
|
+
pl.col("DATE").str.strptime(pl.Date, "%m/%d/%Y", strict=True).alias("date"),
|
|
38
|
+
*[pl.col(name).cast(pl.Float64, strict=True).alias(name.lower()) for name in expected[1:]],
|
|
39
|
+
)
|
|
40
|
+
.select("date", "open", "high", "low", "close")
|
|
41
|
+
.sort("date")
|
|
42
|
+
)
|
|
43
|
+
if values.is_empty() or values.null_count().sum_horizontal().item() != 0:
|
|
44
|
+
raise ValueError("Cboe VIX history is empty or has missing values")
|
|
45
|
+
if values.select(pl.any_horizontal(pl.all().exclude("date") <= 0.0).any()).item():
|
|
46
|
+
raise ValueError("Cboe VIX history has non-positive OHLC values")
|
|
47
|
+
# Cboe's early historical file contains a small number of OHLC rows whose
|
|
48
|
+
# intraday high/low do not bracket open or close. VIX *closes* are the
|
|
49
|
+
# data used by the models here, and remain well defined. Preserve the
|
|
50
|
+
# source OHLC columns for provenance, but do not reject valid EOD levels
|
|
51
|
+
# because of those vendor-history anomalies.
|
|
52
|
+
if values.select(pl.col("date").n_unique() != pl.len()).item():
|
|
53
|
+
raise ValueError("Cboe VIX history has duplicate dates")
|
|
54
|
+
return values
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def refresh_cboe_vix(*, timeout_seconds: float = 30.0) -> pl.DataFrame:
|
|
58
|
+
"""Fetch official Cboe VIX closes and replace the native raw-data cache.
|
|
59
|
+
|
|
60
|
+
The raw-data location is determined by ``openqdata.env``.
|
|
61
|
+
"""
|
|
62
|
+
env.require_live("Cboe")
|
|
63
|
+
verify_inp(timeout_seconds > 0.0, lambda: "timeout_seconds must be positive")
|
|
64
|
+
response = requests.get(
|
|
65
|
+
CBOE_VIX_HISTORY_URL,
|
|
66
|
+
headers={"User-Agent": "openqdata-vixdata/1.0"},
|
|
67
|
+
timeout=timeout_seconds,
|
|
68
|
+
)
|
|
69
|
+
response.raise_for_status()
|
|
70
|
+
values = parse_cboe_vix_csv(response.content)
|
|
71
|
+
_raw_cache.write(_DATA_FILE, values, version=_CACHE_VERSION)
|
|
72
|
+
_raw_cache.write(
|
|
73
|
+
"cboe/vix_eod_metadata",
|
|
74
|
+
{
|
|
75
|
+
"source": CBOE_VIX_HISTORY_URL,
|
|
76
|
+
"retrieved_at_utc": datetime.now(timezone.utc).isoformat(),
|
|
77
|
+
"observations": len(values),
|
|
78
|
+
"first_date": values["date"].min().isoformat(),
|
|
79
|
+
"last_date": values["date"].max().isoformat(),
|
|
80
|
+
"units": "annualized implied-volatility percentage points",
|
|
81
|
+
},
|
|
82
|
+
version=_CACHE_VERSION,
|
|
83
|
+
fmt=SubDir.JSON_PLAIN,
|
|
84
|
+
)
|
|
85
|
+
return values
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def load_cboe_vix(
|
|
89
|
+
start: date | str | None = None,
|
|
90
|
+
end: date | str | None = None,
|
|
91
|
+
*,
|
|
92
|
+
refresh: bool = False,
|
|
93
|
+
) -> pl.DataFrame:
|
|
94
|
+
"""Load cached official daily VIX OHLC observations, optionally refreshing.
|
|
95
|
+
|
|
96
|
+
``close`` is the official Cboe end-of-day VIX level, in annualized implied
|
|
97
|
+
volatility percentage points. The interval is inclusive.
|
|
98
|
+
"""
|
|
99
|
+
start_date = _as_date(start, name="start")
|
|
100
|
+
end_date = _as_date(end, name="end")
|
|
101
|
+
if start_date is not None and end_date is not None and start_date > end_date:
|
|
102
|
+
raise ValueError("start must not exceed end")
|
|
103
|
+
values = None if refresh else _raw_cache.read(_DATA_FILE, version=_CACHE_VERSION)
|
|
104
|
+
if values is None:
|
|
105
|
+
values = refresh_cboe_vix()
|
|
106
|
+
if not isinstance(values, pl.DataFrame):
|
|
107
|
+
raise RuntimeError("native Cboe VIX cache has an invalid type")
|
|
108
|
+
filters: list[pl.Expr] = []
|
|
109
|
+
if start_date is not None:
|
|
110
|
+
filters.append(pl.col("date") >= start_date)
|
|
111
|
+
if end_date is not None:
|
|
112
|
+
filters.append(pl.col("date") <= end_date)
|
|
113
|
+
return values.filter(*filters).sort("date") if filters else values
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
if __name__ == "__main__":
|
|
117
|
+
from openqdata.cli import run_module
|
|
118
|
+
|
|
119
|
+
run_module(globals())
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Cboe client for official end-of-day VIX history.
|
|
2
|
+
|
|
3
|
+
The Cboe history file is public; no credentials are required.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from datetime import date
|
|
9
|
+
|
|
10
|
+
import polars as pl
|
|
11
|
+
|
|
12
|
+
from openqdata import version
|
|
13
|
+
from openqdata.vixdata import cboe
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@version("0.1")
|
|
17
|
+
class CboeClient:
|
|
18
|
+
"""Cboe connectivity: cached official daily VIX observations.
|
|
19
|
+
|
|
20
|
+
Standard usage::
|
|
21
|
+
|
|
22
|
+
from openqdata.vixdata import CboeClient
|
|
23
|
+
vix = CboeClient().load_vix("2024-01-02", "2024-03-28")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
locations = cboe._locations
|
|
27
|
+
""" :class:`openqdata.Locations` for Cboe VIX data. """
|
|
28
|
+
|
|
29
|
+
URL = cboe.CBOE_VIX_HISTORY_URL #: Source of the official VIX history.
|
|
30
|
+
|
|
31
|
+
def refresh_vix(self, *, timeout_seconds: float = 30.0) -> pl.DataFrame:
|
|
32
|
+
"""Download the full history and replace the raw cache; refused in test mode."""
|
|
33
|
+
return cboe.refresh_cboe_vix(timeout_seconds=timeout_seconds)
|
|
34
|
+
|
|
35
|
+
def load_vix(self, start: date | str | None = None, end: date | str | None = None, *,
|
|
36
|
+
refresh: bool = False) -> pl.DataFrame:
|
|
37
|
+
"""Cached daily VIX OHLC in volatility points; see :func:`openqdata.vixdata.cboe.load_cboe_vix`."""
|
|
38
|
+
return cboe.load_cboe_vix(start, end, refresh=refresh)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
if __name__ == "__main__":
|
|
42
|
+
from openqdata.cli import run_module
|
|
43
|
+
|
|
44
|
+
run_module(globals())
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Cboe's discrete-strike VIX formula, independent of a pricing model.
|
|
2
|
+
|
|
3
|
+
Reference: https://cdn.cboe.com/resources/vix/VIX_Methodology.pdf
|
|
4
|
+
Prices are discounted currency prices; ``discount_factor`` is exp(-R*T).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from cdxcore.err import verify_inp
|
|
13
|
+
from numpy.typing import NDArray
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, kw_only=True)
|
|
17
|
+
class VixStrip:
|
|
18
|
+
"""Selected OTM contracts, including the averaged call/put at K0."""
|
|
19
|
+
|
|
20
|
+
indices: NDArray[np.int64]
|
|
21
|
+
strikes: NDArray[np.float64]
|
|
22
|
+
delta_strikes: NDArray[np.float64]
|
|
23
|
+
prices: NDArray[np.float64]
|
|
24
|
+
forward: float
|
|
25
|
+
k0: float
|
|
26
|
+
put_zero_bid_stop: float | None
|
|
27
|
+
call_zero_bid_stop: float | None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def select_vix_strip(
|
|
31
|
+
*,
|
|
32
|
+
strikes: NDArray[np.float64],
|
|
33
|
+
call_bids: NDArray[np.float64],
|
|
34
|
+
call_asks: NDArray[np.float64],
|
|
35
|
+
put_bids: NDArray[np.float64],
|
|
36
|
+
put_asks: NDArray[np.float64],
|
|
37
|
+
discount_factor: float,
|
|
38
|
+
) -> VixStrip:
|
|
39
|
+
"""Infer F by put-call parity and apply the two-consecutive-zero-bid rule.
|
|
40
|
+
|
|
41
|
+
Absent contracts are NaN, not zero bids. Invalid books break a consecutive
|
|
42
|
+
zero sequence; an absent contract is not a strike in that side's chain.
|
|
43
|
+
"""
|
|
44
|
+
strikes = np.asarray(strikes, dtype=np.float64)
|
|
45
|
+
books = [np.asarray(x, dtype=np.float64) for x in (call_bids, call_asks, put_bids, put_asks)]
|
|
46
|
+
verify_inp(strikes.ndim == 1 and len(strikes) >= 3,
|
|
47
|
+
lambda: "At least three strikes are required")
|
|
48
|
+
verify_inp(all(x.shape == strikes.shape for x in books), lambda: "Book shapes must match strikes")
|
|
49
|
+
verify_inp(np.all(np.isfinite(strikes)) and np.all(strikes > 0) and np.all(np.diff(strikes) > 0),
|
|
50
|
+
lambda: "Strikes must be finite, positive and strictly increasing")
|
|
51
|
+
verify_inp(np.isfinite(discount_factor) and discount_factor > 0, lambda: "Invalid discount factor")
|
|
52
|
+
cb, ca, pb, pa = books
|
|
53
|
+
valid_c = np.isfinite(cb) & np.isfinite(ca) & (cb >= 0) & (ca >= cb)
|
|
54
|
+
valid_p = np.isfinite(pb) & np.isfinite(pa) & (pb >= 0) & (pa >= pb)
|
|
55
|
+
calls, puts = (cb + ca) / 2, (pb + pa) / 2
|
|
56
|
+
paired = np.flatnonzero(valid_c & valid_p)
|
|
57
|
+
if not len(paired):
|
|
58
|
+
raise ValueError("No matched call/put book for the forward")
|
|
59
|
+
parity_index = paired[np.argmin(np.abs(calls[paired] - puts[paired]))]
|
|
60
|
+
forward = float(strikes[parity_index] + (calls[parity_index] - puts[parity_index]) / discount_factor)
|
|
61
|
+
below = np.flatnonzero(strikes <= forward)
|
|
62
|
+
if not len(below) or below[-1] == len(strikes) - 1:
|
|
63
|
+
raise ValueError("Available strikes do not bracket the inferred forward")
|
|
64
|
+
k0_index = int(below[-1])
|
|
65
|
+
if not (valid_c[k0_index] and valid_p[k0_index]):
|
|
66
|
+
raise ValueError("K0 does not have both a valid call and a valid put")
|
|
67
|
+
|
|
68
|
+
def wing(indices: range, bids: NDArray[np.float64], asks: NDArray[np.float64], valid: NDArray[np.bool_]) -> tuple[list[int], float | None]:
|
|
69
|
+
selected, zero_count = [], 0
|
|
70
|
+
for index in indices:
|
|
71
|
+
if not valid[index]:
|
|
72
|
+
if not (np.isnan(bids[index]) and np.isnan(asks[index])):
|
|
73
|
+
zero_count = 0
|
|
74
|
+
continue
|
|
75
|
+
if bids[index] == 0:
|
|
76
|
+
zero_count += 1
|
|
77
|
+
if zero_count == 2:
|
|
78
|
+
return selected, float(strikes[index])
|
|
79
|
+
else:
|
|
80
|
+
zero_count = 0
|
|
81
|
+
selected.append(index)
|
|
82
|
+
return selected, None
|
|
83
|
+
|
|
84
|
+
left, put_stop = wing(range(k0_index - 1, -1, -1), pb, pa, valid_p)
|
|
85
|
+
right, call_stop = wing(range(k0_index + 1, len(strikes)), cb, ca, valid_c)
|
|
86
|
+
indices = np.asarray(sorted(left + [k0_index] + right), dtype=np.int64)
|
|
87
|
+
if not left or not right:
|
|
88
|
+
raise ValueError("The selected strip must contain both OTM wings")
|
|
89
|
+
k = strikes[indices]
|
|
90
|
+
delta = np.empty_like(k)
|
|
91
|
+
delta[0], delta[-1] = k[1] - k[0], k[-1] - k[-2]
|
|
92
|
+
delta[1:-1] = (k[2:] - k[:-2]) / 2
|
|
93
|
+
q = np.where(indices < k0_index, puts[indices], calls[indices])
|
|
94
|
+
q[indices == k0_index] = (puts[k0_index] + calls[k0_index]) / 2
|
|
95
|
+
return VixStrip(indices=indices, strikes=k, delta_strikes=delta, prices=q,
|
|
96
|
+
forward=forward, k0=float(strikes[k0_index]),
|
|
97
|
+
put_zero_bid_stop=put_stop, call_zero_bid_stop=call_stop)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def discrete_total_variance(
|
|
101
|
+
strip: VixStrip, *, discount_factor: float, prices: NDArray[np.float64] | None = None,
|
|
102
|
+
) -> float:
|
|
103
|
+
"""Return T*sigma² = 2*sum(deltaK*Q/(DF*K²)) - (F/K0-1)²."""
|
|
104
|
+
q = strip.prices if prices is None else np.asarray(prices, dtype=np.float64)
|
|
105
|
+
verify_inp(q.shape == strip.strikes.shape and np.all(np.isfinite(q)) and np.all(q >= 0),
|
|
106
|
+
lambda: "Selected prices must be finite, non-negative and match the strip")
|
|
107
|
+
verify_inp(np.isfinite(discount_factor) and discount_factor > 0, lambda: "Invalid discount factor")
|
|
108
|
+
value = 2 * np.sum(strip.delta_strikes * q / (discount_factor * strip.strikes**2))
|
|
109
|
+
value -= (strip.forward / strip.k0 - 1)**2
|
|
110
|
+
if not np.isfinite(value) or value < 0:
|
|
111
|
+
raise ValueError(f"Invalid discrete total variance: {value}")
|
|
112
|
+
return float(value)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def constant_maturity_vix(
|
|
116
|
+
*, near_days: float, next_days: float, near_total_variance: float,
|
|
117
|
+
next_total_variance: float, target_days: float = 30.0,
|
|
118
|
+
) -> float:
|
|
119
|
+
"""Calendar-time interpolation of total variance, annualized ACT/365."""
|
|
120
|
+
verify_inp(0 < near_days <= target_days <= next_days and near_days < next_days,
|
|
121
|
+
lambda: "Expiries must bracket the target without extrapolation")
|
|
122
|
+
verify_inp(np.isfinite(near_total_variance) and np.isfinite(next_total_variance)
|
|
123
|
+
and min(near_total_variance, next_total_variance) >= 0,
|
|
124
|
+
lambda: "Invalid term variance")
|
|
125
|
+
weight = (target_days - near_days) / (next_days - near_days)
|
|
126
|
+
return float(100 * np.sqrt(((1 - weight) * near_total_variance + weight * next_total_variance) * 365 / target_days))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
if __name__ == "__main__":
|
|
130
|
+
from openqdata.cli import run_module
|
|
131
|
+
|
|
132
|
+
run_module(globals())
|
openqdata/widb/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# openqdata.widb
|
|
2
|
+
|
|
3
|
+
WRDS OptionMetrics IvyDB connector (`WIDBClient`) and the WIDB benchmark pipeline, which produces cleaned option data with an arbitrage-free interpolation: `day` (cleaning and enrichment), `arbfree` (fits to the full book and the batch command), `options_filter` (selection of the reduced set), `sanos` (fits to the reduced set), `fitstats` (fit statistics) and `timeseries` (packing).
|
|
4
|
+
|
|
5
|
+
Documentation: [the WIDB benchmark data](https://github.com/hansbuehler/openqdata/blob/main/docs/widb-benchmark/pipeline.md) and [the WIDB connector](https://github.com/hansbuehler/openqdata/blob/main/docs/connectors/widb.md)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WRDS Option Metric Ivy DB Data Module
|
|
3
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
4
|
+
|
|
5
|
+
Key entry points:
|
|
6
|
+
|
|
7
|
+
* :class:`WIDBClient`: main client for accessing cached raw WIDB data.
|
|
8
|
+
* :func:`collect_raw_day`: basic filtering and cleaning of raw daily WIDB data.
|
|
9
|
+
* :func:`enrich_day`: computation of implied forwards, implied vols, and greeks
|
|
10
|
+
* :func:`mk_arb_free_day` and :func:`fit_sanos_day`: arbitrage-free fits, linear or SANOS, to the full book and to the reduced set.
|
|
11
|
+
Strikes, and whole expiries, which cannot be fitted within bid/ask are masked or dropped.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from openqdata import env, SubDir, Context, version#NOQA
|
|
15
|
+
from openqdata.widb.client import WIDBClient, interpolate_zero_curve
|
|
16
|
+
|
|
17
|
+
__all__ = ["WIDBClient", "interpolate_zero_curve"]
|
|
18
|
+
|
|
19
|
+
_locations_widb = WIDBClient.locations
|
|
20
|
+
|
|
21
|
+
class _cli_defaults:
|
|
22
|
+
period = ("2005-01-01", "2025-09-01") #: Default start and end date for CLI commands.
|
|
23
|
+
workers = 4 #: Default number of workers for CLI commands.
|
|
24
|
+
|
|
25
|
+
|