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

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

转载于:https://my.oschina.net/u/4161332/blog/3072178

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值