日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python實(shí)現(xiàn)時(shí)間序列可視化的方法

系統(tǒng) 1959 0

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第1張圖片

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

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

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

【工具】Python 3

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

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

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

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

            
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 
          

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

            
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 
          

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

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

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第2張圖片

matplotlib庫(kù)中有很多內(nèi)置圖表樣式可以選擇,通過(guò)打印 plt.style.available 查看具體都有哪些選項(xiàng),應(yīng)用的時(shí)候直接調(diào)用 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()
          

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第3張圖片

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

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

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

            
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()
          

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第4張圖片

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

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


plt.show()

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第5張圖片

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

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

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第6張圖片

也可以調(diào)用axvspan()的方法為一段時(shí)間添加陰影標(biāo)注,其中alpha參數(shù)設(shè)置的是陰影的透明度,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()
          

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第7張圖片

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

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

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第8張圖片

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

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

            
# 獲取數(shù)據(jù) 
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 
# 畫(huà)圖 
ax = df.plot(linewidth=2, fontsize=12) 
ax.set_xlabel('trade_date') 
ax.legend(fontsize=15) 
plt.show()


          

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第9張圖片

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

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

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第10張圖片

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

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

Python實(shí)現(xiàn)時(shí)間序列可視化的方法_第11張圖片

5.總結(jié)

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

以上所述是小編給大家介紹的Python實(shí)現(xiàn)時(shí)間序列可視化的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 安多县| 亚东县| 灌云县| 澄江县| 舟山市| 荥阳市| 岳阳市| 丰都县| 乌苏市| 黎川县| 二连浩特市| 囊谦县| 廊坊市| 锡林郭勒盟| 鄢陵县| 铜梁县| 始兴县| 临湘市| 吴桥县| 襄汾县| 突泉县| 宜丰县| 邵阳市| 潜江市| 嘉黎县| 永川市| 武功县| 郓城县| 皋兰县| 忻州市| 泌阳县| 楚雄市| 黔西| 南安市| 鹰潭市| 黄平县| 卓资县| 辉县市| 盈江县| 呈贡县| 荣昌县|