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
openqdata/env.py ADDED
@@ -0,0 +1,112 @@
1
+ """Data locations configured by OQ_DATA_* variables or a TOML file.
2
+
3
+ Precedence: environment, explicit config, first discovered config, defaults.
4
+ Importing this module does not create directories or connect to providers.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import tomllib
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from cdxcore.err import verify_inp
14
+ from cdxcore.subdir import CacheController, SubDir
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Locations:
19
+ """Raw vendor observations and processed reusable data products."""
20
+
21
+ raw: SubDir
22
+ processed: SubDir
23
+
24
+ def __post_init__(self) -> None:
25
+ for name in ("raw", "processed"):
26
+ verify_inp(isinstance(getattr(self, name), SubDir), lambda: f"{name} must be a SubDir")
27
+
28
+ def __call__(self, name: str, *, default_fmt=None, fmt_raw=None, fmt_processed=None) -> Locations:
29
+ """Return source-specific locations, optionally selecting storage formats."""
30
+ verify_inp(bool(name) and not Path(name).is_absolute() and ".." not in Path(name).parts,
31
+ lambda: f"Invalid source subdirectory: {name!r}")
32
+ return Locations(
33
+ raw=self.raw(name, fmt=default_fmt if fmt_raw is None else fmt_raw, create_directory=False),
34
+ processed=self.processed(name, fmt=default_fmt if fmt_processed is None else fmt_processed, create_directory=False),
35
+ )
36
+
37
+ @staticmethod
38
+ def create_from_root(root: str | Path | SubDir) -> Locations:
39
+ """Describe the two locations below a root without creating files."""
40
+ root = SubDir(str(root) if isinstance(root, Path) else root, create_directory=False)
41
+ return Locations(root("raw", create_directory=False), root("processed", create_directory=False))
42
+
43
+
44
+ class Environment:
45
+ """Resolve storage once at import; construct another instance to reload settings.
46
+
47
+ Configuration uses a [data] table with root, raw, processed and cache_mode.
48
+ Relative paths in a configuration file resolve against that file's directory.
49
+ Test mode reads existing local fixtures with cacheonly and blocks providers.
50
+ """
51
+
52
+ CACHE_EXCLUDE_ARGS = ["self", "Context", "WRDSClient", "WIDBClient", "MassiveClient"]
53
+
54
+ def __init__(self, config_file: str | Path | None = None) -> None:
55
+ self.config_file: Path | None = None
56
+ explicit = config_file if config_file is not None else os.environ.get("OQ_DATA_CONFIG")
57
+ candidates = [Path(explicit).expanduser()] if explicit is not None else [
58
+ Path.cwd() / "openqdata.toml",
59
+ Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "openqdata/config.toml",
60
+ Path.home() / ".openqdata.toml",
61
+ ]
62
+ settings = {}
63
+ for candidate in candidates:
64
+ if candidate.is_file():
65
+ self.config_file = candidate.resolve()
66
+ with candidate.open("rb") as handle:
67
+ settings = tomllib.load(handle).get("data", {})
68
+ if not isinstance(settings, dict):
69
+ raise ValueError("The TOML [data] section must be a table")
70
+ unknown = settings.keys() - {"root", "raw", "processed", "cache_mode"}
71
+ if unknown:
72
+ raise ValueError(f"Unknown [data] settings: {sorted(unknown)}")
73
+ break
74
+ if explicit is not None and self.config_file is None:
75
+ raise FileNotFoundError(f"Configuration file does not exist: {explicit}")
76
+
77
+ def location(key: str, default: Path) -> Path:
78
+ value = os.environ.get(f"OQ_DATA_{key.upper()}")
79
+ configured = value is None and key in settings
80
+ value = settings.get(key, default) if value is None else value
81
+ if not isinstance(value, (str, Path)) or not str(value).strip():
82
+ raise ValueError(f"{key} must be a non-empty path")
83
+ path = Path(os.path.expandvars(str(value))).expanduser()
84
+ if configured and not path.is_absolute():
85
+ path = self.config_file.parent / path
86
+ return path.resolve()
87
+
88
+ mode = os.environ.get("OQ_DATA_TEST_MODE", "0")
89
+ if mode not in {"0", "1"}:
90
+ raise ValueError("OQ_DATA_TEST_MODE must be 0 or 1; fixture generation is explicit")
91
+ self.test_mode = mode == "1"
92
+ root = location("root", Path.home() / ".local/share/openqdata")
93
+ fixture_root = Path(os.environ.get("OQ_DATA_TEST_ROOT", Path(__file__).resolve().parents[2] / "tests/stored_data")).expanduser().resolve()
94
+ cache_mode = "cacheonly" if self.test_mode else os.environ.get("OQ_DATA_CACHE_MODE", settings.get("cache_mode", "on"))
95
+ controller = CacheController(exclude_arg_types=self.CACHE_EXCLUDE_ARGS, cache_mode=cache_mode)
96
+ self.locations = Locations(**{
97
+ name: SubDir(str(fixture_root / name if self.test_mode else location(name, root / name)),
98
+ cache_controller=controller, create_directory=False)
99
+ for name in ("raw", "processed")
100
+ })
101
+ if self.test_mode:
102
+ for name in ("raw", "processed"):
103
+ if not (fixture_root / name).is_dir():
104
+ raise FileNotFoundError(f"Missing local fixture directory: {fixture_root / name}")
105
+
106
+ def require_live(self, provider: str) -> None:
107
+ """Refuse provider access before credentials or network are consulted."""
108
+ if self.test_mode:
109
+ raise RuntimeError(f"{provider} access disabled by OQ_DATA_TEST_MODE=1; supply local fixtures")
110
+
111
+
112
+ env = Environment()
@@ -0,0 +1,5 @@
1
+ # openqdata.fred
2
+
3
+ FRED connector (`FREDClient`): SOFR, EFFR and short Treasury rates.
4
+
5
+ Documentation: [connectors/fred.md](https://github.com/hansbuehler/openqdata/blob/main/docs/connectors/fred.md)
@@ -0,0 +1,14 @@
1
+ """
2
+ openqdata.fred
3
+
4
+ FRED (Federal Reserve Economic Data) rates.
5
+ """
6
+
7
+ from openqdata.fred.client import FREDClient
8
+ from openqdata.fred.rates import (
9
+ TREASURY_SERIES,
10
+ load_fred_rates,
11
+ load_fred_treasury_curve,
12
+ )
13
+
14
+ __all__ = ["FREDClient", "TREASURY_SERIES", "load_fred_rates", "load_fred_treasury_curve"]
@@ -0,0 +1,57 @@
1
+ """FRED (Federal Reserve Economic Data) client.
2
+
3
+ Live access requires the ``FRED_API_KEY`` environment variable;
4
+ see https://fred.stlouisfed.org/docs/api/api_key.html.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from datetime import date
11
+
12
+ import polars as pl
13
+ from cdxcore.err import verify
14
+
15
+ from openqdata import env, version
16
+
17
+
18
+ @version("0.1")
19
+ class FREDClient:
20
+ """FRED connectivity: credentials and cached rate series.
21
+
22
+ Standard usage::
23
+
24
+ from openqdata.fred import FREDClient
25
+ rates = FREDClient().load_rates("2024-01-02", "2024-03-28")
26
+ """
27
+
28
+ locations = env.locations("fred")
29
+ """ :class:`openqdata.Locations` for FRED data. """
30
+
31
+ @staticmethod
32
+ def api_key() -> str:
33
+ """Return the FRED API key from ``FRED_API_KEY``; refuse in test mode."""
34
+ env.require_live("FRED")
35
+ key = os.environ.get("FRED_API_KEY")
36
+ verify(
37
+ key is not None,
38
+ "Please set FRED_API_KEY in your environment. See https://fred.stlouisfed.org/docs/api/api_key.html",
39
+ exception=RuntimeError,
40
+ )
41
+ return key
42
+
43
+ def fetch_series(self, series_id: str, start: date, end: date) -> pl.DataFrame:
44
+ """Download one FRED series without caching; ``"."`` observations become nulls."""
45
+ from openqdata.fred.rates import _fetch_fred_series
46
+ return _fetch_fred_series(self.api_key(), series_id, start, end)
47
+
48
+ def load_rates(self, start: str | date, end: str | date) -> pl.DataFrame:
49
+ """Cached SOFR, EFFR and short Treasury rates; see :func:`openqdata.fred.rates.load_fred_rates`."""
50
+ from openqdata.fred.rates import load_fred_rates
51
+ return load_fred_rates(start, end)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ from openqdata.cli import run_module
56
+
57
+ run_module(globals())
@@ -0,0 +1,162 @@
1
+ """
2
+ openqdata.fred.rates
3
+
4
+ Download SOFR, EFFR and Treasury rates from FRED.
5
+ Requires the ``FRED_API_KEY`` environment variable.
6
+ See https://fred.stlouisfed.org/docs/api/api_key.html
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import date
12
+
13
+ import polars as pl
14
+ import requests
15
+
16
+ from openqdata import env
17
+ from openqdata.fred.client import FREDClient
18
+
19
+ _fred_cache = FREDClient.locations.raw
20
+
21
+
22
+ def _redact(text: str, secret: str) -> str:
23
+ """Remove ``secret`` from ``text``."""
24
+ return text.replace(secret, "***") if secret else text
25
+
26
+
27
+ def _fetch_fred_series(api_key: str, series_id: str, start: date, end: date) -> pl.DataFrame:
28
+ env.require_live("FRED")
29
+ url = "https://api.stlouisfed.org/fred/series/observations"
30
+ params = {
31
+ "series_id": series_id,
32
+ "api_key": api_key,
33
+ "file_type": "json",
34
+ "observation_start": start.strftime("%Y-%m-%d"),
35
+ "observation_end": end.strftime("%Y-%m-%d"),
36
+ }
37
+ # FRED only accepts the key as a URL parameter. requests quotes the full URL in its exception
38
+ # messages, so failures are re-raised with a redacted message and without the original chain.
39
+ try:
40
+ r = requests.get(url, params=params, timeout=30)
41
+ r.raise_for_status()
42
+ obs = r.json().get("observations", [])
43
+ except requests.exceptions.RequestException as e:
44
+ # The response and request objects also carry the URL, so they are not attached.
45
+ simple = (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout)
46
+ cls = type(e) if isinstance(e, simple) else requests.exceptions.RequestException
47
+ raise cls(f"FRED request for {series_id} failed: {_redact(str(e), api_key)}") from None
48
+
49
+ if not obs:
50
+ return pl.DataFrame(
51
+ {"date": pl.Series([], dtype=pl.Date), series_id: pl.Series([], dtype=pl.Float64)}
52
+ )
53
+
54
+ df = pl.DataFrame(obs).select(
55
+ pl.col("date").str.strptime(pl.Date, "%Y-%m-%d").alias("date"),
56
+ pl.col("value").alias(series_id),
57
+ )
58
+ df = df.with_columns(
59
+ pl.when(pl.col(series_id) == ".").then(None).otherwise(pl.col(series_id)).alias(series_id)
60
+ ).with_columns(pl.col(series_id).cast(pl.Float64))
61
+ return df
62
+
63
+
64
+ @_fred_cache.cache("0.3", uid=lambda start, end: f"fred/{start}_{end}")
65
+ def load_fred_rates(start: str | date, end: str | date) -> pl.DataFrame:
66
+ """
67
+ Download SOFR, EFFR, DGS1MO, DGS3MO, DGS6MO from FRED and return as unscaled floats.
68
+
69
+ Adds ``on`` column defined as SOFR when available, otherwise EFFR, otherwise DGS1MO.
70
+ Only returns dates that have at least one observed rate, including zero or negative rates. All rate columns are
71
+ forward-filled so there are no trailing nulls.
72
+
73
+ Requires ``FRED_API_KEY`` environment variable.
74
+
75
+ Parameters
76
+ ----------
77
+ start : str | date
78
+ end : str | date
79
+
80
+ Returns
81
+ -------
82
+ pl.DataFrame
83
+ Columns: date, on, sofr, effr, dgs1mo, dgs3mo, dgs6mo (all Float32, unscaled e.g. 0.05 for 5%)
84
+ """
85
+ start = start if not isinstance(start, str) else date.fromisoformat(start)
86
+ end = end if not isinstance(end, str) else date.fromisoformat(end)
87
+ api_key = FREDClient.api_key()
88
+
89
+ series = ["SOFR", "EFFR", "DGS1MO", "DGS3MO", "DGS6MO"]
90
+ dfs = [_fetch_fred_series(api_key=api_key, series_id=s, start=start, end=end) for s in series]
91
+
92
+ df = dfs[0]
93
+ for other in dfs[1:]:
94
+ df = df.join(other, on="date", how="full", coalesce=True)
95
+
96
+ df = df.sort("date")
97
+
98
+ rate_cols = ["sofr", "effr", "dgs1mo", "dgs3mo", "dgs6mo"]
99
+ df = df.with_columns(
100
+ (pl.col("SOFR") / 100.0).cast(pl.Float32).alias("sofr"),
101
+ (pl.col("EFFR") / 100.0).cast(pl.Float32).alias("effr"),
102
+ (pl.col("DGS1MO") / 100.0).cast(pl.Float32).alias("dgs1mo"),
103
+ (pl.col("DGS3MO") / 100.0).cast(pl.Float32).alias("dgs3mo"),
104
+ (pl.col("DGS6MO") / 100.0).cast(pl.Float32).alias("dgs6mo"),
105
+ ).select(["date"] + rate_cols)
106
+
107
+ df = df.filter(pl.any_horizontal([pl.col(c).is_not_null() for c in rate_cols]))
108
+
109
+ df = df.with_columns(
110
+ pl.when(pl.col("sofr").is_not_null())
111
+ .then(pl.col("sofr"))
112
+ .when(pl.col("effr").is_not_null())
113
+ .then(pl.col("effr"))
114
+ .otherwise(pl.col("dgs1mo"))
115
+ .alias("on")
116
+ )
117
+
118
+ df = df.with_columns([pl.col(c).forward_fill() for c in ["on"] + rate_cols]).sort("date")
119
+
120
+ return df.select(["date", "on"] + rate_cols)
121
+
122
+
123
+ #: FRED Treasury constant-maturity series and their maturities in years.
124
+ TREASURY_SERIES: dict[str, float] = {
125
+ "DGS1MO": 1 / 12, "DGS3MO": .25, "DGS6MO": .5, "DGS1": 1., "DGS2": 2., "DGS3": 3., "DGS5": 5., "DGS7": 7., "DGS10": 10.,
126
+ }
127
+
128
+
129
+ @_fred_cache.cache("0.1", uid=lambda start, end: f"treasury/{start}_{end}")
130
+ def load_fred_treasury_curve(start: str | date, end: str | date) -> pl.DataFrame:
131
+ """
132
+ Daily US Treasury constant-maturity yields from FRED, 1 month to 10 years.
133
+
134
+ Requires the ``FRED_API_KEY`` environment variable.
135
+
136
+ Parameters
137
+ ----------
138
+ start, end : str | date
139
+ Inclusive observation range.
140
+
141
+ Returns
142
+ -------
143
+ pl.DataFrame
144
+ ``date`` and one ``Float64`` column per series in :data:`TREASURY_SERIES`, as decimals
145
+ (``0.05`` for 5%). These are bond-equivalent par yields as published; missing observations
146
+ (holidays, discontinued tenors) are null. Only dates with at least one observation are kept.
147
+ """
148
+ start = start if not isinstance(start, str) else date.fromisoformat(start)
149
+ end = end if not isinstance(end, str) else date.fromisoformat(end)
150
+ api_key = FREDClient.api_key()
151
+ curve = None
152
+ for series_id in TREASURY_SERIES:
153
+ frame = _fetch_fred_series(api_key=api_key, series_id=series_id, start=start, end=end)
154
+ curve = frame if curve is None else curve.join(frame, on="date", how="full", coalesce=True)
155
+ curve = curve.sort("date").with_columns([(pl.col(c) / 100.).alias(c) for c in TREASURY_SERIES])
156
+ return curve.filter(pl.any_horizontal([pl.col(c).is_not_null() for c in TREASURY_SERIES]))
157
+
158
+
159
+ if __name__ == "__main__":
160
+ from openqdata.cli import run_module
161
+
162
+ run_module(globals())
@@ -0,0 +1,5 @@
1
+ # openqdata.massive
2
+
3
+ Massive connector (`MassiveClient`), trade/quote filtering and alignment (`processing`), trade conditions, option contracts (`options`) and ticker-level series (`tickers`).
4
+
5
+ Documentation: [connectors/massive.md](https://github.com/hansbuehler/openqdata/blob/main/docs/connectors/massive.md)
@@ -0,0 +1,15 @@
1
+ """
2
+ Massive.com Data Module
3
+ ^^^^^^^^^^^^^^^^^^^^^^^
4
+
5
+ Data pipeline for `massive.com <https://massive.com/>`_ market data.
6
+ """
7
+
8
+ from openqdata import env, SubDir, Context, version#NOQA
9
+ from openqdata.massive.client import MassiveClient
10
+
11
+ _locations_massive = MassiveClient.locations
12
+
13
+ class _cli_defaults:
14
+ period = (str(MassiveClient.START_DATE), "2025-12-01") #: Default start and end date for CLI commands.
15
+ workers = 4 #: Default number of workers for CLI commands.