Measure the correlation between stock and bond returns with pandas corr and NumPy corrcoef, compute rolling correlations, and compare two window lengths.
After this lesson, you can compute the correlation between two return series and see how it changes from one window to the next.
How do I measure the correlation of two return series?
returns["stock_return"].corr(returns["bond_return"]) computes the Pearson correlation of the two series, and over the six made-up days it is 0. On the first three days, the bond’s return is the negative of the stock’s, and on the last three days, the two are equal, so the two halves cancel.
Here \(R_S\) and \(R_B\) are the stock’s and the bond’s returns, \(\operatorname{Cov}\) their covariance and \(\sigma\) each standard deviation. The correlation lies between −1 and 1, and returns in percent or in decimals give the same value.
The returns are daily returns in percent of AAA’s stock and BBB’s bond. .corr() pairs the returns by their date labels, and np.corrcoef pairs them by position and returns the matrix of all pairs, with each series’ correlation of 1 with itself on the diagonal.
The following box computes the correlation both ways.
How does the correlation change from window to window?
.rolling(3).corr() computes one correlation per window of three days, and it moves from −1 on 4 March, a window with opposite moves, to 1 on 9 March, a window with equal moves. A window of four days on 9 March also holds 4 March, when the stock gained 2% and the bond lost 2%, so its correlation falls to 0.455.
.rolling(3) returns a rolling object that only defines the windows, as in the lesson on rolling, and .corr(bond_return) on it computes the correlation inside each window. A short window follows changes quickly but rests on few days. Real data use longer windows, such as 60 days.
The following box computes both rolling correlations side by side.