在时间上平移股票价格
您在视频中看到的第一个时间序列操作方法是 .shift(),它可以将 Series 或 DataFrame 中的所有值沿着 DateTimeIndex 按给定的期数平移到不同的时间点。
让我们用它把 Google 的股价序列分别向过去和未来平移 90 个工作日,并进行可视化对比。
本练习是课程的一部分
Python 中的时间序列数据处理
练习说明
我们已经将 pandas 以 pd 导入,并将 matplotlib.pyplot 以 plt 导入。
- 使用
pd.read_csv()导入'google.csv',将'Date'解析为日期,设为index,并赋值给google。 - 使用
.asfreq()将google的频率设置为工作日频率。 - 在
google中新增lagged和shifted两列,分别包含将Close向过去和平移向未来 90 个工作日得到的值。 - 绘制
google的这三列。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import data here
google = ____
# Set data frequency to business daily
google = ____
# Create 'lagged' and 'shifted'
google['lagged'] = ____
google['shifted'] = ____
# Plot the google price series