開始使用免費開始

產生隨機漫步

股價的「報酬」常被建模為白噪音,而股價「價格」本身通常遵循隨機漫步。也就是說,今天的價格等於昨天的價格再加上一些隨機雜訊。

你將模擬一檔股票隨時間變動的價格,起始價格為 100,且每天會隨機上漲或下跌一個數值。然後,將模擬出的股價繪圖。若你多次按下「Run Code」按鈕,你會看到多種不同的實現結果。

本練習屬於課程

Python 中的時間序列分析

檢視課程

練習說明

  • 使用 np.random.normal() 產生平均數為 0、標準差為 1 的 500 個常態分配「步伐」,其中平均數的參數為 loc,標準差的參數為 scale
  • 模擬股價 P
    • 使用 numpy 的 .cumsum() 方法對隨機 steps 進行累加。
    • P 加上 100,讓起始股價為 100。
  • 繪製模擬的隨機漫步圖形

動手互動練習

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

# Generate 500 random steps with mean=0 and standard deviation=1
steps = np.random.normal(loc=___, scale=___, size=___)

# Set first element to 0 so that the first price will be the starting stock price
steps[0]=0

# Simulate stock prices, P with a starting price of 100
P = ___ + np.cumsum(___)

# Plot the simulated stock prices
plt.plot(___)
plt.title("Simulated Random Walk")
plt.show()
編輯並執行程式碼