pandas處理finance.yahoo股票數據 WTI CL USO OIL

1.參考

用Python作科學計算-基礎篇 »matplotlib-繪製精美的圖表 »快速繪圖 使用pyplot模塊繪圖

2.數據來源

CLhtml

USOpython

OILspa

3.代碼

 1 #encoding='utf-8'
 2 import pandas  as pd
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 
 6 import matplotlib
 7 import sys
 8 import time
 9 
10 print('{:<10}: {}'.format('python',sys.version))
11 print('{:<10}: {}'.format('pandas',pd.__version__))
12 print('{:<10}: {}'.format('numpy',np.__version__))
13 print('{:<10}: {}'.format('matplotlib',matplotlib.__version__))
14 # python    : 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
15 # pandas    : 0.20.2
16 # numpy     : 1.13.0
17 # matplotlib: 2.0.2
18 
19 df_cl = pd.read_csv('CL.csv',na_values=['-'],index_col='日期',parse_dates=['日期'],encoding='gbk')
20 df_uso = pd.read_csv('USO.csv',na_values=['null'],index_col='Date',parse_dates=['Date'])
21 df_oil = pd.read_csv('OIL.csv',na_values=['null'],index_col='Date',parse_dates=['Date'])
22 
23 # 傳入由Series組成的字典
24 df_merge = pd.DataFrame({'CL':df_cl['最新股價'],'USO':df_uso['Adj Close'],'OIL':df_oil['Adj Close']},columns=['CL','USO','OIL'])
25 # 對不一樣的列填充不一樣的值
26 # df_merge_fillna = df_merge.fillna({'CL':df_cl['最新股價'][0],'USO':df_uso['Adj Close'][0],'OIL':df_oil['Adj Close'][0]})
27 df_merge_deal_na = df_merge.dropna()
28 
29 
30 # plt.figure(1)
31 ax1 = plt.subplot(211) 
32 ax2 = plt.subplot(212)    
33 # plt.sca(ax1)
34 # plt.plot(df_uso['Adj Close'])只支持index 0 1 2
35 # ax1.set_ylim([0,150])
36 df_cl['最新股價'].plot(ax=ax1,yticks=range(0,150,10),grid=True)
37 df_merge_deal_na.plot(ax=ax2)
38 plt.show()
39 # 須要手動關閉做圖窗口才能繼續,若是ctrl+c會致使做圖窗口無響應
40 # plt.clf()
41 # 若是關閉了圖表窗口,則沒法使用savefig()保存圖像。
42 # http://hyry.dip.jp/tech/book/page/scipy/matplotlib_fast_plot.html
43 ax1 = plt.subplot(211) 
44 ax2 = plt.subplot(212)    
45 df_cl['最新股價'].plot(ax=ax1,yticks=range(0,150,10),grid=True)
46 df_merge_deal_na.plot(ax=ax2)
47 plt.savefig('result_{}.png'.format(time.strftime('%m%d_%H%M')), dpi=200)

 

4.結果

相關文章
相關標籤/搜索