自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

簡(jiǎn)潔的Python時(shí)間序列可視化實(shí)現(xiàn)

開發(fā) 后端
本文會(huì)利用Python中的matplotlib【1】庫,并配合實(shí)例進(jìn)行講解。matplotlib庫是一個(gè)用于創(chuàng)建出版質(zhì)量圖表的桌面繪圖包(2D繪圖庫),是Python中最基本的可視化工具。

[[272839]]

時(shí)間序列數(shù)據(jù)在數(shù)據(jù)科學(xué)領(lǐng)域無處不在,在量化金融領(lǐng)域也十分常見,可以用于分析價(jià)格趨勢(shì),預(yù)測(cè)價(jià)格,探索價(jià)格行為等。

學(xué)會(huì)對(duì)時(shí)間序列數(shù)據(jù)進(jìn)行可視化,能夠幫助我們更加直觀地探索時(shí)間序列數(shù)據(jù),尋找其潛在的規(guī)律。

本文會(huì)利用Python中的matplotlib【1】庫,并配合實(shí)例進(jìn)行講解。matplotlib庫是一個(gè)用于創(chuàng)建出版質(zhì)量圖表的桌面繪圖包(2D繪圖庫),是Python中最基本的可視化工具。

【工具】Python 3

【數(shù)據(jù)】Tushare

【注】示例注重的是方法的講解,請(qǐng)大家靈活掌握。

1.單個(gè)時(shí)間序列

首先,我們從tushare.pro獲取指數(shù)日線行情數(shù)據(jù),并查看數(shù)據(jù)類型。 

  1. import tushare as ts  
  2. import pandas as pd  
  3. pd.set_option('expand_frame_repr', False)  # 顯示所有列  
  4. ts.set_token('your token')  
  5. pro = ts.pro_api()  
  6. df = pro.index_daily(ts_code='399300.SZ')[['trade_date', 'close']]  
  7. df.sort_values('trade_date', inplace=True)   
  8. df.reset_index(inplace=Truedrop=True 
  9. print(df.head())  
  10.   trade_date    close  
  11. 0   20050104  982.794  
  12. 1   20050105  992.564  
  13. 2   20050106  983.174  
  14. 3   20050107  983.958  
  15. 4   20050110  993.879  
  16. print(df.dtypes)  
  17. trade_date     object  
  18. close         float64  
  19. dtype: object 

交易時(shí)間列'trade_date' 不是時(shí)間類型,而且也不是索引,需要先進(jìn)行轉(zhuǎn)化。 

  1. df['trade_date'] = pd.to_datetime(df['trade_date'])  
  2. df.set_index('trade_date', inplace=True 
  3. print(df.head())  
  4.               close  
  5. trade_date           
  6. 2005-01-04  982.794  
  7. 2005-01-05  992.564  
  8. 2005-01-06  983.174  
  9. 2005-01-07  983.958  
  10. 2005-01-10  993.879 

接下來,就可以開始畫圖了,我們需要導(dǎo)入matplotlib.pyplot【2】,然后通過設(shè)置set_xlabel()和set_xlabel()為x軸和y軸添加標(biāo)簽。 

  1. import matplotlib.pyplot as plt  
  2. ax = df.plot(color='' 
  3. ax.set_xlabel('trade_date')  
  4. ax.set_ylabel('399300.SZ close')  
  5. plt.show() 

matplotlib庫中有很多內(nèi)置圖表樣式可以選擇,通過打印plt.style.available查看具體都有哪些選項(xiàng),應(yīng)用的時(shí)候直接調(diào)用plt.style.use('fivethirtyeight')即可。 

  1. print(plt.style.available)  
  2. ['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'] 
  3.  plt.style.use('fivethirtyeight')  
  4. ax1 = df.plot()  
  5. ax1.set_title('FiveThirtyEight Style')  
  6. plt.show() 

2.設(shè)置更多細(xì)節(jié)

上面畫出的是一個(gè)很簡(jiǎn)單的折線圖,其實(shí)可以在plot()里面通過設(shè)置不同參數(shù)的值,為圖添加更多細(xì)節(jié),使其更美觀、清晰。

figsize(width, height)設(shè)置圖的大小,linewidth設(shè)置線的寬度,fontsize設(shè)置字體大小。然后,調(diào)用set_title()方法設(shè)置標(biāo)題。 

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

如果想要看某一個(gè)子時(shí)間段內(nèi)的折線變化情況,可以直接截取該時(shí)間段再作圖即可,如df['2018-01-01': '2019-01-01'] 

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

如果想要突出圖中的某一日期或者觀察值,可以調(diào)用.axvline()和.axhline()方法添加垂直和水平參考線。 

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

也可以調(diào)用axvspan()的方法為一段時(shí)間添加陰影標(biāo)注,其中alpha參數(shù)設(shè)置的是陰影的透明度,0代表完全透明,1代表全色。 

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

3.移動(dòng)平均時(shí)間序列

有時(shí)候,我們想要觀察某個(gè)窗口期的移動(dòng)平均值的變化趨勢(shì),可以通過調(diào)用窗口函數(shù)rolling來實(shí)現(xiàn)。下面實(shí)例中顯示的是,以250天為窗口期的移動(dòng)平均線close,以及與移動(dòng)標(biāo)準(zhǔn)差的關(guān)系構(gòu)建的上下兩個(gè)通道線upper和lower。 

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

4.多個(gè)時(shí)間序列

如果想要可視化多個(gè)時(shí)間序列數(shù)據(jù),同樣可以直接調(diào)用plot()方法。示例中我們從tushare.pro上面選取三只股票的日線行情數(shù)據(jù)進(jìn)行分析。 

  1. # 獲取數(shù)據(jù)  
  2. code_list = ['000001.SZ', '000002.SZ', '600000.SH']  
  3. data_list = []  
  4. for code in code_list:  
  5.     print(code)  
  6.     df = pro.daily(ts_code=code, start_date='20180101'end_date='20190101')[['trade_date', 'close']]  
  7.     df.sort_values('trade_date', inplace=True 
  8.     df.rename(columns={'close': code}, inplace=True 
  9.     df.set_index('trade_date', inplace=True 
  10.     data_list.append(df)  
  11. df = pd.concat(data_list, axis=1 
  12. print(df.head())  
  13. 000001.SZ  
  14. 000002.SZ  
  15. 600000.SH  
  16.             000001.SZ  000002.SZ  600000.SH  
  17. trade_date                                   
  18. 20180102        13.70      32.56      12.72  
  19. 20180103        13.33      32.33      12.66  
  20. 20180104        13.25      33.12      12.66  
  21. 20180105        13.30      34.76      12.69  
  22. 20180108        12.96      35.99      12.68  
  23. # 畫圖  
  24. ax = df.plot(linewidth=2fontsize=12 
  25. ax.set_xlabel('trade_date')  
  26. ax.legend(fontsize=15 
  27. plt.show() 

調(diào)用.plot.area()方法可以生成時(shí)間序列數(shù)據(jù)的面積圖,顯示累計(jì)的總數(shù)。 

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

如果想要在不同子圖中單獨(dú)顯示每一個(gè)時(shí)間序列,可以通過設(shè)置參數(shù)subplots=True來實(shí)現(xiàn)。layout指定要使用的行列數(shù),sharex和sharey用于設(shè)置是否共享行和列,colormap='viridis' 為每條線設(shè)置不同的顏色。 

  1. df.plot(subplots=True 
  2.           layout=(2, 2),  
  3.           sharex=False 
  4.           sharey=False 
  5.           colormap='viridis' 
  6.           fontsize=7 
  7.           legend=False 
  8.           linewidth=0.3)  
  9. plt.show() 

5.總結(jié)

本文主要介紹了如何利用Python中的matplotlib庫對(duì)時(shí)間序列數(shù)據(jù)進(jìn)行一些簡(jiǎn)單的可視化操作,包括可視化單個(gè)時(shí)間序列并設(shè)置圖中的細(xì)節(jié),可視化移動(dòng)平均時(shí)間序列和多個(gè)時(shí)間序列。

責(zé)任編輯:龐桂玉 來源: 菜鳥學(xué)Python
相關(guān)推薦

2017-10-14 13:54:26

數(shù)據(jù)可視化數(shù)據(jù)信息可視化

2022-08-26 09:15:58

Python可視化plotly

2020-03-11 14:39:26

數(shù)據(jù)可視化地圖可視化地理信息

2014-12-31 16:48:43

Touch touchevent多點(diǎn)觸摸

2022-09-29 11:16:21

Python數(shù)據(jù)可視化

2018-04-03 14:42:46

Python神經(jīng)網(wǎng)絡(luò)深度學(xué)習(xí)

2014-05-28 15:23:55

Rave

2021-09-27 08:31:01

數(shù)據(jù)可視化柱狀圖折現(xiàn)圖

2017-10-31 09:38:53

大數(shù)據(jù)數(shù)據(jù)可視化Python

2023-09-19 15:44:03

Python數(shù)據(jù)可視化

2015-09-16 09:19:57

2018-08-10 14:45:52

Python網(wǎng)絡(luò)爬蟲mongodb

2009-04-21 14:26:41

可視化監(jiān)控IT管理摩卡

2021-02-01 22:01:57

Coco工具macOS

2021-02-21 08:11:46

PythonDash工具

2022-02-23 09:50:52

PythonEchartspyecharts

2020-05-26 11:34:46

可視化WordCloud

2017-06-29 11:26:08

Python數(shù)據(jù)可視化

2020-09-02 13:56:03

Python可視化數(shù)據(jù)

2020-03-04 14:15:29

Python數(shù)據(jù)可視化代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)