def generateGraph(self, opens, closes, highs, lows): self.clearGraphData() # print "DEBUG:" # print "highs = %s" % highs # print "lows = %s" % lows # print "opens = %s" % opens # print "closes = %s" % closes # print "len(highs): %s == len(lows): %s" %(len(highs), len(lows)) # print "len(opens): %s == len(closes): %s" %(len(opens), len(closes)) # # for i in range(len(highs)): # print "DEBUG: (%s, %s, %s, %s)" %(lows[i], opens[i], closes[i], highs[i]) # print "DEBUG: diffs h/l: %s o/c: %s" %(lows[i] - highs[i], opens[i] - closes[i]) self.ax = self.fig.add_subplot(111) self.ax.set_title(_("Session candlestick graph")) #Set axis labels and grid overlay properites self.ax.set_xlabel(_("Sessions"), fontsize = 12) self.ax.set_ylabel("$", fontsize = 12) self.ax.grid(color='g', linestyle=':', linewidth=0.2) candlestick2(self.ax, opens, closes, highs, lows, width=0.50, colordown='r', colorup='g', alpha=1.00) self.graphBox.add(self.canvas) self.canvas.show() self.canvas.draw()
def plot_candlestick(df_show, save_file, show_option=False): show_days = df_show.shape[0] plt.close('all') f, axarr = plt.subplots(3, sharex=True) axarr[0].plot(range(show_days), df_show[['MA_20', 'MA_50']]) candlestick2(axarr[0], df_show.Open, df_show.Close, df_show.High, df_show.Low, width=1, colorup='g', colordown='r', alpha=0.75) axarr[1].plot( range(show_days), df_show[['Close', 'MA_20', 'BollingerUpper20', 'BollingerLower20']]) candlestick2(axarr[1], df_show.Open, df_show.Close, df_show.High, df_show.Low, width=1, colorup='g', colordown='r', alpha=0.75) axarr[2].plot(range(show_days), df_show[['Volume']]) axarr[2].set_title("Volume", fontsize=8) plt.xlim(0, show_days) f.set_size_inches(12, 8) f.savefig(save_file) if show_option: plt.show()
def test_dchannel(ohlc): """DCHANNEL test function.""" dchannel10 = dchannel(ohlc, 10) data = pd.concat([ohlc, dchannel10], axis=1) # print(data) ax1 = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=6) ax1.grid(True) candlestick2(ax1, ohlc["opens"], ohlc["closes"], ohlc["highs"], ohlc["lows"], width=0.7, colorup="r", colordown="g") ax1.plot(dchannel10) plt.title("DCHANNEL Chart") plt.show()
def on_StockView_Plot(self): self.top_axes = self.figure.add_subplot(2, 1, 1) # self.top_axes.subplot2grid((4,4), (0,0), rowspan = 3, colspan = 4) self.top_axes.plot(self.data.index, self.data["High"], 'y', self.data.index, self.data["Close"], 'r', self.data.index, self.data["Open"], 'g', self.data.index, self.data["Low"], 'b') # self.top_axes.set_ylabel('Price', color='r') self.bottom_axes = self.top_axes.twinx() # self.bottom_axes = self.figure.add_subplot(2,1,1) # self.bottom_axes.subplot2grid((4,4), (3,0), rowspan = 1, colspan = 4) self.bottom_axes.bar(self.data.index, self.data["Volume"], alpha=0.05, color='k', label='Volume') self.bottom_axes.get_yaxis().set_visible(False) self.x_axes = self.top_axes.get_xaxis() # get the x-axis self.autoformat = self.x_axes.get_major_formatter( ) # the the auto-formatter self.autoformat.scaled[1. / 24] = '%H:%M' # set the < 1d scale to H:M self.autoformat.scaled[ 1.0] = '%m-%d' # set the > 1d < 1m scale to Y-m-d self.autoformat.scaled[30.] = '%Y-%m' # set the > 1m < 1Y scale to Y-m self.autoformat.scaled[365.] = '%Y' # set the > 1y scale to Y self.top_axes.grid(True) self.top_axes.get_xaxis().set_visible(False) self.candle_axes = self.figure.add_subplot(2, 1, 2) self.candle_axes.get_xaxis().set_visible(False) candlestick2(self.candle_axes, self.data["Open"], self.data["Close"], self.data["High"], self.data["Low"], width=0.6, colorup='g', colordown='r') plot_day_summary2(self.candle_axes, self.data["Open"], self.data["Close"], self.data["High"], self.data["Low"]) self.candle_axes.locator_params(tight=True) self.canvas.draw()
def showDfSimple(self, df): import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.finance as mpf stock_middle_num = self.middle_num(df) fig, ax = plt.subplots(figsize = (50,20)) fig.subplots_adjust(bottom=0.2) mpf.candlestick2(ax, list(df.open),list(df.close),list(df.high),list(df.low), width=0.6, colorup='r', colordown='b',alpha=0.75 ) plt.grid(True) dates = df.index ax.set_xticklabels(dates) # Label x-axis with dates # ax.autoscale_view() plt.plot(stock_middle_num,'k', lw=1) plt.plot(stock_middle_num,'ko') plt.setp(plt.gca().get_xticklabels(), rotation=30)
def on_StockView_Plot(self): self.top_axes = self.figure.add_subplot(2,1,1) # self.top_axes.subplot2grid((4,4), (0,0), rowspan = 3, colspan = 4) self.top_axes.plot( self.data.index, self.data["High"],'y', self.data.index, self.data["Close"],'r', self.data.index, self.data["Open"],'g', self.data.index, self.data["Low"],'b' ) # self.top_axes.set_ylabel('Price', color='r') self.bottom_axes = self.top_axes.twinx() # self.bottom_axes = self.figure.add_subplot(2,1,1) # self.bottom_axes.subplot2grid((4,4), (3,0), rowspan = 1, colspan = 4) self.bottom_axes.bar(self.data.index, self.data["Volume"], alpha=0.05, color='k', label='Volume') self.bottom_axes.get_yaxis().set_visible(False) self.x_axes = self.top_axes.get_xaxis() # get the x-axis self.autoformat = self.x_axes.get_major_formatter() # the the auto-formatter self.autoformat.scaled[1./24] = '%H:%M' # set the < 1d scale to H:M self.autoformat.scaled[1.0] = '%m-%d' # set the > 1d < 1m scale to Y-m-d self.autoformat.scaled[30.] = '%Y-%m' # set the > 1m < 1Y scale to Y-m self.autoformat.scaled[365.] = '%Y' # set the > 1y scale to Y self.top_axes.grid(True) self.top_axes.get_xaxis().set_visible(False) self.candle_axes = self.figure.add_subplot(2,1,2) self.candle_axes.get_xaxis().set_visible(False) candlestick2(self.candle_axes, self.data["Open"],self.data["Close"], self.data["High"], self.data["Low"], width=0.6, colorup='g', colordown='r') plot_day_summary2(self.candle_axes, self.data["Open"],self.data["Close"], self.data["High"], self.data["Low"]) self.candle_axes.locator_params(tight=True) self.canvas.draw()
def plot_candlestick(day_list): opens = [] highs = [] lows = [] closes = [] average_list =[] for day in reversed(day_list): opens.append(day.open) highs.append(day.high) lows.append(day.low) closes.append(day.close) average_list.append(day.average) pass fig, ax = plt.subplots() plt.plot(average_list) candlestick2(ax,opens,closes,highs,lows,0.6) plt.show() pass
def plot_candlestick(day_list): opens = [] highs = [] lows = [] closes = [] average_list = [] for day in reversed(day_list): opens.append(day.open) highs.append(day.high) lows.append(day.low) closes.append(day.close) average_list.append(day.average) pass fig, ax = plt.subplots() plt.plot(average_list) candlestick2(ax, opens, closes, highs, lows, 0.6) plt.show() pass
def candlestick(candles, price_type='ask'): price_type = price_type.title() quotes = {'open': [], 'high': [], 'low': [], 'close': []} for candle in candles: quotes['open'].append(candle['openAsk']) quotes['high'].append(candle['highAsk']) quotes['low'].append(candle['lowAsk']) quotes['close'].append(candle['closeAsk']) fig, ax = plt.subplots() candlestick2(ax, quotes['open'], quotes['close'], quotes['high'], quotes['low'], width=0.5) plt.show()
def plot_k_series(k_data): # 画k线 num_of_ticks = len(k_data) fig, ax = plt.subplots(figsize=(num_of_ticks, 20)) fig.subplots_adjust(bottom=0.2) dates = k_data.index # print dates ax.set_xticks(np.linspace(1, num_of_ticks, num_of_ticks)) ax.set_xticklabels(list(dates)) mpf.candlestick2(ax, list(k_data.open), list(k_data.close), list(k_data.high), list(k_data.low), width=0.6, colorup='r', colordown='b', alpha=0.75) plt.grid(True) plt.setp(plt.gca().get_xticklabels(), rotation=30) return ax
def generateGraph(self, opens, closes, highs, lows): self.clearGraphData() # print "DEBUG:" # print "highs = %s" % highs # print "lows = %s" % lows # print "opens = %s" % opens # print "closes = %s" % closes # print "len(highs): %s == len(lows): %s" %(len(highs), len(lows)) # print "len(opens): %s == len(closes): %s" %(len(opens), len(closes)) # # for i in range(len(highs)): # print "DEBUG: (%s, %s, %s, %s)" %(lows[i], opens[i], closes[i], highs[i]) # print "DEBUG: diffs h/l: %s o/c: %s" %(lows[i] - highs[i], opens[i] - closes[i]) self.ax = self.fig.add_subplot(111) self.ax.set_title(_("Session candlestick graph")) #Set axis labels and grid overlay properites self.ax.set_xlabel(_("Sessions"), fontsize=12) self.ax.set_ylabel("$", fontsize=12) self.ax.grid(color='g', linestyle=':', linewidth=0.2) candlestick2(self.ax, opens, closes, highs, lows, width=0.50, colordown='r', colorup='g', alpha=1.00) self.graphBox.add(self.canvas) self.canvas.show() self.canvas.draw()
t.set_x(0) # align the title left, axes coords t.set_horizontalalignment('left') # align the title left, axes coords axUpper.yaxis.set_major_locator(MultipleLocator(5)) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# #plot_day_summary2(axMiddle, opens, closes, highs, lows) candlestick2(axMiddle, opens, closes, highs, lows) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, '%s daily' % ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top - height, 'MA(5)', color='b', fontsize=textsize,
'Return the label for time x at position pos' ind = int(round(x)) if ind>=len(self.dates) or ind<0: return '' return self.dates[ind].strftime(self.fmt) formatter= MyFormatter(data.vDate[daysToPlot:]) [per_k, per_d] = stochastic_oscillator.stoc_osc(data.vHigh, data.vLow, data.vClose,15,5,5,"ema") plt.figure(1) ax1 = plt.subplot('411') candlestick2(ax1, data.vOpen[daysToPlot:],data.vClose[daysToPlot:],data.vHigh[daysToPlot:],data.vLow[daysToPlot:], width=0.6) [macdOut, ema, divergence] = macd.macd(data.vClose, 12,26, 9) ax2 = plt.subplot('412') ax2.plot(macdOut[daysToPlot:]) ax2.plot( ema[daysToPlot:]) ax2.stem(arange(-1*daysToPlot), divergence[daysToPlot:]) # MACD [macdOut, ema, divergence] = macd.macd(data.vClose, 5,10, 4) ax2 = plt.subplot('413') ax2.plot(macdOut[daysToPlot:]) ax2.plot( ema[daysToPlot:]) ax2.stem(arange(-1*daysToPlot), divergence[daysToPlot:]) # Stochastic Oscillator. ax3 = plt.subplot('414') ax3.plot(per_k[daysToPlot:], color="red") ax3.plot(per_d[daysToPlot:], color='darkviolet')
opens = opens[::-1] close = close[::-1] high = high[::-1] low = low[::-1] #绘图组件的顶层容器 fig = plt.figure() #增加一个子图 ax = fig.add_subplot(111) #将x轴上的主定位器设置为 月和日 定位器 ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) #绘制K线图 candlestick2(ax, opens, close, high, low, width=1, colorup='r', colordown='g', alpha=1) #candlestick2(ax, opens,close,high,low) #将x轴上的标签格式化日期 fig.autofmt_xdate() plt.show()
if after_fenxing.open[i] > after_fenxing.close[i]: after_fenxing.open[i] = after_fenxing.high[i] after_fenxing.close[i] = after_fenxing.low[i] else: after_fenxing.open[i] = after_fenxing.low[i] after_fenxing.close[i] = after_fenxing.high[i] ## 画出k线图 stock_middle_num = middle_num(after_fenxing) fig, ax = plt.subplots(figsize=(50, 20)) fig.subplots_adjust(bottom=0.2) mpf.candlestick2(ax, list(after_fenxing.open), list(after_fenxing.close), list(after_fenxing.high), list(after_fenxing.low), width=0.6, colorup='r', colordown='b', alpha=0.75) plt.grid(True) dates = after_fenxing.index ax.set_xticklabels(dates) # Label x-axis with dates # ax.autoscale_view() plt.plot(stock_middle_num, 'k', lw=1) plt.plot(stock_middle_num, 'ko') plt.setp(plt.gca().get_xticklabels(), rotation=30) ## 找出顶和底 temp_num = 0 # 上一个顶或底的位置 temp_high = 0 # 上一个顶的high值
t.set_y(1.05) # move it up a bit higher than the default t.set_x(0) # align the title left, axes coords t.set_horizontalalignment('left') # align the title left, axes coords axUpper.yaxis.set_major_locator(MultipleLocator(5)) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# candlestick2(axMiddle, r.open, r.close, r.high, r.low, width=0.9) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, '%s daily' % ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top - height, 'MA(5)', color='b', fontsize=textsize,
@author: chew-z """ import matplotlib.pyplot as plt import numpy as np from matplotlib.finance import candlestick2 # 1 read OHLC g = globals() # read global variables d_mat = g['d_mat'] returns = g['returns'] openD1 = d_mat[:, 0] highD1 = d_mat[:, 1] lowD1 = d_mat[:, 2] closeD1 = d_mat[:, 3] # take largest wins index_sorted = np.argsort(returns)[-5:-1] #2 plot candlesticks fig, subplt = plt.subplots(4, 1) i = 0 for ax in subplt: #plt.setp(ax, xlim=[b, e], ylim=[min(lowD1[b:e]), max(highD1[b:e])]) b = index_sorted[i] - 5 e = index_sorted[i] + 5 candlestick2(ax, openD1[b:e], closeD1[b:e], highD1[b:e], lowD1[b:e], 0.5, 'g', 'r') i += 1 del b, e, openD1, highD1, lowD1, closeD1, index_sorted
def plot_bars(self, bar_start=0): self.mpl.canvas.ax.clear() self.mpl.canvas.ax2.clear() bar_end = min(bar_start + self.bars_in_view, self.bar_len) # plot range bars opens = self.bt.range_bar.Open[bar_start:bar_end] closes = self.bt.range_bar.Close[bar_start:bar_end] highs = self.bt.range_bar.High[bar_start:bar_end] lows = self.bt.range_bar.Low[bar_start:bar_end] dates = self.bt.range_bar.CloseTime[bar_start:bar_end] opens.reverse() closes.reverse() highs.reverse() lows.reverse() dates.reverse() mplfin.candlestick2(self.mpl.canvas.ax, opens=opens, closes=closes, highs=highs, lows=lows, width=0.75, colorup=u'g') # plot indicators tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.) first_strat = self.bt.strategies[self.bt.strategies.keys()[0]] for ind, name in enumerate(first_strat.indicators): indicator_val = first_strat.indicators[name].val[bar_start:bar_end] indicator_val.reverse() self.mpl.canvas.ax2.bar(range(self.bars_in_view), indicator_val, width=0.50, color=tableau20[(ind * 5) % len(tableau20)]) # plots trades from all strategies onto candlesticks strat_name = self.bt.strategies.keys() strat_name.sort() for s in strat_name: strat = self.bt.strategies[s] entry_bar = strat.trades.entry_bar exit_bar = strat.trades.exit_bar entry_price = strat.trades.entry_price exit_price = strat.trades.exit_price market_pos = strat.trades.market_pos # use binary search for first trade and last trade index trade_start = self.nearest_idx_gte( entry_bar, self.bt.range_bar.cnt - bar_end - 1) trade_end = self.nearest_idx_gte( exit_bar, self.bt.range_bar.cnt - bar_start - 1) if trade_start and not trade_end: trade_end = trade_start + 1 for idx in range(trade_start, trade_end): bar_x = [ entry_bar[idx] - (self.bt.range_bar.cnt - bar_start) + self.bars_in_view, exit_bar[idx] - (self.bt.range_bar.cnt - bar_start) + self.bars_in_view ] bar_y = [entry_price[idx], exit_price[idx]] if market_pos[idx] == "LONG": self.mpl.canvas.ax.plot(bar_x, bar_y, color='g', linestyle='--', linewidth=2.0) else: self.mpl.canvas.ax.plot(bar_x, bar_y, color='r', linestyle='--', linewidth=2.0) self.mpl.canvas.ax.get_yaxis().grid(True) self.mpl.canvas.ax.get_yaxis().get_major_formatter().set_useOffset( False) increment = 10 xidx = np.arange(0, self.bars_in_view, increment) + round( increment / 2) + bar_start % increment self.mpl.canvas.ax.set_xticks(xidx) time_list = [ dates[int(idx)].time() for idx in xidx if idx < self.bars_in_view ] date_list = [ dates[int(idx)].date() for idx in xidx if idx < self.bars_in_view ] self.label_view_date.setText( str(dates[-1].date()) + " " + str(dates[-1].time()) + " ") self.mpl.canvas.ax.set_xticklabels(time_list) self.mpl.canvas.ax.get_xaxis().grid(True) self.mpl.canvas.ax.set_xlim(xmin=-1, xmax=self.bars_in_view) self.mpl.canvas.ax2.get_yaxis().grid(True) self.mpl.canvas.ax2.get_yaxis().get_major_formatter().set_useOffset( False) self.mpl.canvas.ax2.get_xaxis().grid(True) self.mpl.canvas.draw()
@author: chew-z """ import matplotlib.pyplot as plt import numpy as np from matplotlib.finance import candlestick2 # 1 read OHLC g = globals() # read global variables d_mat = g['d_mat'] returns = g['returns'] openD1 = d_mat[:, 0] highD1 = d_mat[:, 1] lowD1 = d_mat[:, 2] closeD1 = d_mat[:, 3] # take largest wins index_sorted = np.argsort(returns)[-5:-1] #2 plot candlesticks fig, subplt = plt.subplots(4, 1) i = 0 for ax in subplt: #plt.setp(ax, xlim=[b, e], ylim=[min(lowD1[b:e]), max(highD1[b:e])]) b = index_sorted[i]-5 e = index_sorted[i]+5 candlestick2(ax, openD1[b:e], closeD1[b:e], highD1[b:e], lowD1[b:e], 0.5, 'g', 'r') i += 1 del b, e, openD1, highD1, lowD1, closeD1, index_sorted
# -*- coding: utf-8 -*- """ Created on Wed Oct 1 16:00:26 2014 1) Plot candlestick from MQL data (with data window b:e) @author: chew-z """ import matplotlib.pyplot as plt from matplotlib.finance import candlestick2 # 1 read OHLC g = globals() # read global variables d_mat = g['d_mat'] returns = g['returns'] openD1 = d_mat[:, 0] highD1 = d_mat[:, 1] lowD1 = d_mat[:, 2] closeD1 = d_mat[:, 3] b = 4095 e = 4105 #2 plot candlesticks fig, ax = plt.subplots() plt.setp(ax, xlim=[b, e], ylim=[min(lowD1[b:e]), max(highD1[b:e])]) candlestick2(ax, openD1, closeD1, highD1, lowD1, 0.5, 'g', 'r') del b, e, openD1, highD1, lowD1, closeD1
if ind >= len(self.dates) or ind < 0: return '' return self.dates[ind].strftime(self.fmt) formatter = MyFormatter(data.vDate[daysToPlot:]) [per_k, per_d] = stochastic_oscillator.stoc_osc(data.vHigh, data.vLow, data.vClose, 15, 5, 5, "ema") plt.figure(1) ax1 = plt.subplot('411') candlestick2(ax1, data.vOpen[daysToPlot:], data.vClose[daysToPlot:], data.vHigh[daysToPlot:], data.vLow[daysToPlot:], width=0.6) [macdOut, ema, divergence] = macd.macd(data.vClose, 12, 26, 9) ax2 = plt.subplot('412') ax2.plot(macdOut[daysToPlot:]) ax2.plot(ema[daysToPlot:]) ax2.stem(arange(-1 * daysToPlot), divergence[daysToPlot:]) # MACD [macdOut, ema, divergence] = macd.macd(data.vClose, 5, 10, 4) ax2 = plt.subplot('413') ax2.plot(macdOut[daysToPlot:]) ax2.plot(ema[daysToPlot:]) ax2.stem(arange(-1 * daysToPlot), divergence[daysToPlot:]) # Stochastic Oscillator. ax3 = plt.subplot('414')
# -*- coding:utf-8 -*- from pylab import * from matplotlib.ticker import NullFormatter, NullLocator #from matplotlib.finance import quotes_historical_yahoo,candlestick,plot_day_summary, candlestick2 from matplotlib.finance import quotes_historical_yahoo, plot_day_summary, candlestick2 from wolfox.fengine.ifuture.ui.finance import candlestick, candlestick2 date1 = (2004, 2, 1) date2 = (2008, 4, 12) quotes = quotes_historical_yahoo('INTC', date1, date2)[:150] if len(quotes) == 0: raise SystemExit fig = figure(figsize=(16, 7)) fig.subplots_adjust(bottom=0.1) ax = fig.add_subplot(111) ax.patch.set_color('black') nlocator = NullLocator() ax.xaxis.set_major_locator(nlocator) st, sopen, sclose, shigh, slow = np.transpose(quotes)[:5] candlestick2(ax, sopen, sclose, shigh, slow, width=0.6) ax.autoscale_view() show()
t.set_x(0) # align the title left, axes coords t.set_horizontalalignment('left') # align the title left, axes coords axUpper.yaxis.set_major_locator(MultipleLocator(5)) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# #plot_day_summary2(axMiddle, opens, closes, highs, lows) candlestick2(axMiddle, opens, closes, highs, lows, width=0.9) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, '%s daily' % ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top - height, 'MA(5)', color='b', fontsize=textsize,
t.set_x(0) # align the title left, axes coords t.set_horizontalalignment('left') # align the title left, axes coords axUpper.yaxis.set_major_locator( MultipleLocator(5) ) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# #plot_day_summary2(axMiddle, opens, closes, highs, lows) candlestick2(axMiddle, opens, closes, highs, lows) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, '%s daily'%ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top-height, 'MA(5)', color='b', fontsize=textsize, transform=axMiddle.transAxes) t3 = axMiddle.text(left, top-2*height, 'MA(20)', color='r', fontsize=textsize, transform=axMiddle.transAxes) s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' %( time.strftime('%d-%b-%Y'), vopens[-1], vhighs[-1],
t.set_x(0) # align the title left, axes coords t.set_horizontalalignment('left') # align the title left, axes coords axUpper.yaxis.set_major_locator( MultipleLocator(5) ) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# #plot_day_summary2(axMiddle, opens, closes, highs, lows) candlestick2(axMiddle, opens, closes, highs, lows, width=0.9) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, '%s daily'%ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top-height, 'MA(5)', color='b', fontsize=textsize, transform=axMiddle.transAxes) t3 = axMiddle.text(left, top-2*height, 'MA(20)', color='r', fontsize=textsize, transform=axMiddle.transAxes) s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' %( time.strftime('%d-%b-%Y'), vopens[-1], vhighs[-1],
fill_over(axUpper, vind, s, -thresh, purple, over=False) t = axUpper.set_title("Google (GOOG)", fontsize=12) t.set_y(1.05) # move it up a bit higher than the default t.set_x(0) # align the title left, axes coords t.set_horizontalalignment("left") # align the title left, axes coords axUpper.yaxis.set_major_locator(MultipleLocator(5)) # now add some text left, height, top = 0.025, 0.06, 0.85 t = axUpper.text(left, top, "RSI(14) 51.0", fontsize=textsize, transform=axUpper.transAxes) if 1: ############### Middle axes ################# candlestick2(axMiddle, r.open, r.close, r.high, r.low, width=0.9) # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is # upper right left, height, top = 0.025, 0.06, 0.9 t1 = axMiddle.text(left, top, "%s daily" % ticker, fontsize=textsize, transform=axMiddle.transAxes) t2 = axMiddle.text(left, top - height, "MA(5)", color="b", fontsize=textsize, transform=axMiddle.transAxes) t3 = axMiddle.text(left, top - 2 * height, "MA(20)", color="r", fontsize=textsize, transform=axMiddle.transAxes) s = "%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f" % ( time.strftime("%d-%b-%Y"), r.open[-1], r.high[-1], r.low[-1], r.close[-1],
def plot_bars(self, bar_start=0): self.mpl.canvas.ax.clear() self.mpl.canvas.ax2.clear() bar_end = min(bar_start + self.bars_in_view, self.bar_len) # plot range bars opens = self.bt.range_bar.Open[bar_start:bar_end] closes = self.bt.range_bar.Close[bar_start:bar_end] highs = self.bt.range_bar.High[bar_start:bar_end] lows = self.bt.range_bar.Low[bar_start:bar_end] dates = self.bt.range_bar.CloseTime[bar_start:bar_end] opens.reverse() closes.reverse() highs.reverse() lows.reverse() dates.reverse() mplfin.candlestick2(self.mpl.canvas.ax, opens=opens, closes=closes, highs=highs, lows=lows, width=0.75, colorup=u'g') # plot indicators tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.) first_strat = self.bt.strategies[self.bt.strategies.keys()[0]] for ind, name in enumerate(first_strat.indicators): indicator_val = first_strat.indicators[name].val[bar_start:bar_end] indicator_val.reverse() self.mpl.canvas.ax2.bar(range(self.bars_in_view), indicator_val, width=0.50, color=tableau20[(ind*5)%len(tableau20)]) # plots trades from all strategies onto candlesticks strat_name = self.bt.strategies.keys() strat_name.sort() for s in strat_name: strat = self.bt.strategies[s] entry_bar = strat.trades.entry_bar exit_bar = strat.trades.exit_bar entry_price = strat.trades.entry_price exit_price = strat.trades.exit_price market_pos = strat.trades.market_pos # use binary search for first trade and last trade index trade_start = self.nearest_idx_gte(entry_bar, self.bt.range_bar.cnt - bar_end - 1) trade_end = self.nearest_idx_gte(exit_bar, self.bt.range_bar.cnt - bar_start - 1) if trade_start and not trade_end: trade_end = trade_start + 1 for idx in range(trade_start, trade_end): bar_x = [entry_bar[idx] - (self.bt.range_bar.cnt - bar_start) + self.bars_in_view, exit_bar[idx] - (self.bt.range_bar.cnt - bar_start) + self.bars_in_view] bar_y = [entry_price[idx], exit_price[idx]] if market_pos[idx] == "LONG": self.mpl.canvas.ax.plot(bar_x, bar_y, color='g', linestyle='--', linewidth=2.0) else: self.mpl.canvas.ax.plot(bar_x, bar_y, color='r', linestyle='--', linewidth=2.0) self.mpl.canvas.ax.get_yaxis().grid(True) self.mpl.canvas.ax.get_yaxis().get_major_formatter().set_useOffset( False) increment = 10 xidx = np.arange(0, self.bars_in_view, increment) + round( increment / 2) + bar_start % increment self.mpl.canvas.ax.set_xticks(xidx) time_list = [dates[int(idx)].time() for idx in xidx if idx < self.bars_in_view] date_list = [dates[int(idx)].date() for idx in xidx if idx < self.bars_in_view] self.label_view_date.setText(str(dates[-1].date()) + " " + str(dates[-1].time()) + " ") self.mpl.canvas.ax.set_xticklabels(time_list) self.mpl.canvas.ax.get_xaxis().grid(True) self.mpl.canvas.ax.set_xlim(xmin=-1, xmax=self.bars_in_view) self.mpl.canvas.ax2.get_yaxis().grid(True) self.mpl.canvas.ax2.get_yaxis().get_major_formatter().set_useOffset( False) self.mpl.canvas.ax2.get_xaxis().grid(True) self.mpl.canvas.draw()