I am looking for a library routine that will calculate the lag 1 autocorrelation of a time series with a rolling window; meaning "slide a window of size N points along the time series, calculate the lag 1 autocorrelation for each window."

I have implemented an algorithm inspired by Wikipedia but would like something to compare the results with.

Is the mentioned routine available in for example R or Python?

**Contents**hide

#### Best Answer

In python, the pandas library has a function called `rolling_apply`

that, in conjunction with the `Series`

object method `.autocorr()`

should work. Here's an example for $N = 10$.

`import pandas as pd y = pd.Series(np.random.normal(size = 100)) pd.rolling_apply(y, 10, lambda x: pd.Series(x).autocorr()) `

Another option is `pandas.rolling_corr`

, so long as you shift the index of the series, and account for that shift in the size of the window:

`df = np.array([y[0:-1].values, y[1:].values]) df = df.transpose() df = pd.DataFrame(df) pd.rolling_corr(df[1], df[0], 9) `

If you'd like to examine autocorrelation for lags other than 1, the latter approach is more flexible. (In that case I'd advise special care to make sure your indexing matches your intended window; tripped me up at first.)

### Similar Posts:

- Solved – the autocorrelation function of a time series arising from computing a moving standard deviation
- Solved – Look ahead bias induced by standardization of a time series
- Solved – semi-automate MCMC convergence diagnostics to set the burn-in length
- Solved – Surrogate Time Series using Fourier Transform
- Solved – Surrogate Time Series using Fourier Transform