def draw_k_easy(self): fig, ax = plt.subplots(figsize=(15, 5)) mpf.plot_day_summary_oclh(ax, self.mat_data, colorup='r', colordown='k') plt.grid(True) ax.xaxis_date() plt.title(self.name + ':' + self.code) plt.ylabel('Price') plt.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.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 mpf.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()
# date1 = (2013, 10, 20) date2 = (2013, 11, 10) ticker = 'IBM' mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = getData(ticker, date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) ax.xaxis.set_minor_formatter(dayFormatter) plot_day_summary_oclh(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=80, horizontalalignment='right') plt.figtext(0.35, 0.45, '10/29: Open, High, Low, Close') plt.figtext(0.35, 0.42, ' 177.62, 182.32, 177.50, 182.12') plt.figtext(0.35, 0.32, 'Black ==> Close > Open ') plt.figtext(0.35, 0.28, 'Red ==> Close < Open ') plt.title('Candlesticks for IBM from 10/20/2013 to 11/10/2013') plt.ylabel('Price') plt.xlabel('Date') plt.show()
plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() #------------------------------------------------ import matplotlib.finance as mpf import matplotlib.pyplot as plt start = (2014, 5, 1) end = (2014, 6, 30) quotes = mpf.quotes_historical_yahoo_ochl('^GDAXI', start, end) fig, ax = plt.subplots(figsize=(8, 5)) fig.subplots_adjust(bottom=0.2) mpf.plot_day_summary_oclh(ax, quotes, colorup='b', colordown='r') plt.grid(True) ax.xaxis_date() # dates on the x-axis plt.title('DAX Index') plt.ylabel('index level') plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() #------------------------------------------------
d = loaddict("./", "pickle") data_list = [] for block in d: dt = datetime.datetime.utcfromtimestamp( block['id']) + datetime.timedelta(hours=8) # mpf库中要求的顺序是:时间、开盘价、最高价、最低价、收盘价 data_list.append((date2num(dt), block['open'], block['high'], block['low'], block['close'])) fig, ax = plt.subplots() ax.xaxis_date() ax.set_title('BTC/USDT') mpf.candlestick_ohlc(ax, data_list, colorup='green', colordown='r', width=0.005) plt.grid() plt.show() ''' fig, ax = plt.subplots(figsize=(15,5)) mpf.plot_day_summary_oclh(ax, data_list,colorup='g', colordown='r') plt.grid(True) ax.xaxis_date() plt.title('wandayuanxian 17') plt.ylabel('Price') plt.grid() plt.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.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 mpf.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()
plt.xlabel('Date') plt.ylabel('Price') # x轴的刻度为日期 ax.xaxis_date () ###candlestick_ochl()函数的参数 # ax 绘图Axes的实例 # mat_wdyx 价格历史数据 # width 图像中红绿矩形的宽度,代表天数 # colorup 收盘价格大于开盘价格时的颜色 # colordown 低于开盘价格时矩形的颜色 # alpha 矩形的颜色的透明度 ######################一下为绘制美国图############# 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)
#Data comes out as Open, High,Low,Close,and Volume quotes[:2] #Create candlestick plots fig,ax=plt.subplots(figsize=(7,5)) fig.subplots_adjust(bottom=0.2) mpf.candlestick_ochl(ax,quotes,width=0.6,colorup='b',colordown='r') plt.grid(True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(),rotation=30) #Create daily summary plots fig,ax=plt.subplots(figsize=(7,5)) fig.subplots_adjust(bottom=0.2) mpf.plot_day_summary_oclh(ax,quotes,colorup='b',colordown='r') plt.grid(True) ax.xaxis_date() plt.title('DAX Index') plt.ylabel('index level') plt.setp(plt.gca().get_xticklabels(),rotation=30) #Plotting candlestick and barcharts quotes=np.array(mpf.quotes_historical_yahoo_ochl('YHOO',start,end)) fig,(ax1,ax2)=plt.subplots(2,sharex=True,figsize=(8,6)) mpf.candlestick_ochl(ax1,quotes,width=0.6,colorup='b',colordown='r') ax1.set_title('Yahoo Inc.') ax1.grid(True) ax1.xaxis_date() plt.bar(quotes[:,0]-0.25,quotes[:,5],width=0.5) ax2.set_ylabel('volume')