美文网首页大数据 爬虫Python AI Sql随笔-生活工作点滴Python,web开发,前端技术分享
最简洁的Python时间序列可视化:数据科学分析价格趋势,预测价

最简洁的Python时间序列可视化:数据科学分析价格趋势,预测价

作者: 一墨编程学习 | 来源:发表于2019-07-16 14:50 被阅读5次

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

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

    本文会利用Python中的matplotlib【1】库,并配合实例进行讲解。matplotlib库是⼀个⽤于创建出版质量图表的桌⾯绘图包(2D绘图库),是Python中最基本的可视化工具。

    【工具】Python 3

    【数据】Tushare

    【注】示例注重的是方法的讲解,请大家灵活掌握。

    01

    单个时间序列

    首先,我们从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_datetime(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()
    
    

    02

    设置更多细节

    上面画出的是一个很简单的折线图,其实可以在plot()里面通过设置不同参数的值,为图添加更多细节,使其更美观、清晰。

    figsize(width, height)设置图的大小,linewidth设置线的宽度,fontsize设置字体大小。然后,调用set_title()方法设置标题。

    ax = df.plot(color='blue', figsize=(8, 3), linewidth=2, fontsize=6)
    ax.set_title('399300.SZ close from 2005-01-04 to 2019-07-04', fontsize=8)
    plt.show()
    
    

    如果想要看某一个子时间段内的折线变化情况,可以直接截取该时间段再作图即可,如df['2018-01-01': '2019-01-01']

    df_subset_1 = df['2018-01-01':'2019-01-01']
    ax = df_subset_1.plot(color='blue', fontsize=10)
    plt.show()
    
    

    如果想要突出图中的某一日期或者观察值,可以调用.axvline().axhline()方法添加垂直和水平参考线。

    ax = df.plot(color='blue', fontsize=6)
    ax.axvline('2019-01-01', color='red', linestyle='--')
    ax.axhline(3000, color='green', linestyle='--')
    plt.show()
    
    

    也可以调用axvspan()的方法为一段时间添加阴影标注,其中alpha参数设置的是阴影的透明度,0代表完全透明,1代表全色。

    ax = df.plot(color='blue', fontsize=6)
    ax.axvspan('2018-01-01', '2019-01-01', color='red', alpha=0.3)
    ax.axhspan(2000, 3000, color='green', alpha=0.7)
    plt.show()
    
    

    03

    移动平均时间序列

    有时候,我们想要观察某个窗口期的移动平均值的变化趋势,可以通过调用窗口函数rolling来实现。下面实例中显示的是,以250天为窗口期的移动平均线close,以及与移动标准差的关系构建的上下两个通道线upper和lower。

    ma = df.rolling(window=250).mean()
    mstd = df.rolling(window=250).std()
    
    ma['upper'] = ma['close'] + (mstd['close'] * 2)
    ma['lower'] = ma['close'] - (mstd['close'] * 2)
    
    ax = ma.plot(linewidth=0.8, fontsize=6)
    ax.set_xlabel('trade_date', fontsize=8)
    ax.set_ylabel('399300.SZ close from 2005-01-04 to 2019-07-04', fontsize=8)
    ax.set_title('Rolling mean and variance of 399300.SZ cloe from 2005-01-04 to 2019-07-04', fontsize=10)
    plt.show()
    
    

    04

    多个时间序列

    如果想要可视化多个时间序列数据,同样可以直接调用plot()方法。示例中我们从tushare.pro上面选取三只股票的日线行情数据进行分析。

    # 获取数据
    code_list = ['000001.SZ', '000002.SZ', '600000.SH']
    data_list = []
    for code in code_list:
        print(code)
        df = pro.daily(ts_code=code, start_date='20180101', end_date='20190101')[['trade_date', 'close']]
        df.sort_values('trade_date', inplace=True)
        df.rename(columns={'close': code}, inplace=True)
        df.set_index('trade_date', inplace=True)
        data_list.append(df)
    df = pd.concat(data_list, axis=1)
    print(df.head())
    
    000001.SZ
    000002.SZ
    600000.SH
                000001.SZ  000002.SZ  600000.SH
    trade_date                                 
    20180102        13.70      32.56      12.72
    20180103        13.33      32.33      12.66
    20180104        13.25      33.12      12.66
    20180105        13.30      34.76      12.69
    20180108        12.96      35.99      12.68
    
    # 画图
    ax = df.plot(linewidth=2, fontsize=12)
    ax.set_xlabel('trade_date')
    ax.legend(fontsize=15)
    plt.show()
    
    

    调用.plot.area()方法可以生成时间序列数据的面积图,显示累计的总数。

    ax = df.plot.area(fontsize=12)
    ax.set_xlabel('trade_date')
    ax.legend(fontsize=15)
    plt.show()
    
    

    如果想要在不同子图中单独显示每一个时间序列,可以通过设置参数subplots=True来实现。layout指定要使用的行列数,sharexsharey用于设置是否共享行和列,**colormap='viridis' **为每条线设置不同的颜色。

    df.plot(subplots=True,
              layout=(2, 2),
              sharex=False,
              sharey=False,
              colormap='viridis',
              fontsize=7,
              legend=False,
              linewidth=0.3)
    
    plt.show()
    
    

    05

    总结

    本文主要介绍了如何利用Python中的matplotlib库对时间序列数据进行一些简单的可视化操作,包括可视化单个时间序列并设置图中的细节,可视化移动平均时间序列和多个时间序列。

    大家在学python的时候肯定会遇到很多难题,以及对于新技术的追求,这里推荐一下我们的Python学习扣qun:784758214,这里是python学习者聚集地!!同时,自己是一名高级python开发工程师,从基础的python脚本到web开发、爬虫、django、数据挖掘等,零基础到项目实战的资料都有整理。送给每一位python的小伙伴!每日分享一些学习的方法和需要注意的小细节

    相关文章

      网友评论

        本文标题:最简洁的Python时间序列可视化:数据科学分析价格趋势,预测价

        本文链接:https://www.haomeiwen.com/subject/lswhkctx.html