SPB Git

spb/wp40_uqo

Public MIT
5.6 KB · 109 lines python
1"""NumPy-facing wrappers over the compiled core (``raid._core``). All heavy work releases the GIL in C++."""2from __future__ import annotations34import enum5from typing import Any, Mapping, Sequence67import numpy as np8910class Backend(str, enum.Enum):11    auto = "auto"12    cpu = "cpu"13    metal = "metal"141516def _core():17    from . import _core as c  # noqa: WPS43318    if c is None:19        raise ImportError("raid._core is not built; install the wheel or build with -DRAID_BUILD_PYTHON=ON")20    return c212223def devices() -> list[dict[str, Any]]:24    """List the available compute devices (CPU always; Metal when built and present)."""25    return _core().devices()262728def available_backends() -> list[str]:29    return [d["kind"] for d in devices()]303132def _f64(x) -> np.ndarray:33    a = np.ascontiguousarray(x, dtype=np.float64)34    if not np.isfinite(a).all():35        raise ValueError("non-finite values in input (RAID never imputes silently)")36    return a373839def ols(X, y, cov: str = "classical", hac_lags: int = -1, clusters=None, ridge_lambda: float = 0.0,40        unpenalized: Sequence[int] = (), weights=None, names: Sequence[str] | None = None) -> dict[str, Any]:41    """OLS/WLS/ridge with classical, HC0–HC3, HAC (Bartlett) or one-way cluster covariance. Returns an Estimate dict."""42    X = _f64(X); y = _f64(y)43    if X.ndim != 2 or y.ndim != 1 or X.shape[0] != y.shape[0]:44        raise ValueError("X must be (n, k) and y (n,)")45    cl = None if clusters is None else np.ascontiguousarray(clusters, dtype=np.int64)46    w = None if weights is None else _f64(weights)47    return _core().ols(X, y, cov, int(hac_lags), cl, float(ridge_lambda), list(unpenalized), w, list(names or []))484950def realized_measures(returns, offsets, backend: str | Backend = Backend.auto, bpv_finite_sample: bool = True,51                      deterministic: bool = True) -> dict[str, np.ndarray]:52    """Per-segment realized measures from concatenated intraday returns and CSR offsets (n_segments + 1)."""53    r = _f64(returns); off = np.ascontiguousarray(offsets, dtype=np.int64)54    return _core().realized_measures(r, off, str(Backend(backend).value), bool(bpv_finite_sample), bool(deterministic))555657def garch_fit(returns, model: str = "garch", dist: str = "gaussian", horizon: int = 0, cov: str = "qmle",58              max_iter: int = 500, tol: float = 1e-8) -> dict[str, Any]:59    """QML fit of GARCH(1,1) / GJR / EGARCH with Gaussian or Student-t errors (CPU FP64)."""60    return _core().garch_fit(_f64(returns), model, dist, int(horizon), cov, int(max_iter), float(tol))616263def validate_bars(timestamps_us, open_, high, low, close, volume, symbol: str = "", interval: str = "1m",64                  session: str = "regular") -> dict[str, Any]:65    """Quality report of one bar series (timestamps = bar open, microseconds UTC)."""66    t = np.ascontiguousarray(timestamps_us, dtype=np.int64)67    return _core().validate_bars(t, _f64(open_), _f64(high), _f64(low), _f64(close), _f64(volume), symbol, interval, session)686970def calendar_sessions(start: str, end: str) -> list[str]:71    """XNYS trading sessions in [start, end] (ISO dates)."""72    return _core().calendar_sessions(start, end)737475def bars_to_intraday_returns(timestamps_us, close, kind: str = "log") -> dict[str, np.ndarray]:76    """Session-aware intraday log/arithmetic returns from (bar open timestamp, close) arrays; returns CSR layout."""77    t = np.ascontiguousarray(timestamps_us, dtype=np.int64)78    return _core().intraday_returns(t, _f64(close), kind)798081def har_fit(rv, lags=(1, 5, 22), horizon: int = 1, log: bool = False, harq: bool = False, rq=None, cov: str = "hac", hac_lags: int = -1, target: str = "average") -> dict[str, Any]:82    """HAR-RV / log-HAR / HARQ on a daily RV series with HAC (Newey–West) inference by default; returns Estimate + forecast_next."""83    return _core().har_fit(_f64(rv), list(lags), int(horizon), bool(log), bool(harq), None if rq is None else _f64(rq), cov, int(hac_lags), target)848586def har_rolling(rv, lags=(1, 5, 22), horizon: int = 1, log: bool = False, window: int = 1000, step: int = 1, harq: bool = False, rq=None) -> dict[str, Any]:87    """Causal rolling re-estimation with origin-ahead forecasts; returns forecasts, actuals, MSE and QLIKE."""88    return _core().har_rolling(_f64(rv), list(lags), int(horizon), bool(log), int(window), int(step), bool(harq), None if rq is None else _f64(rq))899091def har_batch(rv_concat, offsets, lags=(1, 5, 22), horizon: int = 1, log: bool = False, backend: str | Backend = Backend.auto) -> dict[str, Any]:92    """Batched HAR over a CSR panel of daily RV series (sufficient statistics on the selected backend, FP64 solve)."""93    return _core().har_batch(_f64(rv_concat), np.ascontiguousarray(offsets, dtype=np.int64), list(lags), int(horizon), bool(log), str(Backend(backend).value))949596def bootstrap(x, stat: str = "mean", scheme: str = "stationary", mean_block: float = 0.0, replicas: int = 999, seed: int = 20261102, level: float = 0.95) -> dict[str, Any]:97    """Stationary / circular block / iid bootstrap of mean, realized variance (sum of squares) or variance."""98    return _core().bootstrap(_f64(x), stat, scheme, float(mean_block), int(replicas), int(seed), float(level))99100101def var_connectedness(Y, p: int = 1, H: int = 10, window: int = 0, step: int = 1) -> dict[str, Any]:102    """VAR(p) + generalized FEVD + Diebold–Yilmaz total/from/to/net (and rolling totals when window > 0)."""103    Y = _f64(Y); d = _core().var_connectedness(Y, int(p), int(H), int(window), int(step)); N = Y.shape[1]104    d["table"] = np.asarray(d.pop("table_flat")).reshape(N, N); return d105106107def ledoit_wolf(X) -> dict[str, Any]:108    X = _f64(X); d = _core().ledoit_wolf(X); d["cov"] = np.asarray(d.pop("cov_flat")).reshape(X.shape[1], X.shape[1]); return d109
Files · main
Menu

Theme