How to calculate Rolling Correlation with pandas?
Asked Answered
P

2

22

I understand how to calculate a rolling sum, std or average. Example:

df['MA10'] = df['Asset1'].rolling(10).mean()

But I don't understand the syntax to calculate the rolling correlation between two dataframes columns: df['Asset1'] and df['Asset2']

The documentation doesn't provide any example regarding the correlation.

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html

Any insights?

Thanks!

Pastor answered 21/8, 2018 at 21:52 Comment(0)
V
43

It's in there, even if hidden a bit:

df['Asset1'].rolling(10).corr(df['Asset2'])
Vinitavinn answered 21/8, 2018 at 22:3 Comment(1)
What's best way to visualize this kind of output?Antediluvian
B
1

It's a way slower (~3x) and a bit longer, but in some cases more illustrative:

df[['Asset1','Asset2']].rolling(10).corr().unstack().iloc[:,0]

Multiple assets:

df[['Asset1','Asset2','Asset3']].rolling(100).corr().unstack().iloc[:,[0,1]]
Byng answered 20/4, 2023 at 19:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.