Skip to content

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

Open

Description

@dani2annotti

Describe the bug

A constant series (for example a halted or stale price) carries no autocorrelation, stationarity or fit information. adfuller already rejects it with "Invalid input, x is constant", but other functions do not check for it.

What they return then depends on whether x.mean() happens to be exact in floating point:

  • If it is exact (e.g. 101.37), they return NaN or an untyped error ("cannot convert float NaN to integer").
  • If it is not (e.g. 123.456), x - x.mean() leaves a constant residue of about 1e-14. The functions read it as data and report near-perfect autocorrelation (acf = 0.996, Ljung-Box p = 0.0), strong non-stationarity (KPSS 7.73, p = 0.01) and R² = -28.6.

The same kind of input therefore gives three different outcomes.

Code Sample, a copy-pastable example

import numpy as np
import statsmodels.api as sm
from statsmodels.tsa.stattools import acf, kpss, adfuller
from statsmodels.stats.diagnostic import acorr_ljungbox

for v in (101.37, 123.456):
    x = np.full(250, v)
    print("value", v, "mean - value:", x.mean() - v)
    print("  acf(1):", acf(x, nlags=1)[1])
    print("  Ljung-Box p:", acorr_ljungbox(x, lags=[10])["lb_pvalue"].iloc[0])
    print("  R2 on trend:", sm.OLS(x, sm.add_constant(np.arange(250.))).fit().rsquared)
    try:
        print("  kpss:", kpss(x)[:2])
    except ValueError as e:
        print("  kpss error:", e)
    try:
        adfuller(x)
    except ValueError as e:
        print("  adfuller:", e)

Expected Output

The same behaviour as adfuller for any constant input, whatever its value: raise a clear ValueError (or return NaN with a warning) when the series is constant, e.g. np.ptp(x) <= eps * max(1, abs(x).max()).

This should apply to acf/pacf (and therefore acorr_ljungbox and q_stat) and kpss. For a regression whose dependent variable is constant, R² should be NaN rather than a negative number.

Actual Output

value 101.37 mean - value: 0.0
  acf(1): nan
  Ljung-Box p: nan
  R2 on trend: -inf
  kpss error: cannot convert float NaN to integer
  adfuller: Invalid input, x is constant
value 123.456 mean - value: -1.4210854715202004e-14
  acf(1): 0.996
  Ljung-Box p: 0.0
  R2 on trend: -28.636
  kpss: (np.float64(7.733763837638378), np.float64(0.01))   # only an InterpolationWarning
  adfuller: Invalid input, x is constant

Versions

INSTALLED VERSIONS

Python: 3.13.17.final.0
OS: Linux x86_64

statsmodels

Installed: 0.15.0

Required Dependencies

cython: Not installed
numpy: 2.5.4
scipy: 1.16.3
pandas: 2.3.3
dateutil: 2.9.0.post0
patsy: 1.0.3

Optional Dependencies

matplotlib: 3.10.9
cvxopt: Not installed
joblib: 1.6.0


### Checklist

- [x] I have searched the [issue tracker](https://github.com/statsmodels/statsmodels/issues) for a similar issue and did not find one.

- [x] I have confirmed this bug exists on the [latest released version](https://pypi.org/project/statsmodels/) of statsmodels, or on the `main` branch.

Activity

  1. RaphRGR commented on Oct 30, 2026

    @RaphRGR
    Contributor

    Hi, I'd like to work on this!

    Looking at main:

    • For acf/pacf/kpss, would you prefer raising ValueError("Invalid input, x is constant") (consistent with adfuller) or returning NaNs?
    • For OLS.rsquared, returning np.nan when centered_tss == 0 seems straightforward.

    Would you prefer both handled in a single PR or split across tsa and regression?

  2. dani2annotti commented on Oct 31, 2026

    @dani2annotti
    Author

    Thanks @RaphRGR, great to have you on this! I'm not a maintainer, so they have the final say, but here is what I'd suggest after checking 0.15.0:

    1. acf / pacf / kpss: raise. adfuller already does if x.max() == x.min(): raise ValueError("Invalid input, x is constant"), and zivot_andrews raises the same error. Reusing that exact check and message keeps the module consistent. It's also exact for a constant array whatever the value, which matters here because the bug only shows up when x.mean() is not exact.

    2. OLS.rsquared: centered_tss == 0 is not enough. That's the same trap as in the issue. For x = np.full(250, 123.456) regressed on a constant and a trend:

    value centered_tss ssr rsquared
    101.37 0.0 2.2e-25 -inf
    123.456 5.0e-26 1.5e-24 -28.636

    So centered_tss == 0 fixes the first row but not the second. Checking the data itself (model.endog.max() == model.endog.min() -> np.nan) catches both, and rsquared_adj follows automatically.

    3. Scope is a bit wider than the issue. With the same constant series at 123.456:

    • pacf(x, nlags=1)[1] returns 1.0 (and 0.0 at 101.37)
    • ccf(x, x)[1] returns 1.0 (and nan at 101.37)
    • range_unit_root_test(x) returns (0.0, 0.01) for both values

    acorr_ljungbox and q_stat go through acf, so they're covered once acf checks.

    4. Splitting into one PR for tsa and one for regression seems easier to review, since the code paths don't overlap.

    Happy to review or test.

  3. bashtage commented on Nov 21, 2026

    @bashtage
    Member

    Happy for them to be worked in, but there has been a lot of activity so need to make sure this issue is still valid.

  4. DresdenGman commented on Nov 24, 2026

    @DresdenGman

    I re-checked this on current main (0.15.1.dev2189+g799354300): the tsa side is fixed — acf and pacf now return NaN for a constant series, acorr_ljungbox follows, and both kpss and adfuller reject the input.

    The remaining issue is OLS R-squared on a constant dependent variable: regressing x = np.full(250, 123.456) on a constant and a trend still gives -28.636, and using 101.37 gives -inf (plus a divide-by-zero warning from linear_model.py). As the reporter noted, checking the data directly (endog.max() == endog.min() -> NaN) makes sense since centered_tss == 0 misses the 123.456 case.

    Is the regression half still wanted as a separate PR (returning NaN for R-squared when endog is constant)? Also checking if @RaphRGR is still working on this, or if it's free to pick up. I'll wait until that's confirmed before starting.

  5. RaphRGR commented on Nov 26, 2026

    @RaphRGR
    Contributor

    Hi! Sorry for the late reply. I'm not actively working on this anymore, so please feel free to pick it up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions