多檔股票的年度報酬率相關性
你已在影片中看到如何計算相關性,並將結果視覺化。
在本練習中,我們提供了 Apple(AAPL)、Amazon(AMZN)、IBM(IBM)、WalMart(WMT)與 Exxon Mobile(XOM)自 2001 年 7 月到 2017 年 5 月底,最近 4,000 個交易日的歷史股價。
你將計算年度(年末)報酬率、所有股票兩兩之間的相關性,並將結果以含註解的熱度圖呈現。
本練習屬於課程
Manipulating Time Series Data in Python
練習說明
我們已經將 pandas 匯入為 pd、seaborn 匯入為 sns,以及將 matplotlib.pyplot 匯入為 plt。我們也已將 5 檔股票的每日收盤價載入到名為 data 的變數中。
- 使用
.info()檢視資料。 - 對
data套用.resample()並使用年終頻率(別名:'A'),然後從每個子期間選取.last()價格;將結果指定為annual_prices。 - 對
annual_prices套用.pct_change(),計算得到annual_returns。 - 對
annual_returns套用.corr(),計算得到correlations並印出結果。 - 將
correlations視覺化為帶註解的sns.heatmap()。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Inspect data here
print(____)
# Calculate year-end prices here
annual_prices = ____
# Calculate annual returns here
annual_returns = ____
# Calculate and print the correlation matrix here
correlations = ____
print(____)
# Visualize the correlations as heatmap here