Skip to content

BUG: reject constant series in acf and ccf, fix pacf demeaning - #10701

Merged
bashtage merged 1 commit into
statsmodels:mainfrom
RaphRGR:fix-tsa-constant-series
Nov 15, 2026
Merged

bashtage merged 1 commit into
statsmodels:mainfrom
RaphRGR:fix-tsa-constant-series

Conversation

@RaphRGR

@RaphRGR RaphRGR commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

A constant series carries no autocorrelation information. When x.mean() is not exactly representable in floating point (e.g. 123.456), x - x.mean() leaves a constant residual (~1e-14) that was misinterpreted as near-perfect autocorrelation (acf = 0.996, pacf = 1.0, Ljung-Box p = 0.0).

This PR addresses the time series (tsa) portion of #10647:

  • In pacf (all methods) and acf, return 1.0 for lag 0 and NaN for lags 1 and higher when the input series is constant, with valid confidence intervals ([1.0, 1.0] at lag 0, NaN elsewhere).

  • In acovf, check for constant series in both regular and missing (missing in ("drop", "conservative")) branches using np.ptp, ensuring exact zero demeaned values.

  • In ccf, return NaN for all lags when either series is constant (with or without missing values).

  • Silence 0/0 scalar division warnings in levinson_durbin and pacf_burg.

  • Add release note in version0.15.1.rst and .. versionchanged:: 0.15.1 notes in docstrings.

  • Add parametrized regression tests in test_stattools and test_diagnostic covering all PACF estimation methods, exact/inexact constants, lengths, and missing value options, skipping linear algebra warnings on Pyodide/WASM.

  • closes BUG: acf, acorr_ljungbox, kpss and OLS rsquared return confident results on a constant series when the mean is not exactly representable (adfuller already rejects constant input) #10647 (partially, tsa module)

  • tests added / passed.

  • code/documentation is well formatted.

  • properly formatted commit message. See
    NumPy's guide.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Gemini / Antigravity.
    Used for: drafting the implementation, and writing regression tests.
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.
Details

Notes:

  • It is essential that you add a test when making code changes. Tests are not
    needed for doc changes.
  • When adding a new function, test values should usually be verified in another package (e.g., R/SAS/Stata).
  • When fixing a bug, you must add a test that would produce the bug in main and
    then show that it is fixed with the new code.
  • New code additions must be well formatted. Changes should pass ruff. You can
    verify your changes are well formatted by running
    ruff check . --fix
    
    assuming ruff is installed. While passing this test is not required, it is good practice and it help
    improve code quality in statsmodels.
  • Docstring additions must render correctly, including escapes and LaTeX.
  • If AI tools were used to help write this PR, see the
    AI Policy for what disclosure
    and review is expected of you before submitting.

Copilot AI balanced review requested due to automatic review settings November 8, 2026 15:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@bashtage

bashtage commented Nov 8, 2026

Copy link
Copy Markdown
Member

I think this is not the correct decision. Constant series have a clear acf - all exactly 0, in the same sense that the Corr(a,b)=0 if a and b are constants. Need to think more about pacf.

Do you know what other statistical software do?

@RaphRGR

RaphRGR commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback!

Regarding what other statistical software packages and libraries do for a constant series:

  1. Python ecosystem:

    • scipy.stats.pearsonr(x, x) returns nan.
    • numpy.corrcoef(x, x) returns nan.
    • pandas.Series(x).autocorr() returns nan.
  2. R:

    • stats::acf(x, plot=FALSE) returns an array of NaN for all lags.
    • stats::pacf(x, plot=FALSE) returns an array of NaN for all lags.
    • stats::ccf(x, y, plot=FALSE) returns an array of NaN for all lags.

Also, in statsmodels prior to this PR, when the mean was exact (e.g. x = np.full(250, 101.37) or np.ones(100)), acovf produced exact zeros and acf naturally returned nan (due to 0.0 / 0.0). The issue in #10647 was specifically that when x.mean() has floating-point truncation (e.g. 123.456), x - x.mean() leaves a ~1e-14 residual, yielding 0.996 instead of nan.

Raising ValueError was initially chosen following the discussion on the issue (#10647) to stay consistent with adfuller and zivot_andrews, but now that you mention it, I completely agree that returning a value without crashing pipelines is much better suited for acf and ccf.

Given that R, SciPy, NumPy, and Pandas all return NaN (since $\text{Corr} = 0/0$ is mathematically undefined, and $\text{ACF}(0) = 1$ would otherwise conflict with all zeros), would you prefer acf and ccf to return an array of np.nan (with or without a warning), rather than raising ValueError?

@bashtage

bashtage commented Nov 8, 2026

Copy link
Copy Markdown
Member

Yes, it seems NaN is the best and most consistent choice here.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ptp saves a pass through the array. Also should return nan if not already in these cases.

Comment thread statsmodels/tsa/stattools/_stattools.py Outdated
)
x = array_like(x, "x")
x_valid = x[~np.isnan(x)] if missing in ("drop", "conservative") else x
if x_valid.size > 0 and x_valid.max() == x_valid.min():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should you use ptp.

Comment thread statsmodels/tsa/stattools/_stattools.py Outdated
# then repeats the calculation and its warnings
with np.errstate(all="ignore"):
x = x - x.mean()
if x.size > 0 and x.max() == x.min():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment

Comment thread statsmodels/tsa/stattools/_stattools.py Outdated
x = array_like(x, "x")
if demean:
x = x - x.mean()
if x.size > 0 and x.max() == x.min():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same

RaphRGR added a commit to RaphRGR/statsmodels that referenced this pull request Nov 8, 2026
…#10701

- In acf and ccf, return NaN (and NaN confint/qstats) for constant series.
- In acf, _pacf_yw_levinson, and pacf_burg, use np.ptp(x) == 0.
- Update tests for acf, ccf, and acorr_ljungbox to assert NaN results.

References statsmodels#10647
@RaphRGR
RaphRGR requested a review from bashtage November 8, 2026 23:06
@bashtage

Copy link
Copy Markdown
Member

I think it need a few more changes:

  • Add an exact constant check on the raw input at the top of pacf (all methods) and in acovf's missing branch
  • Return NaN for lags 1.. with lag 0 equal to 1
  • Silence the 0/0 warnings in ld/ldb/burg
  • Delete the acf early return (and the zivot_andrews and nlags changes, or move them)
  • Rewrite the tests as one parametrized test over pacf methods, constants, lengths and acf/ccf with and without NaN
  • Add the release note and versionchanged notes
  • Update the PR body, squash.

@bashtage

Copy link
Copy Markdown
Member

Looks like there is a pyodide failure that needs fixing. Pyodide doesn't handle linear algebra errors correctly as a rule.

@bashtage

Copy link
Copy Markdown
Member

Pull the warning test into a new test and skip on WASM.

@RaphRGR
RaphRGR force-pushed the fix-tsa-constant-series branch from 1c8b7f2 to 649b02c Compare November 14, 2026 16:02
A constant series carries no autocorrelation information. When x.mean()
is not exactly representable in floating point (e.g. 123.456), x - x.mean()
leaves a constant residual (~1e-14) that was misinterpreted as near-perfect
autocorrelation.

- In acf and pacf (all methods), return 1.0 for lag 0 and NaN for lags 1
  and higher when the input is constant.
- In acovf, check for constant series in both the demean and missing
  branches, returning exact zeros.
- In ccf, return NaN for all lags when either series is constant.
- Silence 0/0 scalar division warnings in levinson_durbin and pacf_burg.
- Add release note and versionchanged notes for 0.15.1.
- Add comprehensive parametrized tests across methods, constants, lengths,
  and missing values, skipping linear algebra warnings on WASM.

Closes statsmodels#10647
@RaphRGR
RaphRGR force-pushed the fix-tsa-constant-series branch from 649b02c to 2152cbc Compare November 14, 2026 16:07
@RaphRGR

RaphRGR commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I've addressed all your feedback, updated the tests, added the release notes, rebased and squashed the commits.

@bashtage

Copy link
Copy Markdown
Member

Thanks for the fixes.

@bashtage
bashtage merged commit 4a1625e into statsmodels:main Nov 15, 2026
14 checks passed
bashtage added a commit that referenced this pull request Nov 16, 2026
#10701 returns NaN for a constant series before any shape check.
Invalid input that raised on main therefore returned NaN: ccf with a
constant 2-D x (or y) raised "in1 and in2 should have the same
dimensionality" in ccovf and pacf of a constant (n, 2) array raised in
the method (for example "expecting a vector" for yw).

Only run the constant early return in ccf when both inputs are 1-D, and
in pacf when x is a vector or one column; all other shapes take the
path of main and raise as before. Valid input is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
bashtage added a commit that referenced this pull request Nov 16, 2026
The bullet of #10701 describes changed results of existing functions, so
it belongs at the end of "Behavior changes" and not in the middle of the
Time series analysis bug fixes. Say what users saw before: acf was nan
at all lags when the mean of the constant is exact and showed
autocorrelations near 1 (0.99 at lag 1 for 100 observations of 101.37)
otherwise, and pacf was nan only for some constants and methods. Add that
qstat and pvalues of acf and acorr_ljungbox are nan for a constant series.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
bashtage added a commit that referenced this pull request Nov 16, 2026
Follow-up to #10701. Add tests that invalid shapes of a constant series
still raise in ccf (x or y with ndim 2) and pacf (constant (n, 2) array,
same error as for a non-constant array), and that a single constant
column gives NaN.

Parametrize the acf and ccf constant tests over adjusted, fft, missing
and nlags (the nlags=None branch of the ccf shortcut was untested) and
check that the shortcut comes before the fft path of scipy, which warns
about NaN, for a series that is constant once the NaN is dropped.

Drop test_pacf_yw_constant_warning: it pinned the minimum-norm lstsq
values of a singular system, and test_yw_singular covers the warning.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
bashtage added a commit that referenced this pull request Nov 16, 2026
BUG: Follow up #10701, keep raising for a constant 2-D ccf and pacf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants