I have two matrices with the same shape:
import numpy as np
from scipy.stats import pearsonr
np.random.seed(10)
a = np.random.random(30).reshape(10,3)
b = np.random.random(30).reshape(10,3)
i.e., 10 rows and three columns. I need the rolling correlation of the columns with the same column index in each matrix. The slow way is:
def roll_corr((a, b), window):
out = np.ones_like(a)*np.nan
for i in xrange(window-1, a.shape[0]):
#print "%d --> %d" % ((i-(window-1)), i)
for j in xrange(a.shape[1]):
out[i, j] = pearsonr(
a[(i-(window-1)):(i), j], b[(i-(window-1)):(i), j]
)[0]
return out
With results for roll_corr((a, b), 5)
as I want,
array([[ nan, nan, nan],
[ nan, nan, nan],
[ nan, nan, nan],
[ nan, nan, nan],
[ 0.28810753, 0.27836622, 0.88397851],
[-0.04076151, 0.45254981, 0.83259104],
[ 0.62262963, -0.4188768 , 0.35479134],
[ 0.13130652, -0.91441413, -0.21713372],
[ 0.54327228, -0.91390053, -0.84033286],
[ 0.45268257, -0.95245888, -0.50107515]])
The question is: is there a more idiomatic numpy way to do this? Vectorized? Strides trick? Numba?
I have searched but have not found this. I no not want to use pandas; must be numpy.