Skip to content

Commit d921c35

Browse files
authored
Merge pull request #942 from antonsoo/fix/integer-covariance-products
BUG: Promote discrete covariance inputs before products
2 parents 085ff7b + a8607d5 commit d921c35

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

‎arch/covariance/kernel.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,8 @@ def cov(self) -> CovarianceEstimate:
592592
--------
593593
CovarianceEstimate : The container of the covariance estimates.
594594
"""
595-
x = np.ascontiguousarray(self._x, dtype=float)
595+
dtype = None if not np.issubdtype(self._x.dtype, np.inexact) else float
596+
x = np.ascontiguousarray(self._x, dtype=dtype)
596597
k = x.shape[1]
597598
df = self._df
598599
sr = x.T @ x / df

‎arch/tests/covariance/test_covariance_dtypes.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,28 @@ def test_uncentered_integer_newey_west(lags):
5353
expected += Fraction(2 * (lags + 1 - lag) * products, (lags + 1) * nobs)
5454

5555
assert_allclose(cov_nw(data, lags=lags, demean=False), float(expected))
56+
57+
58+
@pytest.mark.parametrize("dtype", [np.float32, np.float64])
59+
def test_preserve_floating_kernel_dtype(dtype):
60+
data = np.arange(12).reshape(6, 2).astype(dtype) / 10
61+
result = Bartlett(data, bandwidth=2, center=False).cov
62+
expected = data.T @ data / len(data)
63+
assert result.short_run.dtype == expected.dtype
64+
assert_array_equal(result.short_run, expected)
65+
66+
67+
@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.complex64, np.complex128])
68+
@pytest.mark.parametrize("lags", [0, 2])
69+
def test_preserve_inexact_newey_west(dtype, lags):
70+
data = np.arange(12).reshape(6, 2).astype(dtype) / 10
71+
if np.issubdtype(dtype, np.complexfloating):
72+
data = data + 1j * data[::-1]
73+
expected = data.T @ data
74+
for lag in range(1, lags + 1):
75+
gamma = data[lag:].T @ data[:-lag]
76+
expected += (1 - lag / (lags + 1)) * (gamma + gamma.T)
77+
expected /= len(data)
78+
result = cov_nw(data, lags=lags, demean=False)
79+
assert result.dtype == expected.dtype
80+
assert_array_equal(result, expected)

‎arch/utility/cov.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from numpy import asarray, squeeze
1+
from numpy import asarray, inexact, issubdtype, squeeze
22

33
from arch._typing import Float64Array
44
from arch.utility._validation import (
@@ -50,7 +50,10 @@ def cov_nw(
5050
If y is not 1-d or 2-d, is empty or contains NaN or infinite values, or if
5151
lags, axis or ddof are outside their range.
5252
"""
53+
z = asarray(y)
5354
z = check_array("y", y)
55+
if not issubdtype(z.dtype, inexact):
56+
z = z.astype(float)
5457
if z.ndim not in (1, 2) or z.size == 0:
5558
_fail(
5659
ValueError,

0 commit comments

Comments
 (0)