Skip to content
DeepForgeby svx
All problems
MediumTime Seriests-029

Autocorrelation Lag k

Problem

Compute the sample autocorrelation at lag k as the ratio of autocovariances: rho(k) = gamma(k) / gamma(0), using the biased 1/n autocovariance.

Return 0.0 if k is out of range or the series has zero variance. For a non-constant series rho(0) equals 1.0.

Hint

Compute gamma(0) once and divide every lag by it.

Test cases

case 1
in: [[1,2,3,4],0]
expected: 1
case 2
in: [[1,2,3,4],1]
expected: 0.25
case 3
in: [[1,2,3,4],2]
expected: -0.3
case 4
in: [[5,5,5,5],1]
expected: 0
Starter codePython
def autocorrelation(series, k):
    # Your code here
    pass

4 test cases · run your code against them in the editor