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.
Files changed (75) hide show
  1. openqdata/README.md +5 -0
  2. openqdata/__init__.py +15 -0
  3. openqdata/arbfree/README.md +5 -0
  4. openqdata/arbfree/__init__.py +9 -0
  5. openqdata/arbfree/arbfree.py +1494 -0
  6. openqdata/arbfree/sanos.py +316 -0
  7. openqdata/arbfree/sanos_tools.py +958 -0
  8. openqdata/arbfree/tridiag.py +85 -0
  9. openqdata/benchmark/README.md +5 -0
  10. openqdata/benchmark/__init__.py +4 -0
  11. openqdata/biz_calendar.py +506 -0
  12. openqdata/cli.py +91 -0
  13. openqdata/env.py +112 -0
  14. openqdata/fred/README.md +5 -0
  15. openqdata/fred/__init__.py +14 -0
  16. openqdata/fred/client.py +57 -0
  17. openqdata/fred/rates.py +162 -0
  18. openqdata/massive/README.md +5 -0
  19. openqdata/massive/__init__.py +15 -0
  20. openqdata/massive/client.py +1183 -0
  21. openqdata/massive/expiries.py +242 -0
  22. openqdata/massive/options/README.md +5 -0
  23. openqdata/massive/options/__init__.py +6 -0
  24. openqdata/massive/options/contracts.py +610 -0
  25. openqdata/massive/processing.py +447 -0
  26. openqdata/massive/testing/README.md +5 -0
  27. openqdata/massive/testing/__init__.py +8 -0
  28. openqdata/massive/testing/generate.py +61 -0
  29. openqdata/massive/testing/scope.py +8 -0
  30. openqdata/massive/tickers/README.md +5 -0
  31. openqdata/massive/tickers/__init__.py +5 -0
  32. openqdata/massive/tickers/basics.py +66 -0
  33. openqdata/massive/tickers/data.py +362 -0
  34. openqdata/massive/tickers/filtered_history.py +260 -0
  35. openqdata/massive/trade_conds.py +324 -0
  36. openqdata/models/README.md +5 -0
  37. openqdata/models/__init__.py +4 -0
  38. openqdata/pool.py +34 -0
  39. openqdata/tickers/README.md +5 -0
  40. openqdata/tickers/__init__.py +13 -0
  41. openqdata/tickers/ticker_calendar.py +370 -0
  42. openqdata/utils/README.md +3 -0
  43. openqdata/utils/__init__.py +35 -0
  44. openqdata/utils/cvxpy.py +47 -0
  45. openqdata/utils/pd.py +125 -0
  46. openqdata/utils/pl.py +114 -0
  47. openqdata/vixdata/README.md +5 -0
  48. openqdata/vixdata/__init__.py +6 -0
  49. openqdata/vixdata/cboe.py +119 -0
  50. openqdata/vixdata/client.py +44 -0
  51. openqdata/vixdata/formula.py +132 -0
  52. openqdata/widb/README.md +5 -0
  53. openqdata/widb/__init__.py +25 -0
  54. openqdata/widb/arbfree.py +581 -0
  55. openqdata/widb/bad.py +69 -0
  56. openqdata/widb/client.py +517 -0
  57. openqdata/widb/connection.py +72 -0
  58. openqdata/widb/day.py +1098 -0
  59. openqdata/widb/fitstats.py +328 -0
  60. openqdata/widb/options_filter.py +338 -0
  61. openqdata/widb/sanos.py +96 -0
  62. openqdata/widb/testing/README.md +5 -0
  63. openqdata/widb/testing/__init__.py +0 -0
  64. openqdata/widb/testing/generate.py +45 -0
  65. openqdata/widb/testing/scope.py +8 -0
  66. openqdata/widb/timeseries.py +434 -0
  67. openqdata/yahoo/README.md +5 -0
  68. openqdata/yahoo/__init__.py +8 -0
  69. openqdata/yahoo/client.py +229 -0
  70. openqdata-0.3.0.dist-info/METADATA +103 -0
  71. openqdata-0.3.0.dist-info/RECORD +75 -0
  72. openqdata-0.3.0.dist-info/WHEEL +5 -0
  73. openqdata-0.3.0.dist-info/licenses/LICENSE +131 -0
  74. openqdata-0.3.0.dist-info/licenses/NOTICE +1 -0
  75. openqdata-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,96 @@
1
+ """Daily fits, linear or SANOS, to the reduced set: at most 1,000 options selected from the linearly fitted full book."""
2
+ from __future__ import annotations
3
+
4
+ import datetime as dt
5
+
6
+ import pandas as pd
7
+ from cdxcore.subdir import CacheMode, SubDir
8
+ from cdxcore.uniquehash import named_unique_filename48_8
9
+ from cdxcore.util import verify_inp
10
+ from cdxcore.verbose import Context
11
+
12
+ from openqdata import env
13
+ from openqdata.arbfree.arbfree import MkArbFree
14
+ from openqdata.widb.arbfree import (
15
+ arb_free_model_day,
16
+ fit_config,
17
+ fit_model,
18
+ fitted_rows,
19
+ mk_arb_free_day,
20
+ )
21
+ from openqdata.widb.day import SCHEMA_ENRICHED_DAY, ExpiryFilter, RawDayFilter
22
+ from openqdata.widb.options_filter import OptionsFilter, filter_options_day
23
+
24
+ _processing = env.locations("arbfree").processed
25
+
26
+
27
+ def _uid(kind):
28
+ return lambda ticker, d, raw_day_filter, expiry_filter, sanos, options_filter: (
29
+ f"{kind}/{named_unique_filename48_8(f'{raw_day_filter},{expiry_filter},{options_filter}', raw_day_filter, expiry_filter, options_filter)}/"
30
+ f"{named_unique_filename48_8(str(sanos), sanos)}/{ticker}/{d}")
31
+
32
+
33
+ def _selected(ticker, d, sanos, raw_day_filter, expiry_filter, options_filter, raise_if_bad_day, override_cache_mode, verbose):
34
+ """The reduced set: the benchmark linear fit of the full book (:func:`fit_config`), filtered by ``options_filter``."""
35
+ verify_inp(not options_filter.normalize, lambda: "Fits to the reduced set require native coordinates: use OptionsFilter(normalize=False)")
36
+ return filter_options_day(ticker, d, raw_day_filter=raw_day_filter,
37
+ expiry_filter=expiry_filter, mk_arb_free=fit_config(timeout_seconds=sanos.timeout_seconds),
38
+ options_filter=options_filter, raise_if_bad_day=raise_if_bad_day,
39
+ override_cache_mode=override_cache_mode, verbose=verbose)
40
+
41
+
42
+ @_processing(fmt=SubDir.PYTREE_HDF5).cache(
43
+ "0.1", dependencies=[mk_arb_free_day, filter_options_day, MkArbFree],
44
+ uid=_uid("fit_sanos_model_day"), exclude_args=["verbose", "raise_if_bad_day", "selected"],
45
+ )
46
+ def fit_sanos_model_day(ticker: str, d: dt.date, sanos: MkArbFree, *,
47
+ selected: pd.DataFrame | None = None,
48
+ raw_day_filter: RawDayFilter = RawDayFilter(),
49
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
50
+ options_filter: OptionsFilter = OptionsFilter(normalize=False),
51
+ raise_if_bad_day: bool = True,
52
+ override_cache_mode: CacheMode | None = None,
53
+ verbose: Context = Context.all) -> dict:
54
+ """Fitted model and fit statistics for the reduced set of one WIDB day.
55
+
56
+ This is the cached fit behind :func:`fit_sanos_day`; see :func:`openqdata.widb.arbfree.fit_model`
57
+ for the returned dictionary. ``selected`` optionally supplies the already computed selection.
58
+ """
59
+ if selected is None:
60
+ selected = _selected(ticker, d, sanos, raw_day_filter, expiry_filter, options_filter, raise_if_bad_day, override_cache_mode, verbose)
61
+ if selected is None or selected.empty:
62
+ return arb_free_model_day.__wrapped__(ticker, d, enriched_data=pd.DataFrame(columns=list(SCHEMA_ENRICHED_DAY)), verbose=verbose)
63
+ return fit_model(ticker, d, selected.loc[:, list(SCHEMA_ENRICHED_DAY)], sanos, verbose)
64
+
65
+
66
+ @_processing(fmt=SubDir.PANDAS_PARQUET).cache(
67
+ "0.2", dependencies=[mk_arb_free_day, filter_options_day, MkArbFree],
68
+ uid=_uid("fit_sanos_day"), exclude_args=["verbose", "raise_if_bad_day"],
69
+ )
70
+ def fit_sanos_day(ticker: str, d: dt.date, sanos: MkArbFree, *,
71
+ raw_day_filter: RawDayFilter = RawDayFilter(),
72
+ expiry_filter: ExpiryFilter = ExpiryFilter(),
73
+ options_filter: OptionsFilter = OptionsFilter(normalize=False),
74
+ raise_if_bad_day: bool = True,
75
+ override_cache_mode: CacheMode | None = None,
76
+ verbose: Context = Context.all) -> pd.DataFrame:
77
+ """Fitted rows of the reduced set of one WIDB day.
78
+
79
+ The output has the standard daily fitted-row schema. Its cache includes the
80
+ selection configuration, separately from full-book mk_arb_free_day entries.
81
+ With cacheonly a missing entry raises before any processing or fitting.
82
+ The fitted model itself is cached by :func:`fit_sanos_model_day`.
83
+ """
84
+ selected = _selected(ticker, d, sanos, raw_day_filter, expiry_filter, options_filter, raise_if_bad_day, override_cache_mode, verbose)
85
+ if selected is None or selected.empty:
86
+ return selected
87
+ fitted = fit_sanos_model_day(ticker, d, sanos, selected=selected, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter,
88
+ options_filter=options_filter, raise_if_bad_day=raise_if_bad_day,
89
+ override_cache_mode=override_cache_mode, verbose=verbose)
90
+ return fitted_rows(ticker, d, selected.loc[:, list(SCHEMA_ENRICHED_DAY)], fitted,
91
+ mode_surface=sanos.no_arb_mode == "surface", verbose=verbose)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ from openqdata.cli import run_module
96
+ run_module(globals())
@@ -0,0 +1,5 @@
1
+ # openqdata.widb.testing
2
+
3
+ Explicit, live generation of WIDB fixtures into an external data root. Never run by the offline test suite.
4
+
5
+ Documentation: [development.md](https://github.com/hansbuehler/openqdata/blob/main/docs/development.md)
File without changes
@@ -0,0 +1,45 @@
1
+ """
2
+ Generate WIDB test data
3
+ """
4
+
5
+
6
+ from cdxcore.verbose import Context
7
+
8
+ from openqdata import env # triggers construction of caches.
9
+ from openqdata.widb.testing.scope import DATES, TICKERS
10
+
11
+
12
+ def generate_day(ticker, d):
13
+ from openqdata.widb.arbfree import fit_config, mk_arb_free_day
14
+ from openqdata.widb.day import (
15
+ ExpiryFilter,
16
+ RawDayFilter,
17
+ collect_raw_day,
18
+ enrich_day,
19
+ )
20
+
21
+ raw_day_filter = RawDayFilter()
22
+ expiry_filter = ExpiryFilter()
23
+ mk_arb_free = fit_config()
24
+ verbose = Context.all
25
+
26
+ raw_day = collect_raw_day(ticker, d, raw_day_filter=raw_day_filter, verbose=verbose, raise_if_bad_day=False)
27
+ print(raw_day)
28
+
29
+ enr_day = enrich_day(ticker, d, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, verbose=verbose, raise_if_bad_day=False)
30
+ print(enr_day)
31
+
32
+ af_day = mk_arb_free_day(ticker, d, mk_arb_free=mk_arb_free, raw_day_filter=raw_day_filter, expiry_filter=expiry_filter, verbose=verbose, raise_if_bad_day=False)
33
+ print(af_day)
34
+
35
+ def main():
36
+ env.require_live("fixture generation")
37
+
38
+ for ticker in TICKERS:
39
+ for d in DATES:
40
+ print(f"Generating data for {ticker} {d}")
41
+ generate_day(ticker, d)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -0,0 +1,8 @@
1
+ """
2
+ WIDB Testing scope for locally stored sample testing data
3
+ """
4
+
5
+ from openqdata.biz_calendar import next_business_day
6
+
7
+ TICKERS = ["SPX", "AAPL"]
8
+ DATES = [next_business_day(d) for d in ["2005-11-18", "2024-03-04", "2025-01-02", "2024-12-24", "2010-07-06", "2011-07-06"]]
@@ -0,0 +1,434 @@
1
+ """
2
+ Timeseries of daily data per ticker
3
+ ===================================
4
+
5
+ Sampling daily data into a time series using :func:`build_time_series`.
6
+ This includes filtering and sampling the enriched day data for each day according to
7
+ the specified configuration, and optionally making the data arbitrage-free using :func:`mk_arb_free_day`.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math as math
12
+ import warnings as warnings
13
+ from dataclasses import dataclass
14
+ from typing import Mapping
15
+
16
+ import numpy as np
17
+ from cdxcore.err import verify_inp
18
+ from cdxcore.jcpool import JCPool
19
+ from cdxcore.pretty import PrettyObject
20
+ from cdxcore.subdir import CacheMode, CacheMustExistError
21
+ from cdxcore.uniquehash import named_unique_filename48_8
22
+ from cdxcore.util import fmt_big_byte_number, fmt_date, fmt_list
23
+ from cdxcore.verbose import Context
24
+ from cdxcore.version import version
25
+ from prettytable import PrettyTable
26
+
27
+ from openqdata.biz_calendar import DAYS_PER_YEAR, DateRange, count_business_days_between
28
+ from openqdata.pool import PoolConfig
29
+ from openqdata.widb.arbfree import fit_config
30
+ from openqdata.widb.bad import BAD
31
+ from openqdata.widb.day import (
32
+ RAW_PER_EXPIRY_FIELDS,
33
+ ExpiryFilter,
34
+ RawDayFilter,
35
+ SubDir,
36
+ WIDBClient,
37
+ )
38
+ from openqdata.widb.options_filter import (
39
+ SCHEMA_OPTION_DAY,
40
+ MkArbFree,
41
+ OptionsFilter,
42
+ _filter_options_day_num_options,
43
+ filter_options_day,
44
+ )
45
+
46
+ _processing_timeseries = WIDBClient.locations.processed("timeseries",fmt=SubDir.PANDAS_PARQUET)
47
+
48
+ @version("1.0", dependencies=[RawDayFilter, ExpiryFilter, MkArbFree, OptionsFilter] )
49
+ @dataclass(frozen=True)
50
+ class TimeSeriesDefinition:
51
+ """
52
+ User-definition of a time series for experimentation.
53
+ """
54
+ raw_day_filter : RawDayFilter = RawDayFilter() # Configuration for data collection for the raw day data for basic data cleaning using :func:`collect_raw_day`.
55
+ expiry_filter : ExpiryFilter = ExpiryFilter() # Filter for expiries to be able to compute implied forwards. This will be passed to :func:`enrich_day` for each day.
56
+ mk_arb_free : MkArbFree|None = fit_config() # Optional no-arbitrage fit, by default the benchmark linear fit; which generates per expiry a no-arb ``fit1`` between bid/ask, and for the entire surface ``fitX`` which
57
+ # may not fit within bid/ask. This function also generates a ``mask mask_arb_free`` field indicating which options were
58
+ # fitted successfully (those which were not showed actionable static arbitrage on a given expiry).
59
+ options_filter : OptionsFilter = OptionsFilter() # How many options to extract and how, every day using :func:`filter_options_day`.
60
+
61
+ def __str__(self):
62
+ return f"{self.raw_day_filter},{self.expiry_filter},{self.mk_arb_free},{self.options_filter}"
63
+
64
+ def _at_uid(ticker, date_range, time_series_def ) -> str:
65
+ ts_id = named_unique_filename48_8(str(time_series_def), time_series_def)
66
+ return f"{ts_id}/{ticker}/{str(date_range)}"
67
+
68
+ @_processing_timeseries(fmt=SubDir.PICKLE).cache( "0.1", dependencies=[_filter_options_day_num_options, TimeSeriesDefinition],uid=_at_uid )
69
+ def _assemble_time_series(*,
70
+ ticker : str,
71
+ date_range : DateRange,
72
+ time_series_def : TimeSeriesDefinition,
73
+ pool_config : PoolConfig = PoolConfig.off(),
74
+ skip_bad_days : bool = False,
75
+ override_cache_mode : CacheMode|None = None,
76
+ verbose : Context = Context.all ) -> PrettyObject:
77
+ """
78
+ Local wrapper to pre-compute daily data for a time series.
79
+ """
80
+
81
+ dates = sorted( set(date_range.get_business_days())-set(BAD.DAYS_ALL) )
82
+ tme = verbose.timer()
83
+
84
+ verbose.write(lambda: f"Generating daily data for {ticker} time series from {dates[0]} to {dates[-1]} {'excluding' if date_range.exclude_half_days else 'including'} half days:")
85
+ verbose.report(1,lambda: f"Options filter: {time_series_def.options_filter}")
86
+ if not time_series_def.mk_arb_free is None:
87
+ verbose.report(1,lambda: f"MkArbFree config: {time_series_def.mk_arb_free}")
88
+ verbose.report(1,lambda: f"Raw Day filter: {time_series_def.raw_day_filter}")
89
+ verbose.report(1,lambda: f"Expiry filter: {time_series_def.expiry_filter}")
90
+ verbose.report(1,lambda: f"Pool config: {pool_config}")
91
+
92
+ pool = JCPool(num_workers=pool_config.num_workers, threading=pool_config.threading)
93
+
94
+ cnt = 0
95
+ max_options = 0
96
+ fails = []
97
+ for d, cnt_options in pool.parallel( { d: pool.delayed(_filter_options_day_num_options)(
98
+ ticker=ticker,
99
+ d=d,
100
+ raw_day_filter=time_series_def.raw_day_filter,
101
+ expiry_filter=time_series_def.expiry_filter,
102
+ mk_arb_free=time_series_def.mk_arb_free,
103
+ options_filter=time_series_def.options_filter,
104
+ raise_if_bad_day=not skip_bad_days,
105
+ override_cache_mode=override_cache_mode,
106
+ verbose=None
107
+ ) for d in dates } ):
108
+ cnt += 1
109
+ if cnt_options is None:
110
+ fails.append(d)
111
+ else:
112
+ max_options = max(max_options, cnt_options)
113
+ if tme.interval_test(1.):
114
+ verbose.write(lambda: f"\rGenerating daily filtered options data for {ticker} date {cnt}/{len(dates)} {fmt_date(d)} @ {math.ceil(100 * cnt / len(dates))}%. Total run time so far: {tme}{'' if not fails else f', so far {len(fails)} failures'}... ", end='')
115
+
116
+ verbose.write(lambda: f"\rGenerated daily filtered options data {len(dates)} dates for {ticker} from {dates[0]} to {dates[-1]} {'excluding' if date_range.exclude_half_days else 'including'} half days. Maximum number of options is {int(max_options)}{'' if not fails else f', with {len(fails)} failures'}. This took {tme}.")
117
+ if fails:
118
+ raise RuntimeError(f"Failed to generate daily filtered options data for {ticker} for the following dates: {fmt_list(sorted(fails))}.")
119
+ return max_options
120
+
121
+ @version("1.0", dependencies=[TimeSeriesDefinition])
122
+ def build_time_series_uid(ticker, date_range, include_fields, exclude_fields, time_series_def ) -> str:
123
+ """ Returns a relative UID for a time series based on its definition and the requested fields. """
124
+ assert isinstance(time_series_def, TimeSeriesDefinition), f"Internal error: expected 'time_series_def' to be an instance of TimeSeriesDefinition, but got {type(time_series_def)}. Please contact the authors with an example."
125
+ ts_id = named_unique_filename48_8(str(time_series_def), time_series_def)
126
+ fl_id = f"incl_{fmt_list(sorted(include_fields))}," if not include_fields is None else "incl_all,"
127
+ fl_id += f"excl_{fmt_list(sorted(exclude_fields))}" if not exclude_fields is None else "excl_none"
128
+ fl_id = named_unique_filename48_8(fl_id, include_fields, exclude_fields)
129
+ return f"{ts_id}/{ticker}/{str(date_range)}/{fl_id}"
130
+
131
+ _PER_DAY_FIELDS = {'ticker','date','spot','spot_prev','spot_ref','spot_ret','time_y'} # not all fields are present, depending on settings
132
+
133
+ @_processing_timeseries(fmt=SubDir.PYTREE_HDF5).cache( "0.3", dependencies=[filter_options_day, build_time_series_uid],uid=build_time_series_uid )
134
+ def build_time_series(
135
+ ticker : str,
136
+ date_range : DateRange, *,
137
+ include_fields : set[str]|None,
138
+ exclude_fields : set[str]|None,
139
+ time_series_def : TimeSeriesDefinition,
140
+ pool_config : PoolConfig = PoolConfig.off(),
141
+ skip_bad_days : bool = False,
142
+ override_cache_mode : CacheMode|None = None,
143
+ verbose : Context = Context.all ) -> dict[str:np.array|str|type]:
144
+ """
145
+ Collect enriched data for a list of tickers and a date range.
146
+
147
+ This function collects daily data according to its ``raw_day_filter`` for the specified fields (which are usually defined by the target model).
148
+
149
+ Parameters
150
+ ----------
151
+ ticker : str
152
+ Ticker symbol, e.g. "SPX"
153
+ date_range : :class:`DateRange`
154
+ Date range for which to collect data. Only business days will be collected, and the date range can be configured to include or exclude half days.
155
+ include_fields : set[str] | None
156
+ Fields to include. If ``None``, all fields are included by default.
157
+ exclude_fields : set[str] | None
158
+ Fields to exclude, if ``include_fields`` is ``None``.
159
+ time_series_def : :class:`TimeSeriesDefinition`
160
+ Definition of the time series to be built, including the filters for data collection and sampling,
161
+ Includes:
162
+
163
+ * ``raw_day_filter`` of :class:`RawDayFilter`:
164
+ Configuration for data collection for the raw day data for basic data cleaning using :func:`collect_raw_day`.
165
+ * ``expiry_filter`` of :class:`ExpiryFilter`:
166
+ Filter for expiries to be able to compute implied forwards. This will be passed to :func:`enrich_day` for each day.
167
+ * ``mk_arb_free`` of :class:`MkArbFree` | None:
168
+ optional linear no-arbitrage filter which generates per expiry a no-arb ``fit1`` between bid/ask, and for the entire surface ``fitX`` which
169
+ may not fit within bid/ask. This function also generates a ``mask mask_arb_free`` field indicating which options were
170
+ fitted successfully (those which were not showed actionable static arbitrage on a given expiry).
171
+ * ``options_filter`` of :class:`OptionsFilter`:
172
+ How many options to extract and how, every day using :func:`filter_options_day`.
173
+
174
+ pool_config : :class:`PoolConfig`, default ``PoolConfig.off()``
175
+ Configuration for parallel processing. By default, no parallel processing is used.
176
+ skip_bad_days : bool, default ``False``
177
+ If ``False``, known bad days raise during daily processing. If ``True``, known bad days may return empty data.
178
+ Empty days are omitted from the packed result; unexpected processing errors still raise.
179
+ override_cache_mode : :class:`cdxcore.subdir.CacheMode` | None, default ``None``
180
+ If not ``None``, overrides the cache mode for the enriched day data. Set to ``"update"`` to refresh the underlying raw cache.
181
+ With caching off or read-only, daily frames are computed/read once and packed directly without a cache-write prerequisite.
182
+ verbose : :class:`cdxcore.verbose.Context`, default ``Context.all``
183
+ Verbose context for logging.
184
+
185
+ Returns
186
+ -------
187
+ Time series: dict[str:np.array|str|type]
188
+ A dictionary with the requested fields, up to the maximum number of options specified in ``options_filter``, for each business day in the date range.
189
+ The fields are returned as numpy arrays, and the date field is returned as a string in "YYYY-MM-DD" format
190
+ The data is filtered and sampled according to the specified configurations.
191
+ """
192
+
193
+ dates = sorted( set(date_range.get_business_days())-set(BAD.DAYS_ALL) )
194
+ if not dates:
195
+ raise RuntimeError(f"No eligible business days for {ticker} in {date_range} after excluding known bad days.")
196
+ source_schema = SCHEMA_OPTION_DAY(time_series_def.mk_arb_free, time_series_def.options_filter.normalize)
197
+ source_fields = set(source_schema) # what the source offers
198
+ applicable_fields= source_fields - {'call_symbol','put_symbol'}
199
+ available_fields = applicable_fields|{'is_valid','time_y'} # source + what we will generate
200
+
201
+ def get_fields():
202
+ if not exclude_fields is None:
203
+ verify_inp( not 'is_valid' in exclude_fields, lambda : f"'is_valid' cannot be excluded, as it is used for masking invalid options.")
204
+ verify_inp( set(exclude_fields) <= available_fields, lambda : f"'exclude_fields' unknown fields found: {sorted(set(exclude_fields) - available_fields)}. Available fields not yet selected: {sorted(available_fields - set(exclude_fields))}")
205
+ if not include_fields is None:
206
+ verify_inp( 'is_valid' in include_fields, lambda : f"'is_valid' must be included in the fields to include, as it is used for masking invalid options.")
207
+ verify_inp( set(include_fields) <= available_fields, lambda : f"'include_fields' unknown fields found: {sorted(set(include_fields) - available_fields)}. Available fields not yet selected: {sorted(available_fields - set(include_fields))}")
208
+
209
+ flds = {f for f in available_fields if f in include_fields} if include_fields is not None else available_fields
210
+ if exclude_fields is not None:
211
+ flds = flds - set(exclude_fields)
212
+ verify_inp( len(flds) > 0, lambda : "No fields left after applying include/exclude filters. "+\
213
+ f"Included fields: {sorted(include_fields) if include_fields is not None else 'all'}; "+\
214
+ f"excluded fields: {sorted(exclude_fields) if exclude_fields is not None else 'none'}; "+
215
+ f"available fields: {sorted(available_fields)}")
216
+ return set(flds)
217
+ requested_fields = get_fields() # what the caller wants. Must include 'is_valid' for masking.
218
+
219
+ # make sure all data exists
220
+ # this is in multi-processing mode
221
+ # --------------------------------
222
+
223
+ daily_cache_mode = CacheMode(override_cache_mode if override_cache_mode is not None else _processing_timeseries.cache_mode)
224
+ # Precompute only when daily results can be written and subsequently read.
225
+ # Otherwise load/compute each frame once and retain it directly in memory.
226
+ if daily_cache_mode.write:
227
+ _ = _assemble_time_series(
228
+ ticker=ticker,
229
+ date_range=date_range,
230
+ time_series_def=time_series_def,
231
+ pool_config=pool_config,
232
+ skip_bad_days=skip_bad_days,
233
+ override_cache_mode=override_cache_mode,
234
+ verbose=verbose
235
+ )
236
+
237
+ verbose.write(lambda: f"Aggregating {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}data for ticker {ticker} for {len(dates)} business days from {fmt_date(dates[0])} to {fmt_date(dates[-1])} {'excluding' if date_range.exclude_half_days else 'including'} half days:")
238
+ verbose.report(1,lambda: f"Options filter: {time_series_def.options_filter}")
239
+ if not time_series_def.mk_arb_free is None:
240
+ verbose.report(1,lambda: f"MkArbFree config: {time_series_def.mk_arb_free}")
241
+ verbose.report(1,lambda: f"Raw Day filter: {time_series_def.raw_day_filter}")
242
+ verbose.report(1,lambda: f"Expiry filter: {time_series_def.expiry_filter}")
243
+ verbose.report(1,lambda: f"Pool config: {pool_config}")
244
+ verbose.report(1,lambda: f"Requested fields: {fmt_list(sorted(requested_fields))}")
245
+
246
+ # load data into current process
247
+ # All data must exist
248
+ # --------------------------------
249
+
250
+ def load_data():
251
+
252
+ thread_pool = JCPool(num_workers=pool_config.num_workers, threading=True if daily_cache_mode.write else pool_config.threading)
253
+ results = {} # by date
254
+ max_options = 0
255
+
256
+ with verbose.write_t(lambda: f"Reading the generated {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched data for {ticker} in the main process... ", end='') as tme:
257
+ # read them back
258
+ def process(d):
259
+ try:
260
+ df = filter_options_day(
261
+ ticker=ticker, d=d,
262
+ raw_day_filter=time_series_def.raw_day_filter,
263
+ expiry_filter=time_series_def.expiry_filter,
264
+ mk_arb_free=time_series_def.mk_arb_free,
265
+ options_filter=time_series_def.options_filter,
266
+ override_cache_mode="cacheonly" if daily_cache_mode.write else daily_cache_mode,
267
+ raise_if_bad_day=False if daily_cache_mode.write else not skip_bad_days,
268
+ cache_generate_only=False,
269
+ verbose=Context.quiet )
270
+ except CacheMustExistError as e:
271
+ raise RuntimeError(f"Internal error: {ticker} {d}: expected {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched data to be available in the cache after generation, but it was not found. Please contact the authors with an example. Original error message: {str(e)}")
272
+ assert not df is None, f"Internal error: {ticker} {d}: {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enrich_day returned None after generation. Please contact the authors with an example."
273
+ assert set(df.columns) == set(source_fields), f"Internal error: {ticker} {d}: {sorted(source_fields)}, but found {sorted(df.columns)}."
274
+ assert not 'is_valid' in df.columns, f"Internal error: {ticker} {d}: 'is_valid' should not be included in the enriched day data"
275
+ assert not 'time_y' in df.columns, f"Internal error: {ticker} {d}: 'time_y' should not be included in the enriched day data"
276
+ return df
277
+
278
+ for d, df in thread_pool.parallel( { d: thread_pool.delayed(process)(d) for d in dates } ):
279
+ if df is None or df.empty:
280
+ warnings.warn(f"Warning: {ticker} {d}: no data after filtering for this day. This date will be skipped in the time series.")
281
+ continue
282
+ results[d] = df
283
+ if tme.interval_test(1.):
284
+ verbose.write(lambda: f"\rReading market data {len(results)}/{len(dates)} date {fmt_date(d)} for {ticker}. Total run time so far: {tme}... ", end='')
285
+ max_options = max(max_options, len(df))
286
+
287
+ max_options = int(max_options)
288
+ verbose.write(lambda: f"\rRead the generated {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched data for {ticker} in the main process; this took {tme}. Maximum number of options is {max_options}.", end='')
289
+
290
+ return results, max_options
291
+
292
+ results, max_num_options = load_data()
293
+ if not results:
294
+ raise RuntimeError(f"No option data remains for {ticker} in {date_range} after filtering and skipping empty days.")
295
+ num_steps = len(results)
296
+
297
+ # allocate memory
298
+ # ===============
299
+
300
+ with verbose.write_t(lambda: f"Generating time series for {num_steps} business days and at most {max_num_options} options per day for ticker {ticker}... ", end='') as tme:
301
+
302
+ def allocate():
303
+ df0 = results[list(results.keys())[0]] # touch one df to get the schema
304
+ dates = sorted(results)
305
+ r = PrettyObject()
306
+ r.ticker = ticker
307
+ r.dates = dates
308
+ r.is_valid = np.zeros((num_steps,max_num_options), dtype=np.bool_ )
309
+
310
+ if 'time_y' in requested_fields:
311
+ # business-day year fraction since the first date, consistent with 'tte_y = bdte / DAYS_PER_YEAR'
312
+ r.time_y = ( count_business_days_between( dates[0], np.asarray(dates, dtype="datetime64[D]") ) / DAYS_PER_YEAR ).astype(np.float32).reshape((num_steps,1))
313
+
314
+ src_request = sorted(requested_fields-{'is_valid','time_y'})
315
+ for c in src_request:
316
+ v = df0[c].to_numpy()
317
+ assert len(v.shape) == 1, f"Internal error: {ticker}: {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched DataFrame column '{c}' has unexpected shape. Expected 1D array, found shape {v.shape}. Please contact the authors with an example."
318
+ assert len(v) > 0 or c in _PER_DAY_FIELDS, f"Internal error: {ticker}: {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched DataFrame column '{c}' has no values. If this is a per-option field, it should have at least one value. If this is a per-day field, it should be present but can be empty. Please contact the authors with an example."
319
+ r[c] = np.zeros((num_steps, 1 if c in _PER_DAY_FIELDS else max_num_options), dtype=v.dtype)
320
+
321
+ for i, d in enumerate(dates):
322
+ df = results.pop(d)
323
+ ln = len(df)
324
+ r.is_valid[i,:ln] = True
325
+ for c in src_request:
326
+ v = df[c].to_numpy()
327
+ if c in _PER_DAY_FIELDS:
328
+ assert np.all( v[0] == v ), f"Internal error: {ticker} {d}: {'' if time_series_def.mk_arb_free is None else 'arbitrage-free '}enriched DataFrame column '{c}' has different values for different options, but it is expected to be a per-day field with the same value for all options. Please contact the authors with an example."
329
+ r[c][i,0] = v[0]
330
+ else:
331
+ r[c][i,:len(v)] = v
332
+
333
+ for k,v in r.items():
334
+ if k in ["ticker", "dates"]:
335
+ continue
336
+ if v.dtype == np.bool_:
337
+ continue
338
+ if v.dtype != np.dtype("O"):
339
+ try:
340
+ assert np.all( np.isfinite(v) ), f"Internal error: {ticker}: array for column '{k}' contains non-finite values. Please contact the authors with an example."
341
+ except TypeError as e:
342
+ raise RuntimeError(f"Internal error: {ticker}: failed to check for finite values in column '{k}' with dtype {v.dtype}. Please contact the authors with an example. Original error message: {str(e)}")
343
+ return r
344
+
345
+ r = allocate()
346
+
347
+ verbose.write(lambda: f"done; this took {tme}.", head=False)
348
+ if verbose.shall_report(2):
349
+ verbose.report(2, str(table_of_time_series(r)))
350
+
351
+ return dict(r) # for HDF5
352
+
353
+ def table_of_time_series( r : dict[str:np.array|str|type] ) -> PrettyTable:
354
+ """
355
+ Summarizes the sampled data from :func:`build_time_series` in a :class:`prettytable.PrettyTable`
356
+ which can be displayed in a Jupyter notebook or printed in the console.
357
+
358
+ The table includes the shape, dtype, size in bytes, mean, std, min and max for each field in the sampled data.
359
+ """
360
+ nsize = 0
361
+ tbl = PrettyTable()
362
+ tbl.field_names = ["Field", "Shape", "Dtype", "Size", "Mean", "Std", "Min", "Max" ]
363
+ is_valid = r['is_valid']
364
+
365
+ for k, v in r.items():
366
+ if k == "ticker":
367
+ continue
368
+ if isinstance(v, np.ndarray):
369
+ vlid = v[is_valid] if k!="is_valid" and v.shape==is_valid.shape else v
370
+ try:
371
+ vlid = vlid.astype(np.float64)
372
+ except Exception:
373
+ tbl.add_row( [k, v.shape, v.dtype, fmt_big_byte_number(v.nbytes), "", "", "", ""] )
374
+ nsize += v.nbytes
375
+ continue
376
+
377
+ m,s,mi,mx = np.mean(vlid), np.std(vlid), np.min(vlid), np.max(vlid)
378
+ tbl.add_row( [k, v.shape, v.dtype, fmt_big_byte_number(v.nbytes), f"{m:.4g}", f"{s:.4g}", f"{mi:.4g}", f"{mx:.4g}" ] )
379
+ nsize += v.nbytes
380
+ elif isinstance(v, list):
381
+ tbl.add_row([k, (len(v),), type(v[0]).__name__ if len(v) > 0 else "?", "", "", "", "", ""])
382
+ else:
383
+ tbl.add_row([k, str(v)[:10], "", "", "", "", "", ""])
384
+ tbl.add_row(["TOTAL", "", "", fmt_big_byte_number(nsize), "", "", "", ""])
385
+ return tbl
386
+
387
+ def extract_day_block( time_series : Mapping, isample : int, *fields, **rename_fields ) -> PrettyObject:
388
+ """
389
+ Extracts the data for a given sample (day) from the enriched day DataFrame, and organizes it in a PrettyObject with lists of strikes, bids, asks, expiries, etc. per expiry.
390
+ """
391
+
392
+ fields = sorted(set(fields)|set(rename_fields))
393
+ is_valid_t = time_series['is_valid'][isample,:].astype(bool, copy=False)
394
+ ttey_t = time_series['tte_y'][isample,:][is_valid_t]
395
+ slices = { k: time_series[k][isample,:] if k in _PER_DAY_FIELDS else time_series[k][isample,:][is_valid_t] for k in fields }
396
+
397
+ r = PrettyObject({ k: list() if not k in _PER_DAY_FIELDS else None for k in fields })
398
+
399
+ uttys = np.unique(ttey_t)
400
+ for utty in uttys:
401
+ mask = ttey_t == utty
402
+ if np.sum(mask) == 0:
403
+ continue
404
+ for k in fields:
405
+ v = np.asarray(slices[k] if k in _PER_DAY_FIELDS else slices[k][mask])
406
+ if k in _PER_DAY_FIELDS:
407
+ assert np.all( v[0] == v ), f"Internal error: expected all values for field '{k}' to be the same for the same day, but found different values: {v}. Please contact the authors with an example."
408
+ if r[k] is None:
409
+ r[k] = v[0]
410
+ assert np.all( r[k] == v ), f"Internal error: expected all values for field '{k}' to be the same for the same day, but found different values: {v}. Please contact the authors with an example."
411
+ elif k in RAW_PER_EXPIRY_FIELDS:
412
+ assert np.all( v[0] == v ), f"Internal error: expected all values for field '{k}' to be the same for the same day, but found different values: {v}. Please contact the authors with an example."
413
+ r[k].append(v[0])
414
+ else:
415
+ r[k].append(v)
416
+
417
+ for k in fields:
418
+ if k in _PER_DAY_FIELDS:
419
+ assert not r[k] is None
420
+ elif k in RAW_PER_EXPIRY_FIELDS:
421
+ r[k] = np.array(r[k])
422
+
423
+ if k in rename_fields:
424
+ new_name = rename_fields[k]
425
+ r[new_name] = r.pop(k)
426
+
427
+ return r
428
+
429
+
430
+
431
+ if __name__ == "__main__":
432
+ from openqdata.cli import run_module
433
+
434
+ run_module(globals())
@@ -0,0 +1,5 @@
1
+ # openqdata.yahoo
2
+
3
+ Yahoo Finance connector (`YFClient`): price history, dividends and earnings dates.
4
+
5
+ Documentation: [connectors/yahoo.md](https://github.com/hansbuehler/openqdata/blob/main/docs/connectors/yahoo.md)
@@ -0,0 +1,8 @@
1
+ """
2
+ Yahoo finance
3
+ """
4
+
5
+ from openqdata import env, SubDir, Context, version#NOQA
6
+ from openqdata.yahoo.client import YFClient
7
+
8
+ __all__ = ["YFClient"]