Matlab\'s cross-correlation function xcorr(x,y,maxlags) has an option maxlag, which returns the cross-correlation sequence over the lag range
This is my implementation of the lead-lag correlation, but it is limited to be 1-D and not guaranteed to be the best in terms of efficient. It uses the scipy.stats.pearsonr to the do the core computation, so also returned is the p value for the coefficient. Please modify to optimize based on this straw man.
def lagcorr(x,y,lag=None,verbose=True):
'''Compute lead-lag correlations between 2 time series.
,: 1-D time series.
: lag option, could take different forms of :
if 0 or None, compute ordinary correlation and p-value;
if positive integer, compute lagged correlation with lag
upto ;
if negative integer, compute lead correlation with lead
upto <-lag>;
if pass in an list or tuple or array of integers, compute
lead/lag correlations at different leads/lags.
Note: when talking about lead/lag, uses as a reference.
Therefore positive lag means lags by , computation is
done by shifting to the left hand side by with respect to
.
Similarly negative lag means leads by , computation is
done by shifting to the right hand side by with respect to
.
Return : a (n*2) array, with 1st column the correlation
coefficients, 2nd column correpsonding p values.
Currently only works for 1-D arrays.
'''
import numpy
from scipy.stats import pearsonr
if len(x)!=len(y):
raise('Input variables of different lengths.')
#--------Unify types of -------------
if numpy.isscalar(lag):
if abs(lag)>=len(x):
raise('Maximum lag equal or larger than array.')
if lag<0:
lag=-numpy.arange(abs(lag)+1)
elif lag==0:
lag=[0,]
else:
lag=numpy.arange(lag+1)
elif lag is None:
lag=[0,]
else:
lag=numpy.asarray(lag)
#-------Loop over lags---------------------
result=[]
if verbose:
print '\n#: Computing lagged-correlations at lags:',lag
for ii in lag:
if ii<0:
result.append(pearsonr(x[:ii],y[-ii:]))
elif ii==0:
result.append(pearsonr(x,y))
elif ii>0:
result.append(pearsonr(x[ii:],y[:-ii]))
result=numpy.asarray(result)
return result