quantmodeling 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evgeny Baranov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.5
2
+ Name: quantmodeling
3
+ Version: 0.1.0
4
+ Summary: NumPy transforms for returns, realized variance, rolling volatility and robust scaling
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: numpy>=1.26
9
+ Description-Content-Type: text/markdown
10
+
11
+ # quantmodeling
12
+
13
+ NumPy transforms for financial time series. Python 3.11 or later is required.
14
+
15
+ Install from PyPI once a release is available:
16
+
17
+ ```bash
18
+ python -m pip install quantmodeling
19
+ ```
20
+
21
+ From a source checkout, install with `python -m pip install ./packages/transforms`.
22
+
23
+ ```python
24
+ from quantmodeling.transforms import annualized_volatility, log_returns, rolling_variance
25
+
26
+ returns = log_returns([100.0, 101.0, 99.0, 102.0])
27
+ daily_variance = rolling_variance(returns, window=2)
28
+ volatility = annualized_volatility(daily_variance, periods_per_year=252)
29
+ ```
30
+
31
+ | Function | Contract |
32
+ | --- | --- |
33
+ | `simple_returns`, `log_returns` | Adjacent observations of finite, strictly positive, one-dimensional prices. Returns are decimal (0.01 is 1%). Empty and singleton inputs give an empty array. Log returns difference the log prices to avoid overflow of price ratios. |
34
+ | `rolling_variance`, `rolling_volatility` | One-dimensional, trailing windows including the current position. Default variance uses the zero-mean convention with `ddof=0`. Set `demean=True` to subtract the window mean and default to `ddof=1`. The divisor is `window - ddof`. Output length equals input length and the first `window - 1` positions are NaN. Volatility is the square root of variance. |
35
+ | `annualize_variance`, `annualized_volatility` | Pass **per-period variance** and an explicit, finite, positive number of periods per year. The input shape is preserved. Annualized variance multiplies by the factor. Annualized volatility takes the square root of that product. |
36
+ | `realized_variance` | Sums squared intraday log returns over aligned nonnegative integer group indices. Group count defaults to the largest index plus one, or zero for empty input. Missing groups can yield zero (default), NaN, or `InsufficientDataError`. A group containing observations that are all zero yields zero under every policy. A nonfinite return propagates in its own group. |
37
+ | `trailing_mean` | A one-dimensional trailing mean including the current position with NaN for incomplete windows. |
38
+ | `robust_zscores` | A one-dimensional series is centered on its median and divided by 1.4826 times its median absolute deviation. Empty inputs or a zero median absolute deviation yield `None`. |
39
+
40
+ Calculations use float64. Rolling operations retain input positions and NumPy's
41
+ handling of nonfinite values. Window sizes count observations. Choose the
42
+ annualization factor and realized-variance grouping for your sampling convention.
43
+
44
+ The package also exports two shared contracts from `quantmodeling.transforms`:
45
+
46
+ - `FloatArray` is the typing alias for a NumPy array with dtype `numpy.float64`.
47
+ - `require_int(value, name, *, minimum, maximum=None)` accepts Python and
48
+ NumPy integers and returns a Python `int`. Bounds are inclusive. Booleans,
49
+ floats, strings, and out-of-range values raise `ConfigurationError` with
50
+ the supplied parameter name.
51
+
52
+ `QuantModelingError` is the base class for explicit transform validation
53
+ errors. Its subclasses are `ConfigurationError`, `InputValidationError`, and
54
+ `InsufficientDataError`. Each error carries a message and an `issues` tuple
55
+ that is empty for errors raised by the transforms. Downstream callers can
56
+ supply records with `code`, `severity`, `message`, `context`, and `dates`
57
+ attributes. The code and severity expose string `value` attributes. The
58
+ exception snapshots the supplied sequence into a tuple and retains the
59
+ original records.
60
+
61
+ Released under the MIT license. See [LICENSE](LICENSE).
@@ -0,0 +1,51 @@
1
+ # quantmodeling
2
+
3
+ NumPy transforms for financial time series. Python 3.11 or later is required.
4
+
5
+ Install from PyPI once a release is available:
6
+
7
+ ```bash
8
+ python -m pip install quantmodeling
9
+ ```
10
+
11
+ From a source checkout, install with `python -m pip install ./packages/transforms`.
12
+
13
+ ```python
14
+ from quantmodeling.transforms import annualized_volatility, log_returns, rolling_variance
15
+
16
+ returns = log_returns([100.0, 101.0, 99.0, 102.0])
17
+ daily_variance = rolling_variance(returns, window=2)
18
+ volatility = annualized_volatility(daily_variance, periods_per_year=252)
19
+ ```
20
+
21
+ | Function | Contract |
22
+ | --- | --- |
23
+ | `simple_returns`, `log_returns` | Adjacent observations of finite, strictly positive, one-dimensional prices. Returns are decimal (0.01 is 1%). Empty and singleton inputs give an empty array. Log returns difference the log prices to avoid overflow of price ratios. |
24
+ | `rolling_variance`, `rolling_volatility` | One-dimensional, trailing windows including the current position. Default variance uses the zero-mean convention with `ddof=0`. Set `demean=True` to subtract the window mean and default to `ddof=1`. The divisor is `window - ddof`. Output length equals input length and the first `window - 1` positions are NaN. Volatility is the square root of variance. |
25
+ | `annualize_variance`, `annualized_volatility` | Pass **per-period variance** and an explicit, finite, positive number of periods per year. The input shape is preserved. Annualized variance multiplies by the factor. Annualized volatility takes the square root of that product. |
26
+ | `realized_variance` | Sums squared intraday log returns over aligned nonnegative integer group indices. Group count defaults to the largest index plus one, or zero for empty input. Missing groups can yield zero (default), NaN, or `InsufficientDataError`. A group containing observations that are all zero yields zero under every policy. A nonfinite return propagates in its own group. |
27
+ | `trailing_mean` | A one-dimensional trailing mean including the current position with NaN for incomplete windows. |
28
+ | `robust_zscores` | A one-dimensional series is centered on its median and divided by 1.4826 times its median absolute deviation. Empty inputs or a zero median absolute deviation yield `None`. |
29
+
30
+ Calculations use float64. Rolling operations retain input positions and NumPy's
31
+ handling of nonfinite values. Window sizes count observations. Choose the
32
+ annualization factor and realized-variance grouping for your sampling convention.
33
+
34
+ The package also exports two shared contracts from `quantmodeling.transforms`:
35
+
36
+ - `FloatArray` is the typing alias for a NumPy array with dtype `numpy.float64`.
37
+ - `require_int(value, name, *, minimum, maximum=None)` accepts Python and
38
+ NumPy integers and returns a Python `int`. Bounds are inclusive. Booleans,
39
+ floats, strings, and out-of-range values raise `ConfigurationError` with
40
+ the supplied parameter name.
41
+
42
+ `QuantModelingError` is the base class for explicit transform validation
43
+ errors. Its subclasses are `ConfigurationError`, `InputValidationError`, and
44
+ `InsufficientDataError`. Each error carries a message and an `issues` tuple
45
+ that is empty for errors raised by the transforms. Downstream callers can
46
+ supply records with `code`, `severity`, `message`, `context`, and `dates`
47
+ attributes. The code and severity expose string `value` attributes. The
48
+ exception snapshots the supplied sequence into a tuple and retains the
49
+ original records.
50
+
51
+ Released under the MIT license. See [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ """Keep source archives independent of the enclosing repository."""
2
+ from pathlib import Path
3
+
4
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
5
+
6
+
7
+ class CustomBuildHook(BuildHookInterface):
8
+ def initialize(self, version: str, build_data: dict) -> None:
9
+ # Hatchling force-includes VCS ignore files it finds in parent directories.
10
+ force_include = build_data["force_include"]
11
+ for source in tuple(force_include):
12
+ if Path(source).name in {".gitignore", ".hgignore"}:
13
+ del force_include[source]
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "quantmodeling"
7
+ version = "0.1.0"
8
+ description = "NumPy transforms for returns, realized variance, rolling volatility and robust scaling"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["numpy>=1.26"]
14
+
15
+ [dependency-groups]
16
+ test = ["pytest>=8"]
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/quantmodeling/transforms"]
20
+ sources = ["src"]
21
+
22
+ [tool.hatch.build.targets.sdist]
23
+ only-include = [
24
+ "LICENSE",
25
+ "README.md",
26
+ "pyproject.toml",
27
+ "hatch_build.py",
28
+ "src/quantmodeling/transforms/__init__.py",
29
+ "src/quantmodeling/transforms/_arrays.py",
30
+ "src/quantmodeling/transforms/errors.py",
31
+ "src/quantmodeling/transforms/py.typed",
32
+ ]
33
+
34
+ [tool.hatch.build.targets.sdist.hooks.custom]
@@ -0,0 +1,204 @@
1
+ """Pure, vectorised time-series transformations.
2
+
3
+ Functions accept NumPy array-like inputs. Windows that are not fully
4
+ populated yield ``NaN`` in rolling outputs *by position* (the first
5
+ ``window - 1`` entries); callers decide how to treat them. No function fills,
6
+ interpolates or drops observations.
7
+
8
+ Units: returns are decimal (0.01 = 1 %). Variance is in squared return units
9
+ per period; volatility is its square root.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from typing import Literal
14
+
15
+ import numpy as np
16
+ import numpy.typing as npt
17
+ from numpy.lib.stride_tricks import sliding_window_view
18
+
19
+ from ._arrays import FloatArray, _require_int
20
+ from .errors import ConfigurationError, InputValidationError, InsufficientDataError, QuantModelingError
21
+
22
+ require_int = _require_int
23
+
24
+ __all__ = [
25
+ "ConfigurationError",
26
+ "InputValidationError",
27
+ "InsufficientDataError",
28
+ "QuantModelingError",
29
+ "FloatArray",
30
+ "require_int",
31
+ "simple_returns",
32
+ "log_returns",
33
+ "rolling_variance",
34
+ "rolling_volatility",
35
+ "annualize_variance",
36
+ "annualized_volatility",
37
+ "realized_variance",
38
+ "trailing_mean",
39
+ "robust_zscores",
40
+ ]
41
+
42
+
43
+ def _as_float(x: npt.ArrayLike, name: str) -> FloatArray:
44
+ arr = np.asarray(x, dtype=np.float64)
45
+ if arr.ndim != 1:
46
+ raise InputValidationError(f"{name} must be one-dimensional")
47
+ return arr
48
+
49
+
50
+ def _check_prices(prices: FloatArray) -> None:
51
+ if not np.all(np.isfinite(prices)) or np.any(prices <= 0):
52
+ raise InputValidationError("prices must be finite and strictly positive")
53
+
54
+
55
+ def simple_returns(prices: npt.ArrayLike) -> FloatArray:
56
+ """Arithmetic returns ``P_t / P_{t-1} - 1``; length ``n - 1``."""
57
+ p = _as_float(prices, "prices")
58
+ _check_prices(p)
59
+ return np.asarray(p[1:] / p[:-1] - 1.0, dtype=np.float64)
60
+
61
+
62
+ def log_returns(prices: npt.ArrayLike) -> FloatArray:
63
+ """Logarithmic returns ``ln(P_t / P_{t-1})``; length ``n - 1``."""
64
+ p = _as_float(prices, "prices")
65
+ _check_prices(p)
66
+ return np.asarray(np.diff(np.log(p)), dtype=np.float64)
67
+
68
+
69
+ def rolling_variance(
70
+ returns: npt.ArrayLike, window: int, *, demean: bool = False, ddof: int | None = None
71
+ ) -> FloatArray:
72
+ """Rolling variance over the trailing ``window`` observations.
73
+
74
+ Args:
75
+ returns: Return series.
76
+ window: Positive integer number of observations, greater than ``ddof``.
77
+ demean: Subtract the window mean. With ``False`` (default) the
78
+ estimator is the mean of squared returns — the usual
79
+ zero-mean convention for daily volatility.
80
+ ddof: Non-negative integer degrees-of-freedom adjustment; defaults to 1 when ``demean`` and 0
81
+ otherwise.
82
+
83
+ Returns:
84
+ Array of the same length as ``returns``; entry ``t`` uses
85
+ observations ``t - window + 1 .. t``. The first ``window - 1``
86
+ entries are ``NaN``.
87
+ """
88
+ r = _as_float(returns, "returns")
89
+ if ddof is None:
90
+ ddof = 1 if demean else 0
91
+ ddof = _require_int(ddof, "ddof", minimum=0)
92
+ window = _require_int(window, "window", minimum=1)
93
+ if window <= ddof:
94
+ raise ConfigurationError(f"window={window} too small for ddof={ddof}")
95
+ out = np.full(r.shape, np.nan)
96
+ if r.size < window:
97
+ return out
98
+ if demean:
99
+ win = sliding_window_view(r, window)
100
+ # Limit the working array to about one million elements (or one full
101
+ # window). Each row retains NumPy's two-pass mean and sum order.
102
+ rows = max(1, 1_048_576 // window)
103
+ dest = out[window - 1 :]
104
+ for start in range(0, len(win), rows):
105
+ block = win[start : start + rows]
106
+ dev = block - block.mean(axis=1, keepdims=True)
107
+ np.square(dev, out=dev)
108
+ dest[start : start + rows] = dev.sum(axis=1) / (window - ddof)
109
+ else:
110
+ out[window - 1 :] = sliding_window_view(np.square(r), window).sum(axis=1) / (window - ddof)
111
+ return out
112
+
113
+
114
+ def rolling_volatility(
115
+ returns: npt.ArrayLike, window: int, *, demean: bool = False, ddof: int | None = None
116
+ ) -> FloatArray:
117
+ """Square root of :func:`rolling_variance` (per-period volatility)."""
118
+ return np.sqrt(rolling_variance(returns, window, demean=demean, ddof=ddof))
119
+
120
+
121
+ def annualize_variance(daily_variance: npt.ArrayLike, periods_per_year: float) -> FloatArray:
122
+ """Annualised variance = per-period variance x periods per year."""
123
+ if not np.isfinite(periods_per_year) or periods_per_year <= 0:
124
+ raise ConfigurationError("periods_per_year must be finite and positive")
125
+ return np.asarray(np.asarray(daily_variance, dtype=np.float64) * periods_per_year)
126
+
127
+
128
+ def annualized_volatility(daily_variance: npt.ArrayLike, periods_per_year: float) -> FloatArray:
129
+ """Annualised volatility = sqrt(per-period variance x periods per year)."""
130
+ return np.sqrt(annualize_variance(daily_variance, periods_per_year))
131
+
132
+
133
+ def realized_variance(
134
+ intraday_log_returns: npt.ArrayLike,
135
+ group_ids: npt.ArrayLike,
136
+ n_groups: int | None = None,
137
+ *,
138
+ missing: Literal["zero", "nan", "raise"] = "zero",
139
+ ) -> FloatArray:
140
+ """Sum of squared intraday log returns per group (trading day).
141
+
142
+ Args:
143
+ intraday_log_returns: Intraday log returns.
144
+ group_ids: Non-negative integral numeric indices, less than ``n_groups``.
145
+ n_groups: Non-negative integer output length. Defaults to ``max(group_ids) + 1``
146
+ or zero for empty input.
147
+ missing: Policy for groups with no observations. ``"zero"`` retains the
148
+ legacy empty sum. Use ``"nan"`` to mark unavailable estimates or
149
+ ``"raise"`` to reject a missing group with :class:`InsufficientDataError`.
150
+
151
+ Groups with observations whose returns are all zero yield zero under
152
+ every policy. NaN or infinity in returns propagates within its group.
153
+ """
154
+ r = _as_float(intraday_log_returns, "intraday_log_returns")
155
+ g = np.asarray(group_ids)
156
+ if g.shape != r.shape:
157
+ raise InputValidationError("group_ids must align with returns")
158
+ max_groups = np.iinfo(np.intp).max // np.dtype(np.float64).itemsize
159
+ if n_groups is not None:
160
+ n_groups = _require_int(n_groups, "n_groups", minimum=0, maximum=max_groups)
161
+ if missing not in ("zero", "nan", "raise"):
162
+ raise ConfigurationError("missing must be 'zero', 'nan', or 'raise'")
163
+ if g.dtype.kind not in "iuf":
164
+ raise InputValidationError("group_ids must be real numbers with integer values")
165
+ if g.dtype.kind == "f":
166
+ if not np.all(np.isfinite(g)) or np.any(g != np.trunc(g)):
167
+ raise InputValidationError("group_ids must be finite integers")
168
+ # int(max) keeps the upper bound exact even for floats near the intp limit.
169
+ largest = int(g.max()) if g.size else -1
170
+ if n_groups is None:
171
+ n_groups = largest + 1
172
+ if np.any(g < 0) or largest >= min(n_groups, max_groups):
173
+ raise InputValidationError("group_ids must be between zero and n_groups - 1")
174
+ ids = g.astype(np.intp, copy=False)
175
+ if missing != "zero":
176
+ absent = np.bincount(ids, minlength=n_groups) == 0
177
+ if missing == "raise" and absent.any():
178
+ raise InsufficientDataError(f"{np.count_nonzero(absent)} realized variance groups have no observations")
179
+ variance = np.asarray(np.bincount(ids, weights=r * r, minlength=n_groups), dtype=np.float64)
180
+ if missing == "nan":
181
+ variance[absent] = np.nan
182
+ return variance
183
+
184
+
185
+ def trailing_mean(x: npt.ArrayLike, window: int) -> FloatArray:
186
+ """Mean of the trailing ``window`` values (entry ``t`` uses ``t-window+1..t``)."""
187
+ window = _require_int(window, "window", minimum=1)
188
+ arr = _as_float(x, "x")
189
+ out = np.full(arr.shape, np.nan)
190
+ if arr.size >= window:
191
+ out[window - 1 :] = sliding_window_view(arr, window).mean(axis=1)
192
+ return out
193
+
194
+
195
+ def robust_zscores(x: npt.ArrayLike) -> FloatArray | None:
196
+ """Robust z-scores ``(x - median) / (1.4826 * MAD)``; ``None`` if MAD is zero."""
197
+ arr = _as_float(x, "x")
198
+ if arr.size == 0:
199
+ return None
200
+ med = float(np.median(arr))
201
+ mad = float(np.median(np.abs(arr - med)))
202
+ if mad <= 0:
203
+ return None
204
+ return np.asarray((arr - med) / (1.4826 * mad), dtype=np.float64)
@@ -0,0 +1,24 @@
1
+ """Shared NumPy array type and integer validation."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ import numpy.typing as npt
6
+
7
+ from .errors import ConfigurationError
8
+
9
+ FloatArray = npt.NDArray[np.float64]
10
+
11
+
12
+ def _require_int(value: object, name: str, *, minimum: int, maximum: int | None = None) -> int:
13
+ """Return a Python int after validating an integer configuration value.
14
+
15
+ Accept Python and NumPy integers, excluding booleans. Bounds are
16
+ inclusive. An invalid value raises :class:`ConfigurationError` with
17
+ the supplied parameter name.
18
+ """
19
+ if not isinstance(value, bool) and isinstance(value, (int, np.integer)):
20
+ integer = int(value)
21
+ if integer >= minimum and (maximum is None or integer <= maximum):
22
+ return integer
23
+ bounds = f">= {minimum}" if maximum is None else f"in [{minimum}, {maximum}]"
24
+ raise ConfigurationError(f"{name} must be an integer {bounds}")
@@ -0,0 +1,48 @@
1
+ """Exceptions shared by the numerical transforms and their downstream callers."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Sequence
5
+ from datetime import date
6
+ from typing import Any, Protocol
7
+
8
+
9
+ class _IssueLabel(Protocol):
10
+ @property
11
+ def value(self) -> str: ...
12
+
13
+
14
+ class _IssueRecord(Protocol):
15
+ @property
16
+ def code(self) -> _IssueLabel: ...
17
+
18
+ @property
19
+ def severity(self) -> _IssueLabel: ...
20
+
21
+ @property
22
+ def message(self) -> str: ...
23
+
24
+ @property
25
+ def context(self) -> dict[str, Any]: ...
26
+
27
+ @property
28
+ def dates(self) -> tuple[date, ...]: ...
29
+
30
+
31
+ class QuantModelingError(Exception):
32
+ """Base error with an optional tuple of caller-provided diagnostic records."""
33
+
34
+ def __init__(self, message: str, issues: Sequence[_IssueRecord] = ()) -> None:
35
+ super().__init__(message)
36
+ self.issues: tuple[_IssueRecord, ...] = tuple(issues)
37
+
38
+
39
+ class ConfigurationError(QuantModelingError):
40
+ """A configuration value is invalid or a required convention is missing."""
41
+
42
+
43
+ class InputValidationError(QuantModelingError):
44
+ """Input data violates the input contract."""
45
+
46
+
47
+ class InsufficientDataError(QuantModelingError):
48
+ """Not enough valid observations to perform the requested calculation."""