时间序列数据在数据科学领域无处不在,在量化金融领域也十分常见,可以用于分析价格趋势,预测价格,探索价格行为等。
学会对时间序列数据进行可视化,能够帮助我们更加直观地探索时间序列数据,寻找其潜在的规律。
本文会利用Python中的matplotlib【1】库,并配合实例进行讲解。matplotlib库是一个用于创建出版质量图表的桌面绘图包(2D绘图库),是Python中最基本的可视化工具。
【工具】Python 3
【数据】Tushare
【注】示例注重的是方法的讲解,请大家灵活掌握。
1.单个时间序列
首先,我们从tushare.pro获取指数日线行情数据,并查看数据类型。
import tushare as ts import pandas as pd pd.set_option('expand_frame_repr', False) # 显示所有列 ts.set_token('your token') pro = ts.pro_api() df = pro.index_daily(ts_code='399300.SZ')[['trade_date', 'close']] df.sort_values('trade_date', inplace=True) df.reset_index(inplace=True, drop=True) print(df.head()) trade_date close 0 20050104 982.794 1 20050105 992.564 2 20050106 983.174 3 20050107 983.958 4 20050110 993.879 print(df.dtypes) trade_date object close float64 dtype: object
交易时间列'trade_date'
不是时间类型,而且也不是索引,需要先进行转化。
df['trade_date'] = pd.to_dateti<strong>本文来源gaodai#ma#com搞@@代~&码网</strong>me(df['trade_date']) df.set_index('trade_date', inplace=True) print(df.head()) close trade_date 2005-01-04 982.794 2005-01-05 992.564 2005-01-06 983.174 2005-01-07 983.958 2005-01-10 993.879
接下来,就可以开始画图了,我们需要导入matplotlib.pyplot【2】
,然后通过设置set_xlabel()
和set_xlabel()
为x轴和y轴添加标签。
import matplotlib.pyplot as plt ax = df.plot(color='') ax.set_xlabel('trade_date') ax.set_ylabel('399300.SZ close') plt.show()
matplotlib库中有很多内置图表样式可以选择,通过打印plt.style.available
查看具体都有哪些选项,应用的时候直接调用plt.style.use('fivethirtyeight')
即可。
print(plt.style.available) ['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test'] plt.style.use('fivethirtyeight') ax1 = df.plot() ax1.set_title('FiveThirtyEight Style') plt.show()