股票與債券的相關性
投資人常會關心兩種資產報酬率之間的相關性,以做資產配置與避險。在這個練習中,你將嘗試回答:股票和公債之間是正相關還是負相關?散佈圖也很適合用來視覺化兩個變數之間的相關性。
請記得,應該對「百分比變動」而不是原始水準來計算相關性。
股票價格與 10 年期債券殖利率已合併在名為 stocks_and_bonds 的 DataFrame 中,欄位為 SP500 與 US10Y。
pandas 與繪圖模組已為你匯入。課程其餘部分中,pandas 以 pd 匯入,matplotlib.pyplot 以 plt 匯入。
本練習屬於課程
Python 中的時間序列分析
練習說明
- 使用
.pct_change()方法對stocks_and_bondsDataFrame 計算百分比變動,並將新 DataFrame 命名為returns。 - 在
returnsDataFrame 中,使用 Series 的.corr()方法(語法為series1.corr(series2))計算SP500與US10Y欄位的相關性。 - 繪製股票與債券殖利率百分比變動的散佈圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Compute percent change using pct_change()
returns = stocks_and_bonds.___
# Compute correlation using corr()
correlation = ___
print("Correlation of stocks and interest rates: ", correlation)
# Make scatter plot
plt.___
plt.show()