相关性
在构建机器学习模型之前检查相关性很有用,因为可以看到哪些特征与目标的相关性最强。常用的是皮尔逊相关系数,它只能捕捉线性关系。一般会假设数据服从正态分布,我们可以通过直方图直观观察。高度相关的变量其皮尔逊相关系数接近 1(正相关)或 -1(负相关)。接近 0 表示两个变量不存在线性相关。
如果我们对过去价格变动和未来价格变动使用相同的时间窗口,就能判断股票价格是均值回归(来回波动)还是趋势跟随(最近上涨则继续上涨)。
本练习是课程的一部分
Python 金融机器学习
练习说明
使用 lng_df DataFrame 及其 Adj_Close:
- 使用 pandas 的
.shift(-5)创建 5 天后的未来价格(命名为5d_future_close)。 - 对
5d_future_close和Adj_Close使用pct_change(5),分别创建未来 5 天的百分比价格变化(5d_close_future_pct)和当前 5 天的百分比价格变化(5d_close_pct)。 - 在
lng_df上使用.corr()检查这两个 5 天百分比价格变化列之间的相关性。 - 使用
plt.scatter()绘制5d_close_pct与5d_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()