計算股票價格變動
你已在影片中學到如何用當期與位移後的價格來計算報酬率。現在你要練習類似的計算,從當期與位移後的價格求出絕對變動,並將結果與 .diff() 函式比較。
本練習屬於課程
Manipulating Time Series Data in Python
練習說明
我們已經將 pandas 匯入為 pd,並將 matplotlib.pyplot 匯入為 plt。也已載入 2013 到 2015 年的 Yahoo 股價、把頻率設為商業日,並將結果指定給 yahoo。
- 建立一個名為
shifted_30的新欄位,其內容為將'price'向未來位移 30 個商業日後的值。 - 以
'price'減去'shifted_30',並將結果指定到新欄位'change_30'。 - 套用
.diff(),將periods設為 30,並將結果指定到新欄位'diff_30'。 - 檢視
yahoo的最後 5 列以驗證計算。 - 使用
.sub()方法以change_30減去diff_30,並列印結果的.value_counts(),以顯示兩個欄位相等。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Created shifted_30 here
yahoo['shifted_30'] = ____
# Subtract shifted_30 from price
yahoo['change_30'] = ____
# Get the 30-day price difference
yahoo['diff_30'] = ____
# Inspect the last five rows of price
print(____)
# Show the value_counts of the difference between change_30 and diff_30
print(____)