diff --git a/pandas/core/series.py b/pandas/core/series.py index 7400aa5bde2e7..ac8fada304cf9 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1513,6 +1513,42 @@ def autocorr(self): """ return self.corr(self.shift(1)) + def autocov(self, j=1, unbiased=False): + """ + j-lag autocovariance + + Parameters + ---------- + j: int, default 1 + Periods to lag the covariance calculation by + unbiased : boolean, default False + If true return an unbiased estimator of the autocovariance + + See Also + -------- + statsmodels.tsa.statstools.acovf for autocovariance function, which + returns an array of lagged autocovariances + + Returns + ------- + autocov : float + """ + n = len(self) + + if abs(j) >= n or n == 0: + return np.nan + + this = self - self.mean() + shifted = this.shift(-j) + + if unbiased: + d = n - j + else: + d = n + + return float(np.correlate(this[:n - j].values, + shifted[:n - j].values)) / d + def clip(self, lower=None, upper=None, out=None): """ Trim values at input threshold(s) diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 9474f6061f936..1826916a985ba 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -1841,6 +1841,19 @@ def test_cov(self): cp[:] = np.nan self.assert_(isnull(cp.cov(cp))) + def test_autocov(self): + + ts = Series([1, 2, 3] * 2) + + #too big of lag + self.assert_(np.isnan(ts.autocov(j=len(ts) + 1))) + + #test calculations + self.assertAlmostEqual(ts.autocov(j=0), 2.0/3) + self.assertAlmostEqual(ts.autocov(j=1), -1.0/6) + self.assertAlmostEqual(ts.autocov(j=2), -1.0/3) + + def test_copy(self): ts = self.ts.copy()