matplotlib提供了一些金融图表主要用于可视化历史股票价格,或者类似的金融时间序列数据
在matplotlib.finance的子库中也提供了获取历史数据的函数
版本matplotlib 2.2中,finance会被替换成mpl_finance,但是在2.0版本中
import matplotlib.finance as mpf仍可以使用
data = mpf.quotes_historical_yahoo('code',start, end)
但是web数据来源的数据不足以作为任何重要投资的决策基础,本文中的数据通过tushare获取
import matplotlib as mpl
import tushare as ts
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
%matplotlib inline
wdyx = ts.get_k_data('002739','2017-01-01')
wdyx.info()
wdyx[:3]
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }
|
date |
open |
close |
high |
low |
volume |
code |
0 |
2017-01-03 |
54.010 |
54.070 |
54.110 |
53.711 |
30518.0 |
002739 |
1 |
2017-01-04 |
54.090 |
56.691 |
56.771 |
53.831 |
103953.0 |
002739 |
2 |
2017-01-05 |
56.302 |
56.591 |
57.080 |
55.924 |
65414.0 |
002739 |
from matplotlib.pylab import date2num
import datetime
'''
data_list = []
for dates,row in hist_data.iterrows():
# 将时间转换为数字
date_time = datetime.datetime.strptime(dates,'%Y-%m-%d')
t = date2num(date_time)
open,high,low,close = row[:4]
datas = (t,open,high,low,close)
data_list.append(datas)
'''
def date_to_num(dates):
num_time = []
for date in dates:
date_time = datetime.datetime.strptime(date,'%Y-%m-%d')
num_date = date2num(date_time)
num_time.append(num_date)
return num_time
mat_wdyx = wdyx.as_matrix()
num_time = date_to_num(mat_wdyx[:,0])
mat_wdyx[:,0] = num_time
mat_wdyx[:3]
array([[736332.0, 54.01, 54.07, 54.11, 53.711, 30518.0, '002739'],
[736333.0, 54.09, 56.691, 56.771, 53.831, 103953.0, '002739'],
[736334.0, 56.302, 56.591, 57.08, 55.924, 65414.0, '002739']], dtype=object)
fig, ax = plt.subplots(figsize=(15,5))
fig.subplots_adjust(bottom=0.5)
mpf.candlestick_ochl(ax, mat_wdyx, width=0.6, colorup='g', colordown='r', alpha=1.0)
plt.grid(True)
plt.xticks(rotation=30)
plt.title('wanda yuanxian 17')
plt.xlabel('Date')
plt.ylabel('Price')
ax.xaxis_date ()
金融数据每日摘要图表
开盘价格和收盘价格由两条水平线表示
fig, ax = plt.subplots(figsize=(15,5))
mpf.plot_day_summary_oclh(ax, mat_wdyx,colorup='g', colordown='r')
plt.grid(True)
ax.xaxis_date()
plt.title('wandayuanxian 17')
plt.ylabel('Price')
k线图和成交量(柱状图)的组合图表
fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15,8))
mpf.candlestick_ochl(ax1, mat_wdyx, width=1.0, colorup = 'g', colordown = 'r')
ax1.set_title('wandayuanxian')
ax1.set_ylabel('Price')
ax1.grid(True)
ax1.xaxis_date()
plt.bar(mat_wdyx[:,0]-0.25, mat_wdyx[:,5], width= 0.5)
ax2.set_ylabel('Volume')
ax2.grid(True)