diff --git a/arch/tests/univariate/test_volatility.py b/arch/tests/univariate/test_volatility.py index a5fa5ab74c..ad5dcbc960 100644 --- a/arch/tests/univariate/test_volatility.py +++ b/arch/tests/univariate/test_volatility.py @@ -2513,33 +2513,23 @@ def test_garch_starting_values_match_full_grid(setup, p, o, q, power): assert_equal(vol.starting_values(resids), _full_grid_starting_values(vol, resids)) -def test_garch_starting_values_use_overridden_compute_variance(setup): - class CountingGARCH(GARCH): - calls = 0 - - def compute_variance(self, parameters, resids, sigma2, backcast, var_bounds): - CountingGARCH.calls += 1 - return super().compute_variance( - parameters, resids, sigma2, backcast, var_bounds - ) - - vol = CountingGARCH(o=1) - sv = vol.starting_values(setup.resids) - assert CountingGARCH.calls == 64 - assert_equal(sv, GARCH(o=1).starting_values(setup.resids)) - - -def test_garch_starting_values_score_distinct_candidates(setup): - # Without asymmetric terms gamma is unused, so 16 of the 64 grid candidates - # are distinct, and each is scored once - class CountingGARCH(GARCH): - calls = 0 +@pytest.mark.parametrize( + ("p", "o", "q", "expected"), + [(1, 0, 1, 16), (0, 1, 1, 16), (1, 1, 1, 64), (2, 0, 2, 16), (1, 0, 0, 16)], +) +def test_garch_starting_values_score_distinct_candidates(setup, p, o, q, expected): + # alpha is unused when p is 0 and gamma when o is 0, so only the distinct + # candidates of the 4 x 4 x 4 grid are scored, each once + scored = [] + class RecordingGARCH(GARCH): def compute_variance(self, parameters, resids, sigma2, backcast, var_bounds): - CountingGARCH.calls += 1 + scored.append(tuple(parameters)) return super().compute_variance( parameters, resids, sigma2, backcast, var_bounds ) - CountingGARCH().starting_values(setup.resids) - assert CountingGARCH.calls == 16 + RecordingGARCH(p=p, o=o, q=q).starting_values(setup.resids) + num_scored, num_distinct = len(scored), len(set(scored)) + assert num_scored == expected + assert num_distinct == expected diff --git a/arch/univariate/base.py b/arch/univariate/base.py index aba86261b5..649c249012 100644 --- a/arch/univariate/base.py +++ b/arch/univariate/base.py @@ -153,26 +153,18 @@ def constraint(a: Float64Array, b: Float64Array) -> list[dict[str, object]]: a = check_array("a", a, ndim=2, squeeze=False) b = check_array("b", b, ndim=1, shape=(a.shape[0],), squeeze=False) - def factory(coeff: Float64Array, val: float) -> Callable[..., float]: + def factory(coeff: Float64Array, val: float) -> dict[str, object]: def f(params: Float64Array, *args: Any) -> float: return np.dot(coeff, params) - val - return f - - def jac_factory(coeff: Float64Array) -> Callable[..., Float64Array]: # The constraints are linear, so the gradient is the row of a. Without it # SLSQP approximates the gradient by finite differences at every iteration. def jac(params: Float64Array, *args: Any) -> Float64Array: return coeff - return jac - - constraints = [] - for i in range(a.shape[0]): - con = {"type": "ineq", "fun": factory(a[i], b[i]), "jac": jac_factory(a[i])} - constraints.append(con) + return {"type": "ineq", "fun": f, "jac": jac} - return constraints + return [factory(a[i], b[i]) for i in range(a.shape[0])] def format_float_fixed(x: float, max_digits: int = 10, decimal: int = 4) -> str: diff --git a/arch/univariate/volatility.py b/arch/univariate/volatility.py index f6c64b45ba..90969a96e6 100644 --- a/arch/univariate/volatility.py +++ b/arch/univariate/volatility.py @@ -6,7 +6,7 @@ """ from abc import ABCMeta, abstractmethod -from collections.abc import Callable, Sequence +from collections.abc import Sequence import inspect import itertools from typing import TYPE_CHECKING, Any, cast @@ -1638,33 +1638,14 @@ def compute_variance( power = self.power fresids = np.absolute(resids) ** power sresids = np.sign(resids) - return self._transformed_variance( - parameters, fresids, sresids, sigma2, backcast, var_bounds - ) - - def _transformed_variance( - self, - parameters: Float64Array1D, - fresids: Float64Array1D, - sresids: Float64Array1D, - sigma2: Float64Array1D, - backcast: float | Float64Array1D, - var_bounds: Float64Array2D, - ) -> Float64Array1D: - """ - Compute the variance from residuals already raised to the power. - ``fresids`` is ``abs(resids) ** power`` and ``sresids`` is ``sign(resids)``, - so that callers that evaluate many parameter values on the same residuals - compute them once. - """ p, o, q = self.p, self.o, self.q - nobs = fresids.shape[0] + nobs = resids.shape[0] rec.garch_recursion( parameters, fresids, sresids, sigma2, p, o, q, nobs, backcast, var_bounds ) - inv_power = 2.0 / self.power + inv_power = 2.0 / power sigma2 **= inv_power return sigma2 @@ -1750,10 +1731,12 @@ def starting_values(self, resids: ArrayLike1D) -> Float64Array1D: resids = ensure1d(resids, "resids") p, o, q = self.p, self.o, self.q power = self.power - alphas = [0.01, 0.05, 0.1, 0.2] - # Without asymmetric terms gamma is unused, so one value gives every - # distinct starting value, in the same order as the full grid - gammas = alphas if o > 0 else alphas[:1] + grid = [0.01, 0.05, 0.1, 0.2] + # alpha is unused when p is 0, and gamma when o is 0. One value of an unused + # coefficient gives every distinct candidate, in the order of the full grid, + # so the first maximum is the same candidate + alphas = grid if p > 0 else grid[:1] + gammas = grid if o > 0 else grid[:1] abg = [0.5, 0.7, 0.9, 0.98] abgs = list(itertools.product(*[alphas, gammas, abg])) @@ -1765,7 +1748,6 @@ def starting_values(self, resids: ArrayLike1D) -> Float64Array1D: var_bounds = self.variance_bounds(resids) backcast = self.backcast(resids) llfs = np.zeros(len(abgs)) - loglik = self._starting_value_loglikelihood(resids, backcast, var_bounds) for i, values in enumerate(abgs): alpha, gamma, agb = values sv = (1.0 - agb) * target * np.ones(p + o + q + 1, dtype=float) @@ -1778,49 +1760,13 @@ def starting_values(self, resids: ArrayLike1D) -> Float64Array1D: if q > 0: sv[1 + p + o : 1 + p + o + q] = agb / q svs.append(cast("Float64Array1D", sv)) - llfs[i] = loglik(cast("Float64Array1D", sv)) + llfs[i] = self._gaussian_loglikelihood( + cast("Float64Array1D", sv), resids, backcast, var_bounds + ) loc = np.argmax(llfs) return svs[int(loc)] - def _starting_value_loglikelihood( - self, - resids: Float64Array1D, - backcast: float | Float64Array1D, - var_bounds: Float64Array2D, - ) -> Callable[[Float64Array1D], float]: - """ - Return the Gaussian log-likelihood of candidate starting values. - - The residual transforms in ``compute_variance`` do not depend on the - parameters, so they are computed once for the whole grid. The arrays passed - to the recursion are created here as C contiguous float64 vectors and - matrices, so the argument checks of ``compute_variance`` are not repeated. A - subclass that replaces ``compute_variance`` keeps using it. - """ - if type(self).compute_variance is not GARCH.compute_variance: - - def generic(parameters: Float64Array1D) -> float: - return self._gaussian_loglikelihood( - parameters, resids, backcast, var_bounds - ) - - return generic - - resids = np.ascontiguousarray(resids, dtype=float) - var_bounds = np.ascontiguousarray(var_bounds, dtype=float) - fresids = np.absolute(resids) ** self.power - sresids = np.sign(resids) - sigma2 = np.empty(resids.shape[0]) - - def transformed(parameters: Float64Array1D) -> float: - self._transformed_variance( - parameters, fresids, sresids, sigma2, backcast, var_bounds - ) - return float(self._normal.loglikelihood([], resids, sigma2)) - - return transformed - def parameter_names(self) -> list[str]: return _common_names(self.p, self.o, self.q)