Skip to content

Commit cc46392

Browse files
committed
ENH: rolling_corr_pairwise function re: #189
1 parent daf0b13 commit cc46392

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

RELEASE.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ pandas 0.6.1
5454
- Implement DataFrame.from_items alternate constructor (GH #444)
5555
- DataFrame.convert_objects method for inferring better dtypes for object
5656
columns (GH #302)
57+
- Add rolling_corr_pairwise function for computing Panel of correlation
58+
matrices (GH #189)
5759

5860
**Improvements to existing features**
5961

pandas/stats/moments.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
'rolling_sum', 'rolling_mean', 'rolling_std', 'rolling_cov',
1717
'rolling_corr', 'rolling_var', 'rolling_skew', 'rolling_kurt',
1818
'rolling_quantile', 'rolling_median', 'rolling_apply',
19+
'rolling_corr_pairwise',
1920
'ewma', 'ewmvar', 'ewmstd', 'ewmvol', 'ewmcorr', 'ewmcov']
2021

2122
def rolling_count(arg, window, time_rule=None):
@@ -87,6 +88,34 @@ def _flex_binary_moment(arg1, arg2, f):
8788
else:
8889
return _flex_binary_moment(arg2, arg1, f)
8990

91+
def rolling_corr_pairwise(df, window, min_periods=None):
92+
"""
93+
Computes pairwise rolling correlation matrices as Panel whose items are
94+
dates
95+
96+
Parameters
97+
----------
98+
df : DataFrame
99+
window : int
100+
min_periods : int, default None
101+
102+
Returns
103+
-------
104+
correls : Panel
105+
"""
106+
from pandas import Panel
107+
from collections import defaultdict
108+
109+
all_results = defaultdict(dict)
110+
111+
for i, k1 in enumerate(df.columns):
112+
for k2 in df.columns[i:]:
113+
corr = rolling_corr(df[k1], df[k2], window,
114+
min_periods=min_periods)
115+
all_results[k1][k2] = corr
116+
all_results[k2][k1] = corr
117+
118+
return Panel.from_dict(all_results).swapaxes('items', 'major')
90119

91120
def _rolling_moment(arg, window, func, minp, axis=0, time_rule=None):
92121
"""

pandas/stats/tests/test_moments.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,14 @@ def test_rolling_corr(self):
252252
result = mom.rolling_corr(a, b, len(a), min_periods=1)
253253
assert_almost_equal(result[-1], a.corr(b))
254254

255+
def test_rolling_corr_pairwise(self):
256+
panel = mom.rolling_corr_pairwise(self.frame, 10, min_periods=5)
257+
258+
correl = panel.ix[:, 1, 5]
259+
exp = mom.rolling_corr(self.frame[1], self.frame[5],
260+
10, min_periods=5)
261+
tm.assert_series_equal(correl, exp)
262+
255263
def test_flex_binary_frame(self):
256264
def _check(method):
257265
series = self.frame[1]

0 commit comments

Comments
 (0)