def fill_between(self, x, y1, y2 = 0, ax = None, where = None, alpha = 1.0 , color = "#888888", legend = [], *args, **kwargs): # This function fills a unique plot. ## We have to f*****g deal with dates !! # The fill function does not work properly with datetime64 x = ul.fnp(x) y1 = ul.fnp(y1) if (type(ax) == type(None)): ax = self.axes x = ul.preprocess_dates(x) x = ul.fnp(x) # print len(X), len(ul.fnp(Yi).T.tolist()[0]) # print type(X), type(ul.fnp(Yi).T.tolist()[0]) # print X.shape # print len(X.T.tolist()), len(ul.fnp(Yi).T.tolist()[0]) x = x.T.tolist()[0] # print x y1 = ul.fnp(y1).T.tolist()[0] if (where is not None): # print len(x), len(y1), len(where) where = ul.fnp(where) # where = np.nan_to_num(where) where = where.T.tolist()[0] y2 = ul.fnp(y2) if (y2.size == 1): y2 = y2[0,0] else: y2 = y2.T.tolist()[0] # print where[0:20] # print y2 # print len(where) # print x[0:5], y1[0:5] if (len(legend) == 0): legend = None else: legend = legend[0] ln = ax.fill_between(x = x, y1 = y1, y2 = y2, where = where, color = color, alpha = alpha, zorder = self.zorder, label = legend) # *args, **kwargs) self.plots_type.append(["fill"]) self.plots_list.append([ln]) # We store the pointers to the plots data_i = [x,y1,y2, where, ax, alpha,color, args, kwargs] self.Data_list.append(data_i) return ln
def fill_between(self, x, y1, y2 = 0, ax = None, where = None, alpha = 1.0 , color = "#888888", legend = [], *args, **kwargs): # This function fills a unique plot. ## We have to f*****g deal with dates !! # The fill function does not work properly with datetime64 x = ul.fnp(x) y1 = ul.fnp(y1) if (type(ax) == type(None)): ax = self.axes x = ul.preprocess_dates(x) x = ul.fnp(x) # print len(X), len(ul.fnp(Yi).T.tolist()[0]) # print type(X), type(ul.fnp(Yi).T.tolist()[0]) # print X.shape # print len(X.T.tolist()), len(ul.fnp(Yi).T.tolist()[0]) x = x.T.tolist()[0] # print x y1 = ul.fnp(y1).T.tolist()[0] if (where is not None): # print len(x), len(y1), len(where) where = ul.fnp(where) # where = np.nan_to_num(where) where = where.T.tolist()[0] y2 = ul.fnp(y2) if (y2.size == 1): y2 = y2[0,0] else: y2 = y2.T.tolist()[0] # print where[0:20] # print y2 # print len(where) # print x[0:5], y1[0:5] if (len(legend) == 0): legend = None else: legend = legend[0] ln = ax.fill_between(x = x, y1 = y1, y2 = y2, where = where, color = color, alpha = alpha, zorder = self.zorder, label = legend) # *args, **kwargs) self.plots_type.append(["fill"]) self.plots_list.append([ln]) # We store the pointers to the plots data_i = [x,y1,y2, where, ax, alpha,color, args, kwargs] self.Data_list.append(data_i) return ln
def add_vlines(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None, # Automatically do some formatting :) marker = [" ", None, None] ): ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpX, NcX = X.shape NpY, NcY = Y.shape # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape plots,plots_typ = self.init_WidgetData(ws) ############### CALL PLOTTING FUNCTION ########################### # X = X.astype(dt.datetime) # self.X = self.X.astype(dt.datetime) X = ul.preprocess_dates(X) self.X = X lines = [[(X[i].astype(dt.datetime), Y[i,0]),(X[i].astype(dt.datetime), Y[i,1])] for i in range(NpX)] # lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]] # print mdates.date2num(X[i,0].astype(dt.datetime)), type(mdates.date2num(X[i,0].astype(dt.datetime))) lc = mc.LineCollection(lines, colors= "k", linewidths=lw) ax.add_collection(lc) ax.autoscale() ax.margins(0.1) ############### Last setting functions ########################### self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(xlim,ylim, xlimPad,ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) return ax
def add_vlines(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None, # Automatically do some formatting :) marker = [" ", None, None] ): ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpX, NcX = X.shape NpY, NcY = Y.shape # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape plots,plots_typ = self.init_WidgetData(ws) ############### CALL PLOTTING FUNCTION ########################### # X = X.astype(dt.datetime) # self.X = self.X.astype(dt.datetime) X = ul.preprocess_dates(X) self.X = X lines = [[(X[i].astype(dt.datetime), Y[i,0]),(X[i].astype(dt.datetime), Y[i,1])] for i in range(NpX)] # lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]] # print mdates.date2num(X[i,0].astype(dt.datetime)), type(mdates.date2num(X[i,0].astype(dt.datetime))) lc = mc.LineCollection(lines, colors= "k", linewidths=lw) ax.add_collection(lc) ax.autoscale() ax.margins(0.1) ############### Last setting functions ########################### self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) return ax
def bar( self, X=[], Y=[], # X-Y points in the graph. labels=[], legend=[], # Basic Labelling color=None, lw=2, alpha=1.0, # Basic line properties nf=0, na=0, # New axis. To plot in a new axis # TODO: shareX option ax=None, position=[], projection="2d", # Type of plot sharex=None, sharey=None, fontsize=20, fontsizeL=10, fontsizeA=15, # The font for the labels in the axis xlim=None, ylim=None, xlimPad=None, ylimPad=None, # Limits of vision ws=None, Ninit=0, loc="best", dataTransform=None, xaxis_mode=None, yaxis_mode=None, AxesStyle=None, # Automatically do some formatting :) marker=[" ", None, None], fill_mode="independent", # "between", "stacked","independent" # Particular pararm orientation="vertical", barwidth=None, # Rectangle width bottom=None, ## If the y-axis start somewhere else despx=0 # Displacement in the x axis, it is done for the dates # so that we can move some other things (Velero graph) ): # Management of the figure and properties ax = self.figure_management(nf, na, ax=ax, sharex=sharex, sharey=sharey, projection=projection, position=position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X, Y, dataTransform) NpY, NcY = Y.shape plots, plots_typ = self.init_WidgetData(ws) ## We asume that X and Y have the same dimensions print(self.formatXaxis) if (self.formatXaxis == "dates" or self.formatXaxis == "intraday"): X = ul.preprocess_dates(X) print("Formating bar X to dates") if (type(barwidth) == type(None)): barwidth = self.get_barwidth(X, barwidth) * 0.8 if (Y.size != 0): # This would be just to create the axes ############### CALL PLOTTING FUNCTION ########################### for i in range(NcY): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] if (type(bottom) != type(None)): bottom = bottom[self.start_indx:self.end_indx] if (orientation == "vertical"): plot_i = self.axes.bar(X[self.start_indx:self.end_indx], Y[self.start_indx:self.end_indx:, i], width=barwidth, align='center', facecolor=colorFinal, alpha=alpha, label=legend_i, zorder=self.zorder, bottom=bottom) else: # horixontal plot_i = self.axes.bar(width=Y[self.start_indx:self.end_indx:, i], height=barwidth, align='center', facecolor=colorFinal, alpha=alpha, label=legend_i, zorder=self.zorder, left=bottom, bottom=X[self.start_indx:self.end_indx], orientation="horizontal") plots.append(plot_i) plots_typ.append("plot") ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend, NcY, ax=ax, loc=loc) # Update the legend self.set_labels(labels) self.set_zoom(xlim, ylim, xlimPad, ylimPad) self.format_xaxis(ax=ax, xaxis_mode=xaxis_mode) self.format_yaxis(ax=ax, yaxis_mode=yaxis_mode) self.apply_style(nf, na, AxesStyle) return ax #fig, ax_list = plt. subplots(3, 1) #x = y = np.arange(5) # #for ax, where in zip(ax_list, ['pre', 'post', 'mid']): # ax.step(x, y, where=where, color='r', zorder=5, lw=5) # fill_between_steps(ax, x, y, 0, step_where=where)
def tradingPlatform(self, timeData, MA1=26, MA2=12, volumeFactor=3, color_mode=1): gl = self ## TODO, it used to be this all the way: ## [-SP:] # SP = len(date[MA2-1:]) if (color_mode == 1): col_spines = "#5998ff" col_axis = 'k' bg_color = '#555555' # '#07000d' stockTD = timeData.get_timeData() date = stockTD.index.values date = ul.fnp(date) date = ul.preprocess_dates(date) # print pd.to_datetime(date[0]) # mdates.strpdate2num('%Y%m%d') # date = mdates.date2num(date) # date = range(len(date)) openp = stockTD["Open"] closep = stockTD["Close"] highp = stockTD["High"] lowp = stockTD["Low"] volume = stockTD["Volume"] x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x] newAr.append(appendLine) x += 1 # print newAr[0:4] newAr = ul.fnp(newAr).T # print newAr.shape ## Plotting !! # fig = plt.figure(facecolor='#07000d') ########################################################### ################# PLOTTING THE CANDLESTICK ################ ########################################################### # We will divide everything in 6x4 and this will take the 4x4 in the middle # Obtain data to plot Av1 = timeData.SMA(n=MA1) Av2 = timeData.SMA(n=MA2) ax1 = gl.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg=bg_color) gl.plot(date, Av1, nf=0, color='#e1edf9', legend=[str(MA1) + ' SMA'], lw=1.5) gl.plot(date, Av2, nf=0, color='#4ee6fd', legend=[str(MA2) + ' SMA'], lw=1.5) ax1.grid(True, color='w') gl.tradingPV(timeData, color_mode=1, fontsize=15, volumeFactor=volumeFactor) ## Format the legend !! maLeg = ax1.legend(loc=9, ncol=2, prop={'size': 7}, fancybox=True, borderaxespad=0.) maLeg.get_frame().set_alpha(0.4) textEd = ax1.get_legend().get_texts() pylab.setp(textEd[0:5], color='w') ##################################################################### ############## In the upper part plot RSI ########################### ##################################################################### rsi = timeData.RSI(n=14) # print rsi[0:30] ax0 = gl.subplot2grid((6, 4), (0, 0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') tradingOcillator(self, timeData, rsi, osc_name="RSI", ax=None, color_mode=1, lowline=30, highline=70) ##################################################################### ############## MACD Axes ########################### ##################################################################### ax2 = gl.subplot2grid((6, 4), (5, 0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') gl.plotMACD(timeData, ax=ax2) ## Remove the xticklabels of the other axes !! plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ## Final touches !!! plt.suptitle("Trasing Station", color='k', fontsize=20) ### Do some stupid anotation !!!! # ax1.annotate('Big news!',(date[510],Av1[510]), # xytext=(0.8, 0.9), textcoords='axes fraction', # arrowprops=dict(facecolor='white', shrink=0.05), # fontsize=14, color = 'w', # horizontalalignment='right', verticalalignment='bottom') ## Smaller overall image ! So that we can put more stuff !! plt.subplots_adjust(left=.09, bottom=.14, right=.70, top=.95, wspace=.20, hspace=0) plt.show()
def tradingPV(self, timeData, ax=None, width=0.6, color_mode=0, fontsize=-1, Ny=6, Nx=20, volumeFactor=3): ## This thing plots the trading price, value. ## If an axes if given to it, it plots it there, ## otherwise it does it on the last if (color_mode == 0): col_spines = "#5998ff" bg_color = '#07000d' col_axis = 'w' colorup = '#53c156' colordown = '#ff1717' colorVolume = '#00ffe8' if (color_mode == 1): col_spines = "#5998ff" bg_color = '#07000d' col_axis = 'k' colorup = '#53c156' colordown = '#ff1717' colorVolume = '#00ffe8' gl = self stockTD = timeData.get_timeData() date = stockTD.index.values date = ul.fnp(date) date = ul.preprocess_dates(date) # return 1 # print date[0:5] openp = stockTD["Open"] closep = stockTD["Close"] highp = stockTD["High"] lowp = stockTD["Low"] volume = stockTD["Volume"] x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x] newAr.append(appendLine) x += 1 newAr = ul.fnp(newAr).T # We will divide everything in 6x4 and this will take the 4x4 in the middle # print "rev %f" % width width = gl.get_barwidth(date, width) # print width if (ax is None): ax = self.axes gl.candlestick(newAr, ax=ax, width=width, colorup=colorup, colordown=colordown) # return 1 # pylab.setp(ax1 , axis_bgcolor = bg_color) ax.set_axis_bgcolor(bg_color) ### Format the axis color :) !! gl.color_axis(ax, col_spines, col_axis) ### Format the axis locators ! :) !! gl.format_axis2(ax, Nx=Nx, Ny=Ny, fontsize=fontsize) ax.set_ylabel(timeData.symbol, fontsize=fontsize) ## Volume AXES, the same as the price one ! volumeMin = 0 ax1v = gl.plot(date, volume, fill=1, alpha=.4, lw=0.1, color=colorVolume, nf=0, na=1) # ax1v = gl.step(date, volume, # fill = 1, alpha=.4, lw = 0.1, color = '#00ffe8', nf = 0, na =1) # ax1v = gl.bar(date, volume, # alpha=.4, color = '#00ffe8', nf = 0, na =1) ax.grid(True, color="w") ax1v.grid(False) gl.color_axis(ax1v, col_spines, col_axis) gl.format_axis2(ax1v, Nx=Nx, Ny=Ny, fontsize=fontsize) ## Remove the volume labels !!! ax1v.yaxis.set_ticklabels([]) ## Set limits ! ax1v.set_ylim(0, volumeFactor * max(volume)) ax.set_xlim(date[0] - width, date[-1] + width)
def candlestick(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None, # Automatically do some formatting :) barwidth = None, colorup = "g", colordown = "r" ): # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape plots,plots_typ = self.init_WidgetData(ws) ##################### PREPROCESSING AND PLOTTING ####################### # Prepare the data openp = Y[self.start_indx:self.end_indx,0] closep = Y[self.start_indx:self.end_indx,1] highp = Y[self.start_indx:self.end_indx,2] lowp = Y[self.start_indx:self.end_indx,3] dates = X[self.start_indx:self.end_indx] dates = ul.preprocess_dates(dates) if (type(barwidth) == type(None)): barwidth = self.get_barwidth(dates, barwidth) * 0.8 # PLOTTING !! Npoints = dates.size OFFSET = barwidth / 2.0 line_factor = 0.15 barwidth_HL = barwidth * line_factor OFFSET_HL = barwidth_HL / 2.0 lines = [] patches = [] for i in range(Npoints): if closep[i] >= openp[i] : color = colorup baseRectable = openp[i] else: color = colordown baseRectable = closep[i] height = np.abs(openp[i] - closep[i]) ## High-low line # line_HL = Line2D( # xdata=(dates[i],dates[i]), ydata=(lowp[i], highp[i]), # color=color, # linewidth=lw, # antialiased=True, # ) rect_HL = Rectangle( xy=(dates[i] - OFFSET_HL, lowp[i]), width=barwidth_HL, height=highp[i] - lowp[i], facecolor=color, edgecolor=color, ) # print type(dates[i]), type(OFFSET) ## Open Close rectangle rect_OP = Rectangle( xy=(dates[i] - OFFSET, baseRectable), width=barwidth, height=height, facecolor=color, edgecolor=color, ) rect_OP.set_alpha(alpha) # # lines.append(line_HL) # patches.append(rect_OP) # ax.add_line(line_HL) ax.add_patch(rect_OP) ax.add_patch(rect_HL) # lines = mc.LineCollection(lines) # ax.add_collection(lines) # ax.add_collection(patches) ax.autoscale() # TODO: The zoom is not changed if we do not say it ! ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) self.plots_type.append(["candlestick"]) # self.plots_list.append([plotting]) # We store the pointers to the plots data_i = [Y, ax] self.Data_list.append(data_i) return ax
def barchart(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, lw2 = 2,alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None # Automatically do some formatting :) ): # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape NpX, NcX = Y.shape plots,plots_typ = self.init_WidgetData(ws) ############### CALL PLOTTING FUNCTION ########################### # X = X.astype(dt.datetime) # self.X = self.X.astype(dt.datetime) # print X.shape High,Low, Open,Close = Y[:,0], Y[:,1], Y[:,2], Y[:,3] X = ul.preprocess_dates(X) self.X = X # print X width_unit = self.get_barwidth(X) dist = width_unit /2.2 # High-Low linesHL = [[(X[i].astype(dt.datetime),Low[i]),(X[i].astype(dt.datetime), High[i])] for i in range(NpX)] linesO = [[(X[i].astype(dt.datetime) - dist,Open[i]),(X[i].astype(dt.datetime), Open[i])] for i in range(NpX)] linesC = [[(X[i].astype(dt.datetime),Close[i]),(X[i].astype(dt.datetime) + dist, Close[i])] for i in range(NpX)] # lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]] # print mdates.date2num(X[i,0].astype(dt.datetime)), type(mdates.date2num(X[i,0].astype(dt.datetime))) self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) # TODO: Handle the legend better lcHL = mc.LineCollection(linesHL, colors= colorFinal, linewidths=lw, antialiased=True, label = legend[0]) lcO = mc.LineCollection(linesO, colors= colorFinal, linewidths=lw2, antialiased=True) lcC = mc.LineCollection(linesC, colors= colorFinal, linewidths=lw2, antialiased=True) ax.add_collection(lcHL) ax.add_collection(lcO) ax.add_collection(lcC) ax.autoscale() # TODO: The zoom is not changed if we do not say it ! # ax.margins(0.1) ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) # xfmt = mdates.DateFormatter('%b %d') # ax.xaxis.set_major_formatter(xfmt) return ax
def candlestick( self, X=[], Y=[], # X-Y points in the graph. labels=[], legend=[], # Basic Labelling color=None, lw=2, alpha=1.0, # Basic line properties nf=0, na=0, # New axis. To plot in a new axis # TODO: shareX option ax=None, position=[], projection="2d", # Type of plot sharex=None, sharey=None, fontsize=20, fontsizeL=10, fontsizeA=15, # The font for the labels in the axis xlim=None, ylim=None, xlimPad=None, ylimPad=None, # Limits of vision ws=None, Ninit=0, loc="best", dataTransform=None, xaxis_mode=None, yaxis_mode=None, AxesStyle=None, # Automatically do some formatting :) barwidth=None, colorup="g", colordown="r"): # Management of the figure and properties ax = self.figure_management(nf, na, ax=ax, sharex=sharex, sharey=sharey, projection=projection, position=position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X, Y, dataTransform) NpY, NcY = Y.shape plots, plots_typ = self.init_WidgetData(ws) ##################### PREPROCESSING AND PLOTTING ####################### # Prepare the data openp = Y[self.start_indx:self.end_indx, 0] closep = Y[self.start_indx:self.end_indx, 1] highp = Y[self.start_indx:self.end_indx, 2] lowp = Y[self.start_indx:self.end_indx, 3] dates = X[self.start_indx:self.end_indx] dates = ul.preprocess_dates(dates) if (type(barwidth) == type(None)): barwidth = self.get_barwidth(dates, barwidth) * 0.8 # PLOTTING !! Npoints = dates.size OFFSET = barwidth / 2.0 line_factor = 0.15 barwidth_HL = barwidth * line_factor OFFSET_HL = barwidth_HL / 2.0 lines = [] patches = [] for i in range(Npoints): if closep[i] >= openp[i]: color = colorup baseRectable = openp[i] else: color = colordown baseRectable = closep[i] height = np.abs(openp[i] - closep[i]) ## High-low line # line_HL = Line2D( # xdata=(dates[i],dates[i]), ydata=(lowp[i], highp[i]), # color=color, # linewidth=lw, # antialiased=True, # ) rect_HL = Rectangle( xy=(dates[i] - OFFSET_HL, lowp[i]), width=barwidth_HL, height=highp[i] - lowp[i], facecolor=color, edgecolor=color, ) # print type(dates[i]), type(OFFSET) ## Open Close rectangle rect_OP = Rectangle( xy=(dates[i] - OFFSET, baseRectable), width=barwidth, height=height, facecolor=color, edgecolor=color, ) rect_OP.set_alpha(alpha) # # lines.append(line_HL) # patches.append(rect_OP) # ax.add_line(line_HL) ax.add_patch(rect_OP) ax.add_patch(rect_HL) # lines = mc.LineCollection(lines) # ax.add_collection(lines) # ax.add_collection(patches) ax.autoscale() # TODO: The zoom is not changed if we do not say it ! ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend, NcY, ax=ax, loc=loc) # Update the legend self.set_labels(labels) self.set_zoom(ax=ax, xlim=xlim, ylim=ylim, xlimPad=xlimPad, ylimPad=ylimPad) self.format_xaxis(ax=ax, xaxis_mode=xaxis_mode) self.format_yaxis(ax=ax, yaxis_mode=yaxis_mode) self.apply_style(nf, na, AxesStyle) self.plots_type.append(["candlestick"]) # self.plots_list.append([plotting]) # We store the pointers to the plots data_i = [Y, ax] self.Data_list.append(data_i) return ax
def bar(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None, # Automatically do some formatting :) marker = [" ", None, None], fill_mode = "independent", # "between", "stacked","independent" # Particular pararm orientation = "vertical", barwidth = None, # Rectangle width bottom = None, ## If the y-axis start somewhere else despx = 0, # Displacement in the x axis, it is done for the dates # so that we can move some other things (Velero graph) align = "edge" # "center" ): # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape plots,plots_typ = self.init_WidgetData(ws) # print (X) ## We asume that X and Y have the same dimensions # print (self.formatXaxis) if (self.formatXaxis == "dates" or self.formatXaxis == "intraday"): X = ul.preprocess_dates(X) print ("Formating bar X to dates") if (type(barwidth) == type(None)): barwidth = self.get_barwidth(X, barwidth) * 0.8 # print ("Barwidth: ", barwidth) if (Y.size != 0): # This would be just to create the axes ############### CALL PLOTTING FUNCTION ########################### for i in range(NcY): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] if(type(bottom) != type(None)): bottom = bottom[self.start_indx:self.end_indx].flatten() if (orientation == "vertical"): plot_i = self.axes.bar(X[self.start_indx:self.end_indx].flatten(), Y[self.start_indx:self.end_indx:,i].flatten(), width = barwidth, align=align, facecolor= colorFinal,alpha=alpha, label = legend_i, zorder = self.zorder, bottom = bottom) else: # horixontal plot_i = self.axes.bar(width = Y[self.start_indx:self.end_indx:,i].flatten(), height = barwidth, align=align, facecolor= colorFinal,alpha=alpha, label = legend_i, zorder = self.zorder, left = bottom, bottom = X[self.start_indx:self.end_indx].flatten(), orientation = "horizontal") plots.append(plot_i) plots_typ.append("plot") ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) return ax #fig, ax_list = plt. subplots(3, 1) #x = y = np.arange(5) # #for ax, where in zip(ax_list, ['pre', 'post', 'mid']): # ax.step(x, y, where=where, color='r', zorder=5, lw=5) # fill_between_steps(ax, x, y, 0, step_where=where)
def barchart( self, X=[], Y=[], # X-Y points in the graph. labels=[], legend=[], # Basic Labelling color=None, lw=2, lw2=2, alpha=1.0, # Basic line properties nf=0, na=0, # New axis. To plot in a new axis # TODO: shareX option ax=None, position=[], projection="2d", # Type of plot sharex=None, sharey=None, fontsize=20, fontsizeL=10, fontsizeA=15, # The font for the labels in the axis xlim=None, ylim=None, xlimPad=None, ylimPad=None, # Limits of vision ws=None, Ninit=0, loc="best", dataTransform=None, xaxis_mode=None, yaxis_mode=None, AxesStyle=None # Automatically do some formatting :) ): # Management of the figure and properties ax = self.figure_management(nf, na, ax=ax, sharex=sharex, sharey=sharey, projection=projection, position=position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X, Y, dataTransform) NpY, NcY = Y.shape NpX, NcX = Y.shape plots, plots_typ = self.init_WidgetData(ws) ############### CALL PLOTTING FUNCTION ########################### # X = X.astype(dt.datetime) # self.X = self.X.astype(dt.datetime) # print X.shape High, Low, Open, Close = Y[:, 0], Y[:, 1], Y[:, 2], Y[:, 3] X = ul.preprocess_dates(X) self.X = X # print X width_unit = self.get_barwidth(X) dist = width_unit / 2.2 # High-Low linesHL = [[(X[i].astype(dt.datetime), Low[i]), (X[i].astype(dt.datetime), High[i])] for i in range(NpX)] linesO = [[(X[i].astype(dt.datetime) - dist, Open[i]), (X[i].astype(dt.datetime), Open[i])] for i in range(NpX)] linesC = [[(X[i].astype(dt.datetime), Close[i]), (X[i].astype(dt.datetime) + dist, Close[i])] for i in range(NpX)] # lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]] # print mdates.date2num(X[i,0].astype(dt.datetime)), type(mdates.date2num(X[i,0].astype(dt.datetime))) self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) lcHL = mc.LineCollection(linesHL, colors=colorFinal, linewidths=lw, antialiased=True) lcO = mc.LineCollection(linesO, colors=colorFinal, linewidths=lw2, antialiased=True) lcC = mc.LineCollection(linesC, colors=colorFinal, linewidths=lw2, antialiased=True) ax.add_collection(lcHL) ax.add_collection(lcO) ax.add_collection(lcC) ax.autoscale() # TODO: The zoom is not changed if we do not say it ! # ax.margins(0.1) ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend, NcY, ax=ax, loc=loc) # Update the legend self.set_labels(labels) self.set_zoom(xlim, ylim, xlimPad, ylimPad) self.format_xaxis(ax=ax, xaxis_mode=xaxis_mode) self.format_yaxis(ax=ax, yaxis_mode=yaxis_mode) self.apply_style(nf, na, AxesStyle) # xfmt = mdates.DateFormatter('%b %d') # ax.xaxis.set_major_formatter(xfmt) return ax
def bar( self, X=[], Y=[], # X-Y points in the graph. labels=[], # Labels for tittle, axis and so on. legend=[], # Legend for the curves plotted nf=1, # New figure na=0, # New axis. To plot in a new axis # Basic parameters that we can usually find in a plot color=None, # Color width=-1.0, # Rectangle width bottom=None, ## If the y-axis start somewhere else alpha=1.0, # Alpha despx=0, # Displacement in the x axis, it is done for the dates # so that we can move some other things (Velero graph) fontsize=20, # The font for the labels in the title fontsizeL=10, # The font for the labels in the legeng fontsizeA=15, # The font for the labels in the axis ws=-1, loc=1): ## Preprocess the data given so that it meets the right format self.preprocess_data(X, Y) X = self.X Y = self.Y NpX, NcX = X.shape NpY, NcY = Y.shape # print X.shape, Y.shape # Management of the figure self.figure_management(nf, na, labels, fontsize) ################################################################## ############### CALL SCATTERING FUNCTION ########################### ################################################################## if (ws == -1): # We only show the last ws samples ws = NpX if (type(bottom) == type(None)): bottom = np.zeros((NpX, 1)) plots = [] plots_typ = [] ## We asume that X and Y have the same dimensions colorFinal = self.get_color(color) X = ul.preprocess_dates(X) width = self.get_barwidth(X, width) self.zorder = self.zorder + 1 # print self.zorder # X = ul.fnp(X) # It kills stuff if (len(legend) == 0): plot_i = self.axes.bar(X[(NpX - ws):], Y[(NpX - ws):], width=width, align='center', facecolor=colorFinal, alpha=alpha, bottom=bottom[(NpX - ws):], zorder=self.zorder) else: plot_i = self.axes.bar(X[(NpX - ws):], Y[(NpX - ws):], width=width, align='center', facecolor=colorFinal, alpha=alpha, label=legend[0], zorder=self.zorder, bottom=bottom[(NpX - ws):]) plots.append(plot_i) plots_typ.append("bar") # print plots_typ ## Store pointers to variables for interaction self.plots_type.append(plots_typ) self.plots_list.append(plots) # We store the pointers to the plots data_i = [X, Y, bottom] self.Data_list.append(data_i) # print len(X) # print Y.shape # print bottom.shape self.format_axis(nf, fontsize=fontsizeA, wsize=ws, val=NpX - ws) self.update_legend(legend, NcY, loc=loc) # When nf = 0 and na = 0, we lose the grid for some reason. if (na == 1 or nf == 1): self.format_plot() # print self.plots_type ax = self.axes return ax
def scatter( self, X=[], Y=[], # X-Y points in the graph. labels=[], # Labels for tittle, axis and so on. legend=[], # Legend for the curves plotted nf=1, # New figure na=0, # New axis. To plot in a new axis # Basic parameters that we can usually find in a plot color=None, # Color lw=2, # Line width alpha=1.0, # Alpha ws=-1, fontsize=20, # The font for the labels in the title fontsizeL=10, # The font for the labels in the legeng fontsizeA=15, # The font for the labels in the axis loc=1): ## Preprocess the data given so that it meets the right format self.preprocess_data(X, Y) X = self.X Y = self.Y NpX, NcX = X.shape NpY, NcY = Y.shape # Management of the figure self.figure_management(nf, na, labels, fontsize) ################################################################## ############### CALL SCATTERING FUNCTION ########################### ################################################################## ## We asume that X and Y have the same dimensions colorFinal = self.get_color(color) X = ul.preprocess_dates(X) self.zorder = self.zorder + 1 if (len(legend) == 0): plt.scatter(X, Y, lw=lw, alpha=alpha, color=colorFinal, zorder=self.zorder) else: # print X.shape, Y.shape plt.scatter(X, Y, lw=lw, alpha=alpha, color=colorFinal, label=legend[0], zorder=self.zorder) self.format_axis(nf, fontsize=fontsizeA, wsize=ws, val=NpX - ws) self.update_legend(legend, NcY, loc=loc) if (na == 1 or nf == 1): self.format_plot() return 0
def tradingPV(self, timeData, ax = None, width = 0.6, color_mode = 0, fontsize = -1, Ny = 6, Nx = 20, volumeFactor = 3): ## This thing plots the trading price, value. ## If an axes if given to it, it plots it there, ## otherwise it does it on the last if (color_mode == 0): col_spines = "#5998ff" bg_color = '#07000d';col_axis = 'w' colorup='#53c156'; colordown='#ff1717' colorVolume = '#00ffe8' if (color_mode == 1): col_spines = "#5998ff" bg_color = '#07000d';col_axis = 'k' colorup='#53c156'; colordown='#ff1717' colorVolume = '#00ffe8' gl = self stockTD = timeData.get_TD() date = stockTD.index.values date = ul.fnp(date) date = ul.preprocess_dates(date) # return 1 # print date[0:5] openp = stockTD["Open"] closep = stockTD["Close"] highp = stockTD["High"] lowp = stockTD["Low"] volume = stockTD["Volume"] x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x] newAr.append(appendLine) x+=1 newAr = ul.fnp(newAr).T # We will divide everything in 6x4 and this will take the 4x4 in the middle # print "rev %f" % width width = gl.get_barwidth(date, width) # print width if (ax is None): ax = self.axes gl.candlestick(newAr, ax = ax, barwidth = width,colorup=colorup, colordown=colordown) # return 1 # pylab.setp(ax1 , axis_bgcolor = bg_color) ax.set_axis_bgcolor(bg_color) ### Format the axis color :) !! gl.color_axis(ax, col_spines, col_axis) ### Format the axis locators ! :) !! gl.format_axis2(ax, Nx = Nx, Ny = Ny, fontsize = fontsize) ax.set_ylabel(timeData.symbol, fontsize = fontsize) ## Volume AXES, the same as the price one ! volumeMin = 0 ax1v = gl.plot(date, volume, fill = 1, alpha=.4, lw = 0.1, color = colorVolume, nf = 0, na =1) # ax1v = gl.step(date, volume, # fill = 1, alpha=.4, lw = 0.1, color = '#00ffe8', nf = 0, na =1) # ax1v = gl.bar(date, volume, # alpha=.4, color = '#00ffe8', nf = 0, na =1) ax.grid(True, color="w") ax1v.grid(False) gl.color_axis(ax1v, col_spines, col_axis) gl.format_axis2(ax1v, Nx = Nx, Ny = Ny, fontsize = fontsize) ## Remove the volume labels !!! ax1v.yaxis.set_ticklabels([]) ## Set limits ! ax1v.set_ylim(0,volumeFactor * max(volume)) ax.set_xlim(date[0] -width, date[-1] + width)
def tradingPlatform(self, timeData, MA1 = 26, MA2 = 12, volumeFactor = 3, color_mode = 1): gl = self ## TODO, it used to be this all the way: ## [-SP:] # SP = len(date[MA2-1:]) if (color_mode == 1): col_spines = "#5998ff" col_axis = 'k' bg_color = '#555555' # '#07000d' stockTD = timeData.get_timeData() date = stockTD.index.values date = ul.fnp(date) date = ul.preprocess_dates(date) # print pd.to_datetime(date[0]) # mdates.strpdate2num('%Y%m%d') # date = mdates.date2num(date) # date = range(len(date)) openp = stockTD["Open"] closep = stockTD["Close"] highp = stockTD["High"] lowp = stockTD["Low"] volume = stockTD["Volume"] x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x] newAr.append(appendLine) x+=1 # print newAr[0:4] newAr = ul.fnp(newAr).T # print newAr.shape ## Plotting !! # fig = plt.figure(facecolor='#07000d') ########################################################### ################# PLOTTING THE CANDLESTICK ################ ########################################################### # We will divide everything in 6x4 and this will take the 4x4 in the middle # Obtain data to plot Av1 = timeData.SMA( n = MA1) Av2 = timeData.SMA(n = MA2) ax1 = gl.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg= bg_color) gl.plot(date,Av1, nf = 0, color = '#e1edf9',legend=[str(MA1)+' SMA'], lw = 1.5) gl.plot(date,Av2, nf = 0, color = '#4ee6fd',legend=[str(MA2)+' SMA'], lw = 1.5) ax1.grid(True, color='w') gl.tradingPV(timeData, color_mode = 1, fontsize = 15, volumeFactor = volumeFactor) ## Format the legend !! maLeg = ax1.legend(loc=9, ncol=2, prop={'size':7}, fancybox=True, borderaxespad=0.) maLeg.get_frame().set_alpha(0.4) textEd = ax1.get_legend().get_texts() pylab.setp(textEd[0:5], color = 'w') ##################################################################### ############## In the upper part plot RSI ########################### ##################################################################### rsi = timeData.RSI(n = 14) # print rsi[0:30] ax0 = gl.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') tradingOcillator(self, timeData, rsi, osc_name = "RSI", ax = None, color_mode = 1, lowline = 30, highline = 70) ##################################################################### ############## MACD Axes ########################### ##################################################################### ax2 = gl.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') gl.plotMACD(timeData, ax = ax2) ## Remove the xticklabels of the other axes !! plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ## Final touches !!! plt.suptitle("Trasing Station",color='k', fontsize = 20) ### Do some stupid anotation !!!! # ax1.annotate('Big news!',(date[510],Av1[510]), # xytext=(0.8, 0.9), textcoords='axes fraction', # arrowprops=dict(facecolor='white', shrink=0.05), # fontsize=14, color = 'w', # horizontalalignment='right', verticalalignment='bottom') ## Smaller overall image ! So that we can put more stuff !! plt.subplots_adjust(left=.09, bottom=.14, right=.70, top=.95, wspace=.20, hspace=0) plt.show()