開始使用免費開始

為波動度計算共變異數

在 MPT 中,我們用波動度來量化風險。計算投資組合波動度的數學推導較為複雜,且需要每日報酬率的共變異數。現在我們要迴圈走訪 returns_monthly DataFrame 中的每個月份,並計算該月份每日報酬率的共變異數。

使用 pandas 的日期時間索引時,可以用 df.index.monthdf.index.year 取得月份與年份。我們會用這兩者替 returns_daily 建立一個篩選條件,讓它在迴圈中擷取目前月份與年份的每日報酬。接著用這個篩選條件來子集化 DataFrame,如:df[mask]。這會在每次迴圈中,取得 returns_daily 當前月份與年份的資料。最後,使用 pandas 的 .cov() 方法計算每日報酬的共變異數。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 迴圈走訪 returns_monthly 的索引。
  • returns_daily 建立一個篩選條件,利用 returns_monthly 的當前月份與年份,並與迴圈中 i 的當前月份與年份相符。
  • returns_daily 上套用該篩選條件,並使用 .cov() 計算共變異數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Daily covariance of stocks (for each monthly period)
covariances = {}
rtd_idx = returns_daily.index
for i in returns_monthly.____:    
    # Mask daily returns for each month and year, and calculate covariance
    mask = (rtd_idx.month == i.month) & (rtd_idx.____ == i.____)
    
    # Use the mask to get daily returns for the current month and year of monthy returns index
    covariances[i] = returns_daily[____].cov()

print(covariances[i])
編輯並執行程式碼