def rolling_corr(x, y, **kwargs): """ Rolling correlation between columns from x and y. """ def rolling(dataframe, *args, **kwargs): ret = dataframe.copy() for col in ret: ret[col] = rolling_m(ret[col], *args, **kwargs) return ret n, k = x.shape EX = rolling(x, **kwargs) EY = rolling(y, **kwargs) EX2 = rolling(x ** 2, **kwargs) EY2 = rolling(y ** 2, **kwargs) RXY = np.zeros((n, k, k)) for i, col_x in enumerate(x): for j, col_y in enumerate(y): DX = EX2[col_x] - EX[col_x] ** 2 DY = EY2[col_y] - EY[col_y] ** 2 RXY[:, i, j] = rolling_m(x[col_x] * y[col_y], **kwargs) - EX[col_x] * EY[col_y] RXY[:, i, j] = RXY[:, i, j] / np.sqrt(DX * DY) return RXY, EX.values
def rolling(dataframe, *args, **kwargs): ret = dataframe.copy() for col in ret: ret[col] = rolling_m(ret[col], *args, **kwargs) return ret