開始使用免費開始

投資組合模擬 - 第一部分

接下來幾個練習,你會計算股票投資組合的期望報酬,並刻畫其不確定性。

假設你在由多檔股票組成的投資組合中投入了 $10,000。你想評估此投資組合在 10 年內的表現。你可以調整整體的期望報酬率與波動度(報酬率的標準差)。假設報酬率服從常態分佈。

先來撰寫一個函式:輸入本金(初始投資)、年數、期望報酬率與波動度,並回傳 10 年後投資組合的總價值。

完成本練習後,你會有一個可以呼叫來評估投資組合績效的函式。

本練習屬於課程

Python 的統計模擬

檢視課程

練習說明

  • 在函式定義中,接受四個引數作為輸入:年份 yrs、期望報酬率 avg_return、波動度 sd_of_return,以及本金(初始投資)principal
  • 將每一年的報酬率 rates 以常態隨機變數進行模擬。
  • end_return 初始化為輸入的 principal。在 for 迴圈中,每年用當年的報酬率放大 end_return
  • 使用 portfolio_return() 計算並列印 result

動手互動練習

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

# rates is a Normal random variable and has size equal to number of years
def portfolio_return(____):
    np.random.seed(123)
    rates = ____(loc=avg_return, scale=sd_of_return, size=yrs)
    # Calculate the return at the end of the period
    end_return = ____
    for x in rates:
        end_return = end_return*(1+____)
    return end_return

result = portfolio_return(yrs = 5, avg_return = 0.07, sd_of_return = 0.15, principal = 1000)
print("Portfolio return after 5 years = {}".format(____))
編輯並執行程式碼