Skip to content

ENH: autocov function for Series #1991

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down