roll_corr

Defined in fynance.features.roll_functions

roll_corr(x, y, w=63)[source]

Trailing rolling Pearson correlation between two aligned 1-D series.

\[roll\_corr^w_t(x, y) = \frac{ \sum_{i=t-w+1}^{t} (x_i - \bar{x}_t)(y_i - \bar{y}_t) }{ \sqrt{\sum_{i=t-w+1}^{t} (x_i - \bar{x}_t)^2} \sqrt{\sum_{i=t-w+1}^{t} (y_i - \bar{y}_t)^2} }\]

over the trailing window \([t - w + 1, t]\) (inclusive of t, see roll_cov). The 1/w normalization of the covariance and the two variances cancels out, so the result does not depend on ddof.

Parameters:
xnp.ndarray[float64, ndim=1]

First series. Cast to float64 if needed; must not contain NaN.

ynp.ndarray[float64, ndim=1]

Second series, same length as x. Cast to float64 if needed; must not contain NaN.

wint, optional

Size of the trailing window, must be an integer >= 2. Default is 63.

Returns:
np.ndarray[float64, ndim=1]

Trailing rolling correlation, in [-1, 1]. The first w - 1 entries are np.nan (insufficient history). If either series has zero variance within a window, that entry is np.nan (checked explicitly before dividing — no RuntimeWarning is raised).

See also

roll_cov, roll_beta

Examples

>>> x = np.array([1., 2., 3., 4., 5.])
>>> y = 2 * x
>>> roll_corr(x, y, w=3)
array([nan, nan,  1.,  1.,  1.])