From 5d7ba2b62165539d8e114d438f43e685468b9465 Mon Sep 17 00:00:00 2001 From: yqia03 <176992144+yqia03@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:50:29 +0800 Subject: [PATCH] BUG: Make optimal bootstrap block length invariant to extreme scaling Generated-by: OpenAI Codex --- arch/bootstrap/base.py | 6 +++++- arch/tests/bootstrap/test_block_length.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/arch/bootstrap/base.py b/arch/bootstrap/base.py index bf3c21b66f..bd09caea57 100644 --- a/arch/bootstrap/base.py +++ b/arch/bootstrap/base.py @@ -114,7 +114,11 @@ def _single_optimal_block(x: Float64Array) -> tuple[float, float]: Estimated optimal window length for circular bootstrap """ nobs = x.shape[0] - eps = x - x.mean(0) + # The ratios below are scale invariant but form fourth powers of the + # data's scale. Rescale by a power of two before centering. + _, exponent = np.frexp(np.max(np.abs(x))) + scaled = np.ldexp(x, -exponent) + eps = scaled - scaled.mean(0) b_max = np.ceil(min(3 * np.sqrt(nobs), nobs / 3)) kn = max(5, int(np.log10(nobs))) m_max = int(np.ceil(np.sqrt(nobs))) + kn diff --git a/arch/tests/bootstrap/test_block_length.py b/arch/tests/bootstrap/test_block_length.py index b3fb508751..e151a578b2 100644 --- a/arch/tests/bootstrap/test_block_length.py +++ b/arch/tests/bootstrap/test_block_length.py @@ -1,6 +1,7 @@ import numpy as np from numpy.testing import assert_allclose import pandas as pd +import pytest from arch.bootstrap.base import optimal_block_length @@ -30,3 +31,12 @@ def test_block_length(): bl = optimal_block_length(np.asarray(df)) assert tuple(bl.index) == (0, 1) + + +@pytest.mark.parametrize("exponent", [-400, 400]) +def test_block_length_is_invariant_to_scale(exponent): + x = np.array([2.0, 5.0, 4.0, 0.0, 5.0, 5.0, 5.0, -5.0, -1.0, 1.0, -2.0, -1.0]) + expected = optimal_block_length(x) + with np.errstate(over="raise", divide="raise", invalid="raise"): + actual = optimal_block_length(np.ldexp(x, exponent)) + assert_allclose(actual, expected, rtol=1e-13, equal_nan=False)