Search code examples
pythonfunctionnumpytime-seriesautocorrelation

Trying to calculate autocorrelation coefficient with function


I am trying to replicate this autocorrelation formula, where T is number of samples and k is number of lags.

Autocorrelation formula


Solution

  • The autocorrelation for the first element is 1.0 per definition. For the remaining elements we use a list comprehension (please note that the formula in the questions assumes indexing from 1 to T whereas python arrays are 0 based):

    mean = np.mean(x)    
    denominator = np.sum((x-mean)**2)
    [1.0] + [np.sum((x[j:]-mean) * (x[:-j]-mean)) / denominator for j in range(1, len(x))]