Skip to content

ENH: add a function to compute residuals for RollingOLS #7521

Closed

Description

@matthewgilbert

I'm wondering if it is possible to get residuals from the fit object of a statsmodels.regression.rolling.RollingOLS model? Something akin to statsmodels.regression.linear_model.RegressionResultsWrapper.resid, statsmodels.regression.recursive_ls.RecursiveLSResultsWrapper.resid or statsmodels.regression.recursive_ls.RecursiveLSResultsWrapper.resid_recursive?

(As an aside, @ChadFulton is there a DOI associated with Harvey 1989 that you mention here? As someone unfamiliar with the literature googling Harvey 1989 seems to return a reference to The condition of postmodernity by David Harvey which I don't think is the relevant text?)

My impression is that calculating the residuals from the rolling regression would be fairly straightforward? I.e. some generalized version of the following

import numpy
import pandas

from statsmodels.regression.rolling import RollingOLS

n = 1000
x = numpy.random.randn(n, 2)
beta = [2, 1]
y = (beta * x).sum(axis=1) + numpy.random.randn(n)

def rolling_residuals(rolling_parameters, X, y):
    y_hat = X * rolling_parameters
    return y - y_hat

rolling_ols_fit = RollingOLS(endog=y, exog=x, window=250, min_nobs=10).fit()
rolling_residuals(rolling_ols_fit.params, x, y)

Is there something I am overlooking for why calculating residuals in this way should be avoided?

Activity

  1. matthewgilbert commented on Jun 27, 2021

    @matthewgilbert
    Author

    Re DOI, apologies. some more searching turned up the relevant text

    Harvey, A. (1990). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge: Cambridge University Press. doi:10.1017/CBO9781107049994

    As an aside, it seems like most texts, e.g. Durbin & Koopman, reference what I believe is the original edition from 1989 but the only reference I could find online was to the reprint in 1990.

  2. ChadFulton commented on Jun 28, 2021

    @ChadFulton
    Member

    I have not used rolling OLS extensively for anything myself, but I suppose that the appropriate residuals depend on what you plan to do with them.

    For example, in your code you are computing residuals e_i as e_i = y_i - E[y_i | y_{i-1}, y_{i-2}, ..., y-{i-w}], where the window size is w. This is computing the residual for each datapoint i using the regression based on observation i and the previous w-1 observations.

    But there is no particular reason you couldn't compute them as, for example, the datapoint i and the subsequent w-1 observations, e_i = y_i - E[y_i | y_{i+1}, y_{i+2}, ..., y-{i+w}].

  3. ChadFulton commented on Jun 28, 2021

    @ChadFulton
    Member

    Re DOI, apologies. some more searching turned up the relevant text

    Harvey, A. (1990). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge: Cambridge University Press. doi:10.1017/CBO9781107049994

    As an aside, it seems like most texts, e.g. Durbin & Koopman, reference what I believe is the original edition from 1989 but the only reference I could find online was to the reprint in 1990.

    Thanks, this is a good point, and in any case we should provide the reference in the file where we cite it.

  4. bashtage commented on Jun 28, 2021

    @bashtage
    Member

    I implemented RollingOLS. I wasn't sure what residuals should look like since there are at least 2 different definitions. 1. A set of T-window+1 set of residuals for each regression run, or two a single set of rolling residuals that would only include the last observation in the residual, e.g., if using observations [12, 13, 14, 15, 16], then only y[16] - x[16]@beta[16].

    I think if you use pandas the second type are very easy to get

    import pandas as pd
    import statsmodels.api as sm
    import numpy as np
    from statsmodels.regression.rolling import RollingOLS
    
    index = pd.date_range("2000-1-1",periods=250, freq="M")
    y = pd.Series(np.random.standard_normal(250),index=index)
    x = sm.add_constant(pd.DataFrame(np.random.standard_normal((250,3)),index=index))
    x = sm.add_constant(pd.DataFrame(np.random.standard_normal((250,3)),index=index))
    
    res = RollingOLS(y,x, window=60).fit()
    rolling_resid = y - (res.params * x).sum(1)
  5. matthewgilbert commented on Jun 28, 2021

    @matthewgilbert
    Author

    Thanks @bashtage for clarifying that the ambiguity around what .resid would refer to in a rolling model is why there is no implementation. I will close this as a result, with the understanding that if a user wants residuals based on the second approach you describe they can extract them as you demonstrate above.

  6. bashtage commented on Jun 28, 2021

    @bashtage
    Member

    Code is pretty easy, and now this is documented.

  7. added this to the 0.13 milestone on Sep 9, 2021
  8. robertmartin8 commented on Jun 23, 2022

    @robertmartin8

    For people using RollingOLS.from_formula, this won't work because of Intercept and categorical encodings.

    The workaround is to first transform your data using patsy.

    Given some mod_str = "y ~ x1 + C(x2)" and your dataframe data:

    from patsy import dmatrix
    
    mod = rolling.RollingOLS.from_formula(mod_str, data=data, window=100).fit()
    reg_data = dmatrix(mod_str.split("~")[1], data)
    yhat = (mod.params * reg_data).sum(axis="columns")
    rolling_resid = data["y"] - yhat
  9. bashtage commented on Jun 28, 2022

    @bashtage
    Member

    I think that we should probably add a function that would handle the obvious cases.

  10. changed the title [-]Residuals for RollingOLS[/-] [+]ENH: add a function to compute residuals for RollingOLS[/+] on Jun 28, 2022
  11. self-assigned this
    on Jun 28, 2022
  12. AnthonyTremblayy commented on Apr 9, 2024

    @AnthonyTremblayy

    Has there been any further implementation for the second case (set of residuals for each regression run) in rollingOLS? I would need them to compute the standard deviations of the residuals in each run.

  13. bashtage commented on Apr 9, 2024

    @bashtage
    Member

    Rolling residual variance estimators should be easy to compute along side other rolling quantities. Since these would be a 1d array and well-defined, this doesn't create the issue that rolling residuals do.

  14. AnthonyTremblayy commented on Apr 10, 2024

    @AnthonyTremblayy

    Yes, storing a 1d-array of residual standard deviations should be easy enough, but I was wondering if there was an easy way to access them via the attributes without having to fork the function.

  15. shan3520 commented on Oct 5, 2026

    @shan3520
    Contributor

    Would be great if I could work on this, given your 2022 comment on "adding a function that would handle the obvious cases".

    Here is my proposal of adding get_resid(out_of_sample=False) method on rolling results that calculates residuals on request, addressing your concerns in #6986 about storing.

    It takes into account two cases. The default is to calculate y[t] - x[t] @ params[t] using coefficients from the window ending with t (and including t itself), following your second definition from 2021. When out_of_sample=True, one can calculate one-step ahead error: y[t] - x[t] @ params[t-1], again using coefficients from the previous window.

    Since it utilizes the design matrix of the model, it works well with from_formula and categoricals (workaround y - (params * x).sum(1) doesn't work with from_formula according to 2022 report). Moreover, it provides unweighted residuals for RollingWLS (as WLS.resid) while preserving pandas index in case of pandas inputs. It produces np.nan for values before the window has reached sufficient number of observations (min_nobs) and for observations with np.nan value. In order not to allocate much memory, the method doesn't provide residuals matrix for all windows.

    The feature is already implemented and tested on my fork, which has passed comparison with WLS fitted for each window and R's per-window lm().

    Is the API fine or would you rather prefer another name/resid property instead?

  16. added a commit that references this issue on Oct 6, 2026
    e0fc8ce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions