如何根据k线数据绘制k线图

原创
2019/07/10 14:47
阅读数 179
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import mpl_finance as mpf
from matplotlib.ticker import Formatter
import numpy as np
from zb import ZB

# 根据api接口获取K线数据
zb = ZB()
dfcvs = zb.fetch_ohlcv()

dfcvs.columns = ['candle_begin_time', 'open', 'high', 'low', 'close', 'volume']
dfcvs['candle_begin_time'] = pd.to_datetime(dfcvs['candle_begin_time'], format="%Y/%m/%d-%H:%M")

dfcvs['candle_begin_time'] = dfcvs['candle_begin_time'].apply(lambda x: dates.date2num(x) * 1440)
data_mat = dfcvs.as_matrix()

fig, ax = plt.subplots(figsize=(1200 / 72, 680 / 72))

fig.subplots_adjust(bottom=0.2)
mpf.candlestick_ohlc(ax, data_mat, colordown='#53c156', colorup='#ff1717', width=2.4, alpha=1)


# 将x轴的浮点数格式化成日期小时分钟
# 默认的x轴格式化是日期被dates.date2num之后的浮点数,因为在上面乘以了1440,所以默认是错误的
# 只能自己将浮点数格式化为日期时间分钟
# 参考https://matplotlib.org/examples/pylab_examples/date_index_formatter.html
class MyFormatter(Formatter):
   def __init__(self, dates, fmt='%Y%m%d %H:%M'):
       self.dates = dates
       self.fmt = fmt

   def __call__(self, x, pos=0):
       'Return the label for time x at position pos'
       ind = int(np.round(x))
       # ind就是x轴的刻度数值,不是日期的下标

       return dates.num2date(ind / 1440).strftime(self.fmt)


formatter = MyFormatter(data_mat[:, 0])
ax.xaxis.set_major_formatter(formatter)

for label in ax.get_xticklabels():
   # 标签旋转的角度
   label.set_rotation(20)
   label.set_horizontalalignment('right')

plt.show()
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部