開始使用免費開始

多檔股票的年度報酬率相關性

你已在影片中看到如何計算相關性,並將結果視覺化。

在本練習中,我們提供了 Apple(AAPL)、Amazon(AMZN)、IBM(IBM)、WalMart(WMT)與 Exxon Mobile(XOM)自 2001 年 7 月到 2017 年 5 月底,最近 4,000 個交易日的歷史股價。

你將計算年度(年末)報酬率、所有股票兩兩之間的相關性,並將結果以含註解的熱度圖呈現。

本練習屬於課程

Manipulating Time Series Data in Python

檢視課程

練習說明

我們已經將 pandas 匯入為 pdseaborn 匯入為 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

編輯並執行程式碼