開始使用免費開始

相關性

在建立機器學習模型之前先查看相關性很有幫助,因為可以看到哪些特徵與目標的相關程度最高。常用皮爾森相關係數,它只偵測線性關係。一般也會假設資料近似常態分布,我們可以從直方圖「用眼睛估」一下。高度相關的變數,其皮爾森相關係數會接近 1(正相關)或 -1(負相關)。接近 0 的值代表兩個變數之間沒有線性相關。

如果我們對「過去的價格變動」與「未來的價格變動」使用相同的時間區間,就可以觀察股價是均值回歸(來回震盪)還是趨勢追隨(最近在上漲時未來也較可能續漲)。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

使用 lng_df DataFrame 及其 Adj_Close

  • 以 pandas 的 .shift(-5) 建立 5 天後的未來價格(命名為 5d_future_close)。
  • 5d_future_closeAdj_Close 使用 pct_change(5),分別建立未來 5 天的價格百分比變化(5d_close_future_pct)與當前 5 天的價格百分比變化(5d_close_pct)。
  • lng_df 上用 .corr() 檢視這兩個 5 天百分比變化欄位之間的相關性。
  • 使用 plt.scatter(),繪製 5d_close_pct5d_close_future_pct 的散佈圖。

動手互動練習

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

# Create 5-day % changes of Adj_Close for the current day, and 5 days in the future
lng_df['5d_future_close'] = lng_df['Adj_Close'].shift(____)
lng_df['5d_close_future_pct'] = lng_df['5d_future_close'].pct_change(5)
lng_df['5d_close_pct'] = lng_df['Adj_Close'].pct_change(____)

# Calculate the correlation matrix between the 5d close pecentage changes (current and future)
corr = lng_df[['5d_close_pct', '5d_close_future_pct']].____
print(corr)

# Scatter the current 5-day percent change vs the future 5-day percent change
plt.scatter(lng_df['5d_close_pct'], lng_df[____])
plt.show()
編輯並執行程式碼