• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python实现时间序列可视化的方法

python 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

时间序列数据在数据科学领域无处不在,在量化金融领域也十分常见,可以用于分析价格趋势,预测价格,探索价格行为等。

学会对时间序列数据进行可视化,能够帮助我们更加直观地探索时间序列数据,寻找其潜在的规律。

本文会利用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()

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python实现时间序列可视化的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址