quantmodeling 0.1.0__tar.gz → 0.1.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: quantmodeling
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: NumPy transforms for returns, realized variance, rolling volatility and robust scaling
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -30,9 +30,10 @@ volatility = annualized_volatility(daily_variance, periods_per_year=252)
30
30
 
31
31
  | Function | Contract |
32
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. |
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. Each log return equals `log_price_ratio` of the adjacent prices. |
34
+ | `log_price_ratio` | Elementwise `ln(price / base)` for finite, strictly positive arrays of the same shape, accurate to a few units in the last place. Ratios between 1/2 and 2 use `log1p((price - base) / base)`, where the difference is exact, so small moves lose no precision to cancellation. Other ratios take the logarithm of the quotient, and quotients outside the normal float64 range fall back to `ln(price) - ln(base)`. |
35
+ | `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`. `demean` accepts only Python or NumPy booleans. 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. |
36
+ | `annualize_variance`, `annualized_volatility` | Pass **per-period variance** and an explicit, finite, positive real number of periods per year. Booleans, strings and arrays are rejected. The input shape is preserved. Annualized variance multiplies by the factor. Annualized volatility takes the square root of that product. |
36
37
  | `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
38
  | `trailing_mean` | A one-dimensional trailing mean including the current position with NaN for incomplete windows. |
38
39
  | `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`. |
@@ -20,9 +20,10 @@ volatility = annualized_volatility(daily_variance, periods_per_year=252)
20
20
 
21
21
  | Function | Contract |
22
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. |
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. Each log return equals `log_price_ratio` of the adjacent prices. |
24
+ | `log_price_ratio` | Elementwise `ln(price / base)` for finite, strictly positive arrays of the same shape, accurate to a few units in the last place. Ratios between 1/2 and 2 use `log1p((price - base) / base)`, where the difference is exact, so small moves lose no precision to cancellation. Other ratios take the logarithm of the quotient, and quotients outside the normal float64 range fall back to `ln(price) - ln(base)`. |
25
+ | `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`. `demean` accepts only Python or NumPy booleans. 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. |
26
+ | `annualize_variance`, `annualized_volatility` | Pass **per-period variance** and an explicit, finite, positive real number of periods per year. Booleans, strings and arrays are rejected. The input shape is preserved. Annualized variance multiplies by the factor. Annualized volatility takes the square root of that product. |
26
27
  | `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
28
  | `trailing_mean` | A one-dimensional trailing mean including the current position with NaN for incomplete windows. |
28
29
  | `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`. |
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "quantmodeling"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "NumPy transforms for returns, realized variance, rolling volatility and robust scaling"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -16,7 +16,7 @@ import numpy as np
16
16
  import numpy.typing as npt
17
17
  from numpy.lib.stride_tricks import sliding_window_view
18
18
 
19
- from ._arrays import FloatArray, _require_int
19
+ from ._arrays import FloatArray, _require_bool, _require_finite_real, _require_int
20
20
  from .errors import ConfigurationError, InputValidationError, InsufficientDataError, QuantModelingError
21
21
 
22
22
  require_int = _require_int
@@ -30,6 +30,7 @@ __all__ = [
30
30
  "require_int",
31
31
  "simple_returns",
32
32
  "log_returns",
33
+ "log_price_ratio",
33
34
  "rolling_variance",
34
35
  "rolling_volatility",
35
36
  "annualize_variance",
@@ -59,23 +60,68 @@ def simple_returns(prices: npt.ArrayLike) -> FloatArray:
59
60
  return np.asarray(p[1:] / p[:-1] - 1.0, dtype=np.float64)
60
61
 
61
62
 
63
+ def _log_ratio(price: FloatArray, base: FloatArray) -> FloatArray:
64
+ """``ln(price / base)`` for validated finite, strictly positive arrays of equal shape.
65
+
66
+ For a ratio in ``[1/2, 2]`` the difference ``price - base`` is exact
67
+ (Sterbenz lemma), so ``log1p((price - base) / base)`` rounds only in the
68
+ division and in ``log1p``. Other ratios give results of at least ``ln 2`` in
69
+ magnitude, where rounding ``price / base`` costs about one ulp of the
70
+ logarithm. A ratio outside the normal float64 range falls back to
71
+ ``ln(price) - ln(base)``, whose absolute error is negligible against such a
72
+ large result.
73
+ """
74
+ with np.errstate(over="ignore", under="ignore", divide="ignore"):
75
+ # Explicit outputs keep zero-dimensional inputs as assignable arrays.
76
+ ratio = np.divide(price, base, out=np.empty(price.shape))
77
+ out = np.log(ratio, out=np.empty(price.shape))
78
+ near = (ratio >= 0.5) & (ratio <= 2.0)
79
+ out[near] = np.log1p((price[near] - base[near]) / base[near])
80
+ extreme = (ratio < np.finfo(np.float64).tiny) | np.isinf(ratio)
81
+ out[extreme] = np.log(price[extreme]) - np.log(base[extreme])
82
+ return out
83
+
84
+
85
+ def log_price_ratio(price: npt.ArrayLike, base: npt.ArrayLike) -> FloatArray:
86
+ """Elementwise ``ln(price / base)``, accurate to a few ulps for any positive float64 prices.
87
+
88
+ Args:
89
+ price: Finite, strictly positive prices.
90
+ base: Finite, strictly positive reference prices of the same shape.
91
+
92
+ Returns:
93
+ Float64 array of the input shape. Small moves lose no precision to
94
+ cancellation and extreme ratios do not overflow.
95
+ """
96
+ p = np.asarray(price, dtype=np.float64)
97
+ b = np.asarray(base, dtype=np.float64)
98
+ if p.shape != b.shape:
99
+ raise InputValidationError("price and base must have the same shape")
100
+ if not (np.all(np.isfinite(p)) and np.all(np.isfinite(b))) or np.any(p <= 0) or np.any(b <= 0):
101
+ raise InputValidationError("price and base must be finite and strictly positive")
102
+ return _log_ratio(p, b)
103
+
104
+
62
105
  def log_returns(prices: npt.ArrayLike) -> FloatArray:
63
- """Logarithmic returns ``ln(P_t / P_{t-1})``; length ``n - 1``."""
106
+ """Logarithmic returns ``ln(P_t / P_{t-1})``; length ``n - 1``.
107
+
108
+ Each return equals :func:`log_price_ratio` of the adjacent prices.
109
+ """
64
110
  p = _as_float(prices, "prices")
65
111
  _check_prices(p)
66
- return np.asarray(np.diff(np.log(p)), dtype=np.float64)
112
+ return _log_ratio(p[1:], p[:-1])
67
113
 
68
114
 
69
115
  def rolling_variance(
70
- returns: npt.ArrayLike, window: int, *, demean: bool = False, ddof: int | None = None
116
+ returns: npt.ArrayLike, window: int, *, demean: bool | np.bool_ = False, ddof: int | None = None
71
117
  ) -> FloatArray:
72
118
  """Rolling variance over the trailing ``window`` observations.
73
119
 
74
120
  Args:
75
121
  returns: Return series.
76
122
  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
123
+ demean: Boolean; subtract the window mean. With ``False`` (default)
124
+ the estimator is the mean of squared returns — the usual
79
125
  zero-mean convention for daily volatility.
80
126
  ddof: Non-negative integer degrees-of-freedom adjustment; defaults to 1 when ``demean`` and 0
81
127
  otherwise.
@@ -86,6 +132,7 @@ def rolling_variance(
86
132
  entries are ``NaN``.
87
133
  """
88
134
  r = _as_float(returns, "returns")
135
+ demean = _require_bool(demean, "demean")
89
136
  if ddof is None:
90
137
  ddof = 1 if demean else 0
91
138
  ddof = _require_int(ddof, "ddof", minimum=0)
@@ -112,17 +159,19 @@ def rolling_variance(
112
159
 
113
160
 
114
161
  def rolling_volatility(
115
- returns: npt.ArrayLike, window: int, *, demean: bool = False, ddof: int | None = None
162
+ returns: npt.ArrayLike, window: int, *, demean: bool | np.bool_ = False, ddof: int | None = None
116
163
  ) -> FloatArray:
117
164
  """Square root of :func:`rolling_variance` (per-period volatility)."""
118
165
  return np.sqrt(rolling_variance(returns, window, demean=demean, ddof=ddof))
119
166
 
120
167
 
121
168
  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)
169
+ """Annualised variance = per-period variance x periods per year.
170
+
171
+ ``periods_per_year`` is a finite, positive real number other than a boolean.
172
+ """
173
+ factor = _require_finite_real(periods_per_year, "periods_per_year", positive=True)
174
+ return np.asarray(np.asarray(daily_variance, dtype=np.float64) * factor)
126
175
 
127
176
 
128
177
  def annualized_volatility(daily_variance: npt.ArrayLike, periods_per_year: float) -> FloatArray:
@@ -0,0 +1,54 @@
1
+ """Shared NumPy array type and configuration validation."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from numbers import Real
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+
10
+ from .errors import ConfigurationError
11
+
12
+ FloatArray = npt.NDArray[np.float64]
13
+
14
+
15
+ def _require_int(value: object, name: str, *, minimum: int, maximum: int | None = None) -> int:
16
+ """Return a Python int after validating an integer configuration value.
17
+
18
+ Accept Python and NumPy integers, excluding booleans. Bounds are
19
+ inclusive. An invalid value raises :class:`ConfigurationError` with
20
+ the supplied parameter name.
21
+ """
22
+ if not isinstance(value, bool) and isinstance(value, (int, np.integer)):
23
+ integer = int(value)
24
+ if integer >= minimum and (maximum is None or integer <= maximum):
25
+ return integer
26
+ bounds = f">= {minimum}" if maximum is None else f"in [{minimum}, {maximum}]"
27
+ raise ConfigurationError(f"{name} must be an integer {bounds}")
28
+
29
+
30
+ def _require_bool(value: object, name: str) -> bool:
31
+ """Return a Python bool, accepting only Python and NumPy booleans (not 0, 1 or strings)."""
32
+ if isinstance(value, (bool, np.bool_)):
33
+ return bool(value)
34
+ raise ConfigurationError(f"{name} must be a boolean")
35
+
36
+
37
+ def _require_finite_real(value: object, name: str, *, positive: bool = False) -> float:
38
+ """Return a finite Python float from a real number, excluding booleans.
39
+
40
+ Accept Python and NumPy integers and floats and other :class:`numbers.Real`
41
+ values. Strings, ``None``, arrays, booleans, non-finite values and integers
42
+ beyond the float64 range raise :class:`ConfigurationError`. With
43
+ ``positive`` the value must also be greater than zero.
44
+ """
45
+ if isinstance(value, Real) and not isinstance(value, (bool, np.bool_)):
46
+ try:
47
+ result = float(value)
48
+ except OverflowError:
49
+ pass
50
+ else:
51
+ if math.isfinite(result) and (not positive or result > 0):
52
+ return result
53
+ requirement = "finite and positive" if positive else "a finite real number"
54
+ raise ConfigurationError(f"{name} must be {requirement}")
@@ -1,24 +0,0 @@
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}")
File without changes