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()
如何根据k线数据绘制k线图
猜你喜欢
转载自blog.csdn.net/weixin_43958804/article/details/88745910
今日推荐
周排行