import numpy as np import matplotlib.pyplot as mp import matplotlib.dates as md import mpl_finance as mf dates, opening_prices, highest_prices, lowest_prices, closing_prices = np.loadtxt('../../data/goog.csv', delimiter=',', usecols=(0, 1, 2, 3, 4), unpack=True, dtype='M8[D], f8, f8, f8, f8', skiprows=1) mp.figure('Candlestick', facecolor='lightgray') mp.title('Candlestick', fontsize=20) mp.xlabel('Date', fontsize=14) mp.ylabel('Price', fontsize=14) ax = mp.gca() ax.xaxis.set_major_locator(md.MonthLocator()) ax.xaxis.set_major_formatter(md.DateFormatter('%d %b %Y')) mp.tick_params(labelsize=10) mp.grid(linestyle=':') dates = dates.astype(md.datetime.datetime) dates = mf.date2num(dates) ohlcs = np.column_stack((dates, opening_prices, highest_prices, lowest_prices, closing_prices)) mf.candlestick_ohlc(mp.gca(), ohlcs, 0.8, 'orangered', 'limegreen') mp.gcf().autofmt_xdate() mp.show()
def _do_plot_candle(date, p_open, high, low, close, volume, view_index, symbol, day_sum, save, minute): """ 绘制不可交互的k线图 param date: 融时间序列交易日时间,pd.DataFrame.index对象 :param p_open: 金融时间序列开盘价格序列,np.array对象 :param high: 金融时间序列最高价格序列,np.array对象 :param low: 金融时间序列最低价格序列,np.array对象 :param close: 金融时间序列收盘价格序列,np.array对象 :param volume: 金融时间序列成交量序列,np.array对象 :param symbol: symbol str对象 :param day_sum: 端线图 matplotlib的版本有些有bug显示不对 :param save: 是否保存可视化结果在本地 :param minute: 是否是绘制分钟k线图 """ # 需要内部import不然每次import abupy都有warning,特别是子进程很烦人 try: # noinspection PyUnresolvedReferences, PyDeprecation # import matplotlib.mpl_finance as mpf # 改用其他导入方式 import mpl_finance as mpf except ImportError: # 2.2 才会有 # noinspection PyUnresolvedReferences, PyDeprecation import matplotlib.mpl_finance as mpf if not g_only_draw_price: # 成交量,价格都绘制 # noinspection PyTypeChecker fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(20, 12)) else: # 只绘制价格 fig, ax1 = plt.subplots(figsize=(6, 6)) if day_sum: # 端线图绘制 qutotes = [] for index, (d, o, c, l, h) in enumerate(zip(date, p_open, close, low, high)): d = index if minute else mpf.date2num(d) val = (d, o, c, l, h) qutotes.append(val) # plot_day_summary_oclh接口,与mpf.candlestick_ochl不同,即数据顺序为开收低高 mpf.plot_day_summary_oclh(ax1, qutotes, ticksize=5, colorup=__colorup__, colordown=__colordown__) else: # k线图绘制 qutotes = [] for index, (d, o, c, h, l) in enumerate(zip(date, p_open, close, high, low)): d = index if minute else mdates.date2num(d) val = (d, o, c, h, l) qutotes.append(val) # mpf.candlestick_ochl即数据顺序为开收高低 mpf.candlestick_ochl(ax1, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__) if not g_only_draw_price: # 开始绘制成交量 ax1.set_title(symbol) ax1.set_ylabel('ochl') ax1.grid(True) if not minute: ax1.xaxis_date() if view_index is not None: # 开始绘制买入交易日,卖出交易日,重点突出的点位 e_list = date.tolist() # itertools.cycle循环使用备选的颜色 for v, csColor in zip(view_index, itertools.cycle(K_PLT_MAP_STYLE)): try: v_ind = e_list.index(v) except Exception as e: # logging.exception(e) logging.debug(e) # 向前倒一个 v_ind = len(close) - 1 label = symbol + ': ' + str(date[v_ind]) ax1.plot(v, close[v_ind], 'ro', markersize=12, markeredgewidth=4.5, markerfacecolor='None', markeredgecolor=csColor, label=label) # 因为candlestick_ochl 不能label了,所以使用下面的显示文字 # noinspection PyUnboundLocalVariable ax2.plot(v, 0, 'ro', markersize=12, markeredgewidth=0.5, markerfacecolor='None', markeredgecolor=csColor, label=label) plt.legend(loc='best') # 成交量柱子颜色,收盘价格 > 开盘,即红色 # noinspection PyTypeChecker bar_red = np.where(close >= p_open, volume, 0) # 成交量柱子颜色,开盘价格 > 收盘。即绿色 # noinspection PyTypeChecker bar_green = np.where(p_open > close, volume, 0) date = date if not minute else np.arange(0, len(date)) ax2.bar(date, bar_red, facecolor=__colorup__) ax2.bar(date, bar_green, facecolor=__colordown__) ax2.set_ylabel('volume') ax2.grid(True) ax2.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=30) else: ax1.grid(False) if save: # 保存可视化结果在本地 from pylab import savefig save_dir = os.path.join(K_SAVE_CACHE_PNG_ROOT, ABuDateUtil.current_str_date()) png_dir = os.path.join(save_dir, symbol) ABuFileUtil.ensure_dir(png_dir) r_cnt = 0 while True: png_name = '{}{}.png'.format( png_dir, '' if r_cnt == 0 else '-{}'.format(r_cnt)) if not ABuFileUtil.file_exist(png_name): break r_cnt += 1 # noinspection PyUnboundLocalVariable savefig(png_name) fig.clf() plt.close(fig) else: """ save 了就不show了 """ plt.show()