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/widb/client.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WIDB connection and OptionMetrics query helpers
|
|
3
|
+
===============================================
|
|
4
|
+
|
|
5
|
+
Wraps the ``wrds`` Python library to execute SQL queries against
|
|
6
|
+
the OptionMetrics (IvyDB) dataset into a :class:`openqdata.widb.WIDBClient` class
|
|
7
|
+
which provides access via the following functions:
|
|
8
|
+
|
|
9
|
+
* :meth:`openqdata.widb.WIDBClient.lookup_secid(ticker)`: look up the OptionMetrics secid for a given ticker symbol.
|
|
10
|
+
* :meth:`openqdata.widb.WIDBClient.zero_curve(date)`: fetch the zero-coupon yield curve for a given date.
|
|
11
|
+
* :meth:`openqdata.widb.WIDBClient.spot_price(secid, date)`: fetch the spot price of the underlying for a given secid and date.
|
|
12
|
+
* :meth:`openqdata.widb.WIDBClient.option_prices(secid, date)`: fetch raw option price records for a given secid and date.
|
|
13
|
+
* :meth:`openqdata.widb.WIDBClient.forward_prices(secid, date)`: fetch forward prices for a given secid and date
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import datetime as dt
|
|
19
|
+
import os as os
|
|
20
|
+
import warnings as warnings
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import pandas as pd
|
|
25
|
+
from cdxcore.subdir import SubDir, verify, version
|
|
26
|
+
from cdxcore.util import fmt_date, verify_inp
|
|
27
|
+
from cdxcore.verbose import Context
|
|
28
|
+
|
|
29
|
+
from openqdata import env
|
|
30
|
+
from openqdata.biz_calendar import to_date
|
|
31
|
+
from openqdata.widb.connection import WRDSConnection, connect_wrds
|
|
32
|
+
|
|
33
|
+
# Cache available table names per (library, username)
|
|
34
|
+
_TABLES_CACHE: dict[tuple[str, str], set[str]] = {}
|
|
35
|
+
|
|
36
|
+
def _pick_optionm_library(conn: WRDSConnection) -> str:
|
|
37
|
+
"""Pick an OptionMetrics library that exists for this WIDB account."""
|
|
38
|
+
libs = conn.list_libraries()
|
|
39
|
+
for lib in ("optionm_all", "optionm"):
|
|
40
|
+
if lib in libs:
|
|
41
|
+
return lib
|
|
42
|
+
raise RuntimeError(
|
|
43
|
+
"WIDB libraries do not include 'optionm_all' or 'optionm'. "
|
|
44
|
+
"Your WIDB account may not have OptionMetrics/IvyDB access."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
def _tables_in_library(conn: WRDSConnection, library: str) -> set[str]:
|
|
48
|
+
username = WIDBClient.credentials().username
|
|
49
|
+
key = (library, username)
|
|
50
|
+
if key not in _TABLES_CACHE:
|
|
51
|
+
_TABLES_CACHE[key] = set(conn.list_tables(library))
|
|
52
|
+
return _TABLES_CACHE[key]
|
|
53
|
+
|
|
54
|
+
def _resolve_table(
|
|
55
|
+
conn: WRDSConnection,
|
|
56
|
+
*,
|
|
57
|
+
logical: str,
|
|
58
|
+
candidates: list[str],
|
|
59
|
+
date: dt.date | None = None,
|
|
60
|
+
) -> str:
|
|
61
|
+
"""Resolve a logical table name to an existing qualified table.
|
|
62
|
+
|
|
63
|
+
OptionMetrics on WIDB is often year-partitioned (e.g. opprcd2010) and/or
|
|
64
|
+
uses base names without the "_all" suffix.
|
|
65
|
+
"""
|
|
66
|
+
lib = _pick_optionm_library(conn)
|
|
67
|
+
tables = _tables_in_library(conn, lib)
|
|
68
|
+
|
|
69
|
+
expanded: list[str] = []
|
|
70
|
+
for cand in candidates:
|
|
71
|
+
if "{year}" in cand:
|
|
72
|
+
if date is None:
|
|
73
|
+
raise ValueError(f"Table candidate '{cand}' requires a date/year")
|
|
74
|
+
expanded.append(cand.format(year=date.year))
|
|
75
|
+
else:
|
|
76
|
+
expanded.append(cand)
|
|
77
|
+
|
|
78
|
+
for name in expanded:
|
|
79
|
+
if name in tables:
|
|
80
|
+
return f"{lib}.{name}"
|
|
81
|
+
|
|
82
|
+
raise RuntimeError(
|
|
83
|
+
f"Could not resolve OptionMetrics table for '{logical}'. Tried: {expanded} in library '{lib}'. "
|
|
84
|
+
"Your WIDB account may not have the required dataset access, or the table names differ."
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@version("0.1")
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class WRDSCredentials:
|
|
90
|
+
""" WIDB login credentials read from environment variables. """
|
|
91
|
+
username: str #: User account name for `WIDB <https://wrds-www.wharton.upenn.edu/>`__. For live access, set the environment variable ``WRDS_USERNAME`` to your account name.
|
|
92
|
+
wrds_off: bool = False #: If ``True``, WIDB access is disabled. To disable WIDB access, set the environment variable ``WRDS_OFF`` to ``1``.
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def create() -> WRDSCredentials:
|
|
96
|
+
""" Returns :class:`WRDSCredentials` with WIDB credentials read from ``WRDS_USERNAME`` """
|
|
97
|
+
username = os.environ.get("WRDS_USERNAME", None)
|
|
98
|
+
wrds_off = os.environ.get("WRDS_OFF", None) == "1"
|
|
99
|
+
|
|
100
|
+
if username is None:
|
|
101
|
+
raise RuntimeError("For live access to WIDB, set the environment variable WRDS_USERNAME: currently " + ("not set" if username is None else f"'{username}'")+".")
|
|
102
|
+
if wrds_off:
|
|
103
|
+
warnings.warn("WIDB is disabled")
|
|
104
|
+
return WRDSCredentials(username=username,wrds_off=wrds_off)
|
|
105
|
+
|
|
106
|
+
@version("1.0", dependencies=[WRDSCredentials])
|
|
107
|
+
class WIDBClient(object):
|
|
108
|
+
"""
|
|
109
|
+
WIDB connectivity.
|
|
110
|
+
See `the IvyDB reference manual <https://wrds-www.wharton.upenn.edu/documents/1995/IvyDB_US_v6.0_Reference_Manual.pdf>`_ for details on the OptionMetrics dataset and table schemas.
|
|
111
|
+
|
|
112
|
+
Paramemers
|
|
113
|
+
----------
|
|
114
|
+
connect : bool, default ``False``
|
|
115
|
+
If True, establish the connection immediately. Otherwise, delay until the first query is executed.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
locations = env.locations("widb", default_fmt=SubDir.PANDAS_PARQUET)
|
|
119
|
+
|
|
120
|
+
_conn : WRDSConnection | None = None #: Active WIDB connection, or None if not connected.
|
|
121
|
+
_credentials : WRDSCredentials | None = None # Credentials for WIDB connection, read from environment variables when first needed.
|
|
122
|
+
|
|
123
|
+
OPTION_COLS = {
|
|
124
|
+
'symbol',
|
|
125
|
+
'optionid',
|
|
126
|
+
'am_settlement',
|
|
127
|
+
'cp_flag',
|
|
128
|
+
'exercise_style',
|
|
129
|
+
'strike_price',
|
|
130
|
+
'exdate',
|
|
131
|
+
'best_bid',
|
|
132
|
+
'best_offer',
|
|
133
|
+
'volume',
|
|
134
|
+
'open_interest',
|
|
135
|
+
'impl_volatility',
|
|
136
|
+
'delta',
|
|
137
|
+
'gamma',
|
|
138
|
+
'vega',
|
|
139
|
+
'theta',
|
|
140
|
+
'ss_flag',
|
|
141
|
+
'expiry_indicator',
|
|
142
|
+
'contract_size'}
|
|
143
|
+
""" Columns returned by option_prices() queries. """
|
|
144
|
+
|
|
145
|
+
def __init__(self, connect : bool = False):
|
|
146
|
+
""" Initialize """
|
|
147
|
+
if connect:
|
|
148
|
+
self.connect()
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def credentials() -> WRDSCredentials:
|
|
152
|
+
"""
|
|
153
|
+
Returns WIDB credentials read from environment variables.
|
|
154
|
+
|
|
155
|
+
At the moment this is just the ``username``.
|
|
156
|
+
"""
|
|
157
|
+
if WIDBClient._credentials is None:
|
|
158
|
+
WIDBClient._credentials = WRDSCredentials.create()
|
|
159
|
+
return WIDBClient._credentials
|
|
160
|
+
|
|
161
|
+
@staticmethod
|
|
162
|
+
def connect() -> WRDSConnection:
|
|
163
|
+
"""
|
|
164
|
+
Establish a WIDB connection if not already connected.
|
|
165
|
+
Returns a :class:`WRDSConnection` object.
|
|
166
|
+
|
|
167
|
+
Users usually do not have to call this function directly when using any of the
|
|
168
|
+
prepared cached functions below as those will obtain a connection
|
|
169
|
+
lazily themselves.
|
|
170
|
+
|
|
171
|
+
This function is provided for native WRDS access.
|
|
172
|
+
"""
|
|
173
|
+
env.require_live("WRDS IvyDB")
|
|
174
|
+
if WIDBClient._conn is None:
|
|
175
|
+
verify( not env.test_mode, "Attempted to connect to WRDS IvyDB in test mode. Set OQ_DATA_TEST_MODE=0 to enable connections." )
|
|
176
|
+
credentials = WIDBClient.credentials()
|
|
177
|
+
verify( not credentials.wrds_off, "Attempted to connect to WRDS IvyDB while WRDS IvyDB access is disabled. Set WRDS_OFF=0 to enable connections." )
|
|
178
|
+
try:
|
|
179
|
+
WIDBClient._conn = connect_wrds(credentials.username)
|
|
180
|
+
except EOFError as e:
|
|
181
|
+
raise RuntimeError(f"Failed to connect to WRDS with username '{credentials.username}' (EOFError). This is likely caused by too many connections from this account. (If you are using multi-processing, limit the number of processes to four or less)") from e
|
|
182
|
+
except Exception as e:
|
|
183
|
+
raise RuntimeError(f"Failed to connect to WRDS with username '{credentials.username}': {str(e)}") from e
|
|
184
|
+
return WIDBClient._conn
|
|
185
|
+
|
|
186
|
+
@locations.raw(fmt=SubDir.PICKLE).cache(
|
|
187
|
+
"0.2",
|
|
188
|
+
uid = "ticker_to_secid_map",
|
|
189
|
+
exclude_args=['self'])
|
|
190
|
+
def ticker_to_secid_map(self) -> dict[str, int]:
|
|
191
|
+
"""
|
|
192
|
+
Fetch a mapping of all tickers to secids from the securd table.
|
|
193
|
+
Use :meth:`openqdata.widb.client.WIDBClient.lookup_secid` for individual lookups, which is cached separately.
|
|
194
|
+
"""
|
|
195
|
+
conn = self.connect()
|
|
196
|
+
assert not conn is None, "WRDS connection is not established."
|
|
197
|
+
securd = _resolve_table(conn, logical="securd", candidates=["securd", "securd1"])
|
|
198
|
+
query = f"""
|
|
199
|
+
SELECT ticker, secid
|
|
200
|
+
FROM {securd}
|
|
201
|
+
"""
|
|
202
|
+
df = conn.raw_sql(query)
|
|
203
|
+
return dict(zip(df["ticker"], df["secid"], strict=True))
|
|
204
|
+
|
|
205
|
+
@version("0.3", dependencies=["ticker_to_secid_map"])
|
|
206
|
+
def lookup_secid(self, ticker: str) -> int:
|
|
207
|
+
"""Look up the OptionMetrics (IvyDB) secid for a given ticker.
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
ticker : str
|
|
212
|
+
Ticker symbol, e.g. 'SPX'.
|
|
213
|
+
|
|
214
|
+
Returns
|
|
215
|
+
-------
|
|
216
|
+
secid : int
|
|
217
|
+
The secid.
|
|
218
|
+
|
|
219
|
+
Raises
|
|
220
|
+
------
|
|
221
|
+
Not found: :class:`LookupError`
|
|
222
|
+
If the ticker is not found.
|
|
223
|
+
"""
|
|
224
|
+
ticker_map = self.ticker_to_secid_map()
|
|
225
|
+
secid = ticker_map.get(ticker, None)
|
|
226
|
+
if secid is None:
|
|
227
|
+
raise LookupError(f"Ticker '{ticker}' not found in OptionMetrics securd table.")
|
|
228
|
+
return int(secid)
|
|
229
|
+
|
|
230
|
+
@version("0.1", dependencies=[ticker_to_secid_map])
|
|
231
|
+
def lookup_ticker(self, secid: int) -> str:
|
|
232
|
+
"""Look up the ticker symbol for a given OptionMetrics (IvyDB) secid.
|
|
233
|
+
|
|
234
|
+
Parameters
|
|
235
|
+
----------
|
|
236
|
+
secid : int
|
|
237
|
+
The secid.
|
|
238
|
+
|
|
239
|
+
Returns
|
|
240
|
+
-------
|
|
241
|
+
ticker : str
|
|
242
|
+
Ticker symbol, e.g. 'SPX'.
|
|
243
|
+
|
|
244
|
+
Raises
|
|
245
|
+
------
|
|
246
|
+
Not found: :class:`LookupError`
|
|
247
|
+
If the secid is not found.
|
|
248
|
+
"""
|
|
249
|
+
verify_inp( isinstance(secid, int), f"'secid' must be an integer; found '{secid}' of type {type(secid)}")
|
|
250
|
+
ticker_map = self.ticker_to_secid_map()
|
|
251
|
+
for ticker, tsecod in ticker_map.items():
|
|
252
|
+
if int(tsecod) == secid:
|
|
253
|
+
return ticker
|
|
254
|
+
raise LookupError(f"SecID '{secid}' not found in OptionMetrics securd table.")
|
|
255
|
+
|
|
256
|
+
@locations.raw("options", fmt=SubDir.PANDAS_PARQUET).cache(
|
|
257
|
+
"0.4",
|
|
258
|
+
uid = lambda secid, date : f"{int(secid)}/{fmt_date(date)}",
|
|
259
|
+
exclude_args=['self', 'verbose'])
|
|
260
|
+
def options(
|
|
261
|
+
self,
|
|
262
|
+
secid: int,
|
|
263
|
+
date: dt.date,
|
|
264
|
+
*,
|
|
265
|
+
verbose: Context = Context.quiet
|
|
266
|
+
) -> pd.DataFrame:
|
|
267
|
+
"""Fetch all option price records for a given secid on a single date.
|
|
268
|
+
|
|
269
|
+
Columns returned are contained in :attr:`openqdata.widb.client.WIDBClient.OPTION_COLS`, which includes:
|
|
270
|
+
'symbol', 'optionid', 'am_settlement', 'cp_flag', 'exercise_style', 'strike_price', 'exdate', 'best_bid', 'best_offer', 'volume', 'open_interest', 'impl_volatility', 'delta', 'gamma', 'vega', 'theta', 'ss_flag', 'expiry_indicator', 'contract_size'.
|
|
271
|
+
See `the IvyDB reference manual <https://wrds-www.wharton.upenn.edu/documents/1995/IvyDB_US_v6.0_Reference_Manual.pdf>`_ page 20.
|
|
272
|
+
|
|
273
|
+
Parameters
|
|
274
|
+
----------
|
|
275
|
+
secid : int
|
|
276
|
+
OptionMetrics security ID. Use :meth:`openqdata.widb.client.WIDBClient.lookup_secid` to obtain the secid for a given ticker.
|
|
277
|
+
date : :class:`dt.date`
|
|
278
|
+
Observation date.
|
|
279
|
+
verbose : :class:`cdxcore.verbose.Context`, default :attr:`cdxcore.verbose.Context.quiet`
|
|
280
|
+
Channel to print verbosity information, if any.
|
|
281
|
+
|
|
282
|
+
Returns
|
|
283
|
+
-------
|
|
284
|
+
pd.DataFrame
|
|
285
|
+
Raw option prices for the date.
|
|
286
|
+
"""
|
|
287
|
+
verify_inp( isinstance(secid, int), f"'secid' must be an integer; found '{secid}'")
|
|
288
|
+
date = to_date(date)
|
|
289
|
+
secid = int(secid)
|
|
290
|
+
conn = self.connect()
|
|
291
|
+
assert not conn is None, "WIDB connection is not established."
|
|
292
|
+
|
|
293
|
+
opprcd = _resolve_table(
|
|
294
|
+
conn,
|
|
295
|
+
logical="opprcd",
|
|
296
|
+
candidates=["opprcd{year}", "opprcd"],
|
|
297
|
+
date=date,
|
|
298
|
+
)
|
|
299
|
+
query = f"""
|
|
300
|
+
SELECT
|
|
301
|
+
symbol,
|
|
302
|
+
optionid,
|
|
303
|
+
am_settlement,
|
|
304
|
+
cp_flag,
|
|
305
|
+
'E' AS exercise_style,
|
|
306
|
+
strike_price / 1000.0 AS strike_price,
|
|
307
|
+
exdate,
|
|
308
|
+
best_bid,
|
|
309
|
+
best_offer,
|
|
310
|
+
volume,
|
|
311
|
+
open_interest,
|
|
312
|
+
impl_volatility,
|
|
313
|
+
ss_flag,
|
|
314
|
+
delta,
|
|
315
|
+
gamma,
|
|
316
|
+
vega,
|
|
317
|
+
theta,
|
|
318
|
+
expiry_indicator,
|
|
319
|
+
contract_size
|
|
320
|
+
FROM {opprcd}
|
|
321
|
+
WHERE secid = {secid}
|
|
322
|
+
AND date = '{date}'
|
|
323
|
+
"""
|
|
324
|
+
verbose.write(lambda : f"Fetching option prices for secid {secid} on {date}.")
|
|
325
|
+
df = conn.raw_sql(query)
|
|
326
|
+
assert set(df.columns) <= self.OPTION_COLS, f"{secid} {date}: missing columns {sorted(self.OPTION_COLS-set(df.columns))}"
|
|
327
|
+
return df
|
|
328
|
+
|
|
329
|
+
@locations.raw("zero_curve", fmt=SubDir.PANDAS_PARQUET).cache(
|
|
330
|
+
"0.2",
|
|
331
|
+
uid = lambda date : f"{fmt_date(date)}",
|
|
332
|
+
exclude_args=['self','verbose'])
|
|
333
|
+
def zero_curve(
|
|
334
|
+
self,
|
|
335
|
+
date: dt.date,
|
|
336
|
+
*,
|
|
337
|
+
verbose: Context = Context.quiet,
|
|
338
|
+
) -> pd.DataFrame:
|
|
339
|
+
"""
|
|
340
|
+
Fetch the zero-coupon yield curve for a given date.
|
|
341
|
+
|
|
342
|
+
Returns columns: 'date', 'days', 'rate'
|
|
343
|
+
Rate is continuously compounded using ACT/365, i.e. ``df = exp(-rate * calendar_days/365)``.
|
|
344
|
+
|
|
345
|
+
Use :func:`openqdata.widb.client.interpolate_zero_curve`
|
|
346
|
+
to interpolate discount factors for specific days to expiry.
|
|
347
|
+
|
|
348
|
+
Parameters
|
|
349
|
+
----------
|
|
350
|
+
date : :class:`dt.date`
|
|
351
|
+
Observation date.
|
|
352
|
+
verbose : :class:`cdxcore.verbose.Context`, default ``Context.quiet``
|
|
353
|
+
Channel to print verbosity information, if any.
|
|
354
|
+
|
|
355
|
+
Returns
|
|
356
|
+
-------
|
|
357
|
+
Zero curve: :class:`pandas.DataFrame`
|
|
358
|
+
Zero-curve data. Use :func:`openqdata.widb.client.interpolate_zero_curve`
|
|
359
|
+
to interpolate discount factors for specific days to expiry.
|
|
360
|
+
"""
|
|
361
|
+
date = to_date(date)
|
|
362
|
+
conn = self.connect()
|
|
363
|
+
assert not conn is None, "WIDB connection is not established."
|
|
364
|
+
zerocd = _resolve_table(conn, logical="zerocd", candidates=["zerocd"])
|
|
365
|
+
query = f"""
|
|
366
|
+
SELECT date, days, rate
|
|
367
|
+
FROM {zerocd}
|
|
368
|
+
WHERE date = '{date}'
|
|
369
|
+
ORDER BY days
|
|
370
|
+
"""
|
|
371
|
+
verbose.write(lambda : f"Fetching USD zero curve for {date}.")
|
|
372
|
+
return conn.raw_sql(query)
|
|
373
|
+
|
|
374
|
+
@locations.raw("forwards", fmt=SubDir.PANDAS_PARQUET).cache(
|
|
375
|
+
"0.3",
|
|
376
|
+
uid = lambda secid, date : f"{int(secid)}/{fmt_date(date)}",
|
|
377
|
+
exclude_args=['self','verbose'])
|
|
378
|
+
def forwards(
|
|
379
|
+
self,
|
|
380
|
+
secid: int,
|
|
381
|
+
date: dt.date,
|
|
382
|
+
*,
|
|
383
|
+
verbose: Context = Context.quiet,
|
|
384
|
+
) -> pd.DataFrame:
|
|
385
|
+
"""Fetch forward prices for a given secid on a date.
|
|
386
|
+
|
|
387
|
+
Returns columns: date, exdate, am_settlement, forward_price
|
|
388
|
+
|
|
389
|
+
Parameters
|
|
390
|
+
----------
|
|
391
|
+
secid : int
|
|
392
|
+
OptionMetrics security ID. Use :meth:`openqdata.widb.client.WIDBClient.lookup_secid` to obtain the secid for a given ticker.
|
|
393
|
+
date : :class:`dt.date`
|
|
394
|
+
Observation date.
|
|
395
|
+
verbose : :class:`cdxcore.verbose.Context`, default ``Context.quiet``
|
|
396
|
+
Channel to print verbosity information, if any.
|
|
397
|
+
|
|
398
|
+
Returns
|
|
399
|
+
-------
|
|
400
|
+
Forward table: :class:`pandas.DataFrame`
|
|
401
|
+
Forward price data with columns ``date``, ``exdate``, ``am_settlement``, ``forward_price``.
|
|
402
|
+
"""
|
|
403
|
+
verify_inp( isinstance(secid, int), f"'secid' must be an integer; found '{secid}'")
|
|
404
|
+
date = to_date(date)
|
|
405
|
+
secid = int(secid)
|
|
406
|
+
conn = self.connect()
|
|
407
|
+
assert not conn is None, "WIDB connection is not established."
|
|
408
|
+
fwdprd = _resolve_table(
|
|
409
|
+
conn,
|
|
410
|
+
logical="fwdprd",
|
|
411
|
+
candidates=["fwdprd{year}", "fwdprd"],
|
|
412
|
+
date=date,
|
|
413
|
+
)
|
|
414
|
+
query = f"""
|
|
415
|
+
SELECT
|
|
416
|
+
date,
|
|
417
|
+
expiration AS exdate,
|
|
418
|
+
amsettlement AS am_settlement,
|
|
419
|
+
forwardprice AS forward_price
|
|
420
|
+
FROM {fwdprd}
|
|
421
|
+
WHERE secid = {secid}
|
|
422
|
+
AND date = '{date}'
|
|
423
|
+
"""
|
|
424
|
+
verbose.write(lambda : f"Fetching forward prices for secid {secid} on {date}.")
|
|
425
|
+
return conn.raw_sql(query)
|
|
426
|
+
|
|
427
|
+
@locations.raw("spot_price", fmt=SubDir.PICKLE).cache(
|
|
428
|
+
"0.2",
|
|
429
|
+
uid = lambda secid, date : f"{secid}/{fmt_date(date)}",
|
|
430
|
+
exclude_args=['self', 'verbose'])
|
|
431
|
+
def spot_price(
|
|
432
|
+
self,
|
|
433
|
+
secid: int,
|
|
434
|
+
date: dt.date,
|
|
435
|
+
*,
|
|
436
|
+
verbose: Context = Context.quiet,
|
|
437
|
+
) -> float:
|
|
438
|
+
"""Fetch the spot (close) price of the underlying for a given date.
|
|
439
|
+
|
|
440
|
+
Parameters
|
|
441
|
+
----------
|
|
442
|
+
secid : int
|
|
443
|
+
OptionMetrics security ID. Use :meth:`openqdata.widb.client.WIDBClient.lookup_secid` to obtain the secid for a given ticker.
|
|
444
|
+
date : :class:`dt.date`
|
|
445
|
+
Observation date.
|
|
446
|
+
verbose : :class:`cdxcore.verbose.Context`, default ``Context.quiet``
|
|
447
|
+
Channel to print verbosity information, if any.
|
|
448
|
+
|
|
449
|
+
Returns
|
|
450
|
+
-------
|
|
451
|
+
Spot : float
|
|
452
|
+
Spot price.
|
|
453
|
+
|
|
454
|
+
Raises
|
|
455
|
+
------
|
|
456
|
+
Spot not found: :class:`LookupError`
|
|
457
|
+
If no spot price is available. This likely means either the ``secid`` is not covered by Option Metrics,
|
|
458
|
+
or ``date`` is not a business day for this underlying.
|
|
459
|
+
"""
|
|
460
|
+
verify_inp( isinstance(secid, int), f"'secid' must be an integer; found '{secid}'")
|
|
461
|
+
date = to_date(date)
|
|
462
|
+
secid = int(secid)
|
|
463
|
+
conn = self.connect()
|
|
464
|
+
assert not conn is None, "WIDB connection is not established."
|
|
465
|
+
secprd = _resolve_table(
|
|
466
|
+
conn,
|
|
467
|
+
logical="secprd",
|
|
468
|
+
candidates=["secprd", "secprd{year}"],
|
|
469
|
+
date=date,
|
|
470
|
+
)
|
|
471
|
+
query = f"""
|
|
472
|
+
SELECT close
|
|
473
|
+
FROM {secprd}
|
|
474
|
+
WHERE secid = {secid}
|
|
475
|
+
AND date = '{date}'
|
|
476
|
+
"""
|
|
477
|
+
verbose.write(lambda : f"Fetching spot price for secid {secid} on {date}.")
|
|
478
|
+
df = conn.raw_sql(query)
|
|
479
|
+
if df.empty:
|
|
480
|
+
raise LookupError(f"No spot price found for secid {secid} on {date}.")
|
|
481
|
+
return float(df["close"].iloc[0])
|
|
482
|
+
|
|
483
|
+
@version("0.1")
|
|
484
|
+
def interpolate_zero_curve(
|
|
485
|
+
zero_curve: pd.DataFrame,
|
|
486
|
+
days_to_expiry: np.ndarray,
|
|
487
|
+
) -> np.ndarray:
|
|
488
|
+
"""
|
|
489
|
+
Interpolate discount factors from the zero-coupon curve using ACT/365.
|
|
490
|
+
|
|
491
|
+
Parameters
|
|
492
|
+
----------
|
|
493
|
+
zero_curve : :class:`pandas.DataFrame`
|
|
494
|
+
Must have columns ``days`` and ``rate``.
|
|
495
|
+
days_to_expiry : :class:`numpy.ndarray`
|
|
496
|
+
Calendar days to each expiry, as floats
|
|
497
|
+
|
|
498
|
+
Returns
|
|
499
|
+
-------
|
|
500
|
+
Discount factors: :class:`numpy.ndarray`
|
|
501
|
+
Discount factors ``exp(-rate * days / 365)``.
|
|
502
|
+
"""
|
|
503
|
+
assert "days" in zero_curve.columns and "rate" in zero_curve.columns, (
|
|
504
|
+
"zero_curve must have 'days' and 'rate' columns"
|
|
505
|
+
)
|
|
506
|
+
curve_days = zero_curve["days"].values.astype(float)
|
|
507
|
+
curve_rates = zero_curve["rate"].values.astype(float) # in pcnt e.g. 3 = 3%
|
|
508
|
+
dte_float = days_to_expiry.astype(float)
|
|
509
|
+
rates = np.interp(dte_float, curve_days, curve_rates)
|
|
510
|
+
return np.exp(-rates * dte_float / 36500.0)
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
if __name__ == "__main__":
|
|
515
|
+
from openqdata.cli import run_module
|
|
516
|
+
|
|
517
|
+
run_module(globals())
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""WRDS connection selection, including a Python 3.14 compatible transport.
|
|
2
|
+
|
|
3
|
+
The upstream WRDS SDK pins Pandas below 2.3. Python 3.14 uses a narrow
|
|
4
|
+
SQLAlchemy transport instead, preserving the three operations IvyDB needs.
|
|
5
|
+
Credentials use libpq's standard .pgpass / PGPASSFILE support; no secrets
|
|
6
|
+
are read into package configuration or persisted by this module.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
from sqlalchemy import create_engine, inspect, text
|
|
16
|
+
from sqlalchemy.engine import URL
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class WRDSConnection(Protocol):
|
|
20
|
+
"""Subset of the vendor connection interface used by the data client."""
|
|
21
|
+
|
|
22
|
+
def raw_sql(self, query: str) -> pd.DataFrame: ...
|
|
23
|
+
def list_libraries(self) -> list[str]: ...
|
|
24
|
+
def list_tables(self, library: str) -> list[str]: ...
|
|
25
|
+
def close(self) -> None: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PostgreSQLConnection:
|
|
29
|
+
"""Read WRDS using SQLAlchemy and libpq authentication, without SDK pins.
|
|
30
|
+
|
|
31
|
+
This is a data-query transport, not a replacement for all SDK features.
|
|
32
|
+
PGHOST, PGPORT and PGDATABASE may override the standard WRDS endpoint.
|
|
33
|
+
A configured .pgpass file (or PGPASSFILE) is required for password auth.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, username: str) -> None:
|
|
37
|
+
url = URL.create(
|
|
38
|
+
"postgresql+psycopg2", username=username,
|
|
39
|
+
host=os.environ.get("PGHOST", "wrds-pgdata.wharton.upenn.edu"),
|
|
40
|
+
port=int(os.environ.get("PGPORT", "9737")),
|
|
41
|
+
database=os.environ.get("PGDATABASE", "wrds"),
|
|
42
|
+
)
|
|
43
|
+
self.engine = create_engine(url, connect_args={"sslmode": "require", "connect_timeout": 30})
|
|
44
|
+
# Match the vendor SDK's eager connection check without issuing a query.
|
|
45
|
+
with self.engine.connect():
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def raw_sql(self, query: str) -> pd.DataFrame:
|
|
49
|
+
"""Execute a query and return vendor-compatible Pandas observations."""
|
|
50
|
+
with self.engine.connect() as connection:
|
|
51
|
+
return pd.read_sql_query(text(query), connection)
|
|
52
|
+
|
|
53
|
+
def list_libraries(self) -> list[str]:
|
|
54
|
+
"""List database schemas visible to the current account."""
|
|
55
|
+
return inspect(self.engine).get_schema_names()
|
|
56
|
+
|
|
57
|
+
def list_tables(self, library: str) -> list[str]:
|
|
58
|
+
"""List both physical tables and views in an IvyDB library."""
|
|
59
|
+
inspector = inspect(self.engine)
|
|
60
|
+
return sorted(set(inspector.get_table_names(schema=library)) | set(inspector.get_view_names(schema=library)))
|
|
61
|
+
|
|
62
|
+
def close(self) -> None:
|
|
63
|
+
"""Release connections owned by this transport."""
|
|
64
|
+
self.engine.dispose()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def connect_wrds(username: str) -> WRDSConnection:
|
|
68
|
+
"""Select the vendor SDK on 3.12/3.13 and the narrow transport on 3.14."""
|
|
69
|
+
if sys.version_info >= (3, 14):
|
|
70
|
+
return PostgreSQLConnection(username)
|
|
71
|
+
import wrds
|
|
72
|
+
return wrds.Connection(wrds_username=username)
|