def draw_figure(canvas, figure, loc=(0, 0)): """ Draw a matplotlib figure onto a Tk canvas loc: location of top-left corner of figure on canvas in pixels. Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py """ figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = PhotoImage(master=canvas, width=figure_w, height=figure_h) # Position: convert from top-left anchor to center anchor canvas.create_image(loc[0] + figure_w / 2, loc[1] + figure_h / 2, image=photo) # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears return photo
def main(): fig = Figure() ax = fig.add_subplot(111) ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.grid() canvas_elem = g.Canvas(size=(640, 480)) # get the canvas we'll be drawing on slider_elem = g.Slider(range=(0, 10000), size=(60, 10), orientation='h') # define the form layout layout = [[ g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20') ], [canvas_elem], [slider_elem], [ g.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14') ]] # create the form and show it without the plot form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI') form.Layout(layout) form.ReadNonBlocking() graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) canvas = canvas_elem.TKCanvas dpts = [randint(0, 10) for x in range(10000)] for i in range(len(dpts)): button, values = form.ReadNonBlocking() if button is 'Exit' or values is None: exit(69) slider_elem.Update(i) ax.cla() ax.grid() DATA_POINTS_PER_SCREEN = 40 ax.plot(range(DATA_POINTS_PER_SCREEN), dpts[i:i + DATA_POINTS_PER_SCREEN], color='purple') graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def plot_figure(self, fig): if self._empty: self._empty = False self._canvas.delete(self._text_id) f_w = fig.get_window_extent().width f_h = fig.get_window_extent().height f_w, f_h = int(f_w), int(f_h) # draw out figure fca = FigureCanvasAgg(fig) fca.draw() f_w, f_h = fca.get_renderer().get_canvas_width_height() f_w, f_h = int(f_w), int(f_h) self._graph_h += f_h self._graph_w = max(self._graph_w, f_w) self._canvas.config(width=self._graph_w, height=self._graph_h) self._canvas.grid(row=0, column=0) photo = tk.PhotoImage(master=self._canvas, width=f_w, height=f_h) self._canvas.create_image(f_w/2, self._graph_h-f_h/2, image=photo) tkagg.blit(photo, fca.get_renderer()._renderer, colormode=2) self._root.update() self._figs.append(fig) self._fcas[fig] = fca self._photos[fig] = photo
def draw_figure(canvas, figure, loc = (0,0)): figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo
def draw(fig, canvas): # Magic code that draws the figure onto the Canvas Element's canvas figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo
def draw_figure(canvas, figure, loc=(0, 0)): # Convert plot figure into a photo object figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.image = photo canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) plt.close('all') return photo
def draw_figure(canvas, figure, loc=(0, 0)): """ Draw a matplotlib figure onto a Tk canvas loc: location of top-left corner of figure on canvas in pixels. Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py """ figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo
def draw_figure(canvas, figure, loc=(0, 0)): figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(loc[0] + figure_w / 2, loc[1] + figure_h / 2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) #return handle containing reference to photo - must be kept live else picture disappears return photo
def _plot_pic(self, figure, gait_canvas): """ 在pysimplegui上绘制plot。调用这个函数必须接受返回值,不接受的话无法绘图,我也不知道为啥,辣鸡tkinter :param gait_canvas: :param figure: :return: """ figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=gait_canvas, width=figure_w, height=figure_h) gait_canvas.create_image(figure_w / 2, figure_h / 2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo
def update_graph(): graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.image = photo canvas.pack(fill="both", expand=True) canvas.create_image(fig.get_figwidth() * 100 / 2, fig.get_figheight() * 100 / 2, image=photo) #canvas.update(size=(size(window_g)[0],size(window_g)[1])) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() _backend_tk.blit(photo, figure_canvas_agg.get_renderer()._renderer, (0, 1, 2, 3))
def main(): # define the form layout layout = [[sg.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')], [sg.Canvas(size=(640, 480), key='canvas')], [sg.ReadButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] # create the form and show it without the plot window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() canvas_elem = window.FindElement('canvas') canvas = canvas_elem.TKCanvas while True: event, values = window.Read(timeout=10) if event in ('Exit', None): exit(69) def PyplotScatterWithLegend(): import matplotlib.pyplot as plt from numpy.random import rand fig, ax = plt.subplots() for color in ['red', 'green', 'blue']: n = 750 x, y = rand(2, n) scale = 200.0 * rand(n) ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none') ax.legend() ax.grid(True) return fig fig = PyplotScatterWithLegend() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640/2, 480/2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() # Unfortunately, there's no accessor for the pointer to the native renderer tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def update_graph(): slide = int(values['slider']) ax.cla() ax.hist(x, bins, alpha=0.5, label='x', color='pink') ax.hist(y, bins, alpha=0.5, label='y', color='deepskyblue') ax.legend(loc='upper right') ax.axvline(x=slide / 10, ymin=0, ymax=20) graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.image = photo canvas.create_image(640 * 1.3 / 2, 480 * 1.3 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() _backend_tk.blit(photo, figure_canvas_agg.get_renderer()._renderer, (0, 1, 2, 3)) #Do it all again for the ROC curve ax2.cla() ax2.plot(fpr, tpr, linewidth=3, color='deeppink') ax2.plot(fpr[slide], tpr[slide], '*', color='deepskyblue', markersize=20) ax2.set_xlabel("FPR") ax2.set_ylabel("TPR") graph2.draw() figure_x, figure_y, figure_w, figure_h = fig2.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas2, width=figure_w, height=figure_h) canvas2.image = photo canvas2.create_image(640 * 1.3 / 2, 480 * 1.3 / 2, image=photo) figure_canvas_agg2 = FigureCanvasAgg(fig2) figure_canvas_agg2.draw() _backend_tk.blit(photo, figure_canvas_agg2.get_renderer()._renderer, (0, 1, 2, 3)) ##and update the output values window['-OUTPUT_TPR-'].update(f'{tpr[slide]:.3f}') window['-OUTPUT_FPR-'].update(f'{fpr[slide]:.3f}') window['-OUTPUT_AUC-'].update(f'{auc:.3f}')
def main(): fig = Figure() ax = fig.add_subplot(111) ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.grid() layout = [[g.Text('Animated Matplotlib', size=(40, 1), justification='center', font='Helvetica 20')], [g.Canvas(size=(640, 480), key='canvas')], [g.ReadFormButton('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] # create the form and show it without the plot form = g.FlexForm('Demo Application - Embedding Matplotlib In PySimpleGUI') form.Layout(layout) form.ReadNonBlocking() canvas_elem = form.FindElement('canvas') graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) canvas = canvas_elem.TKCanvas dpts = [randint(0, 10) for x in range(10000)] for i in range(len(dpts)): button, values = form.ReadNonBlocking() if button is 'Exit' or values is None: exit(69) ax.cla() ax.grid() ax.plot(range(20), dpts[i:i + 20], color='purple') graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
def drawFigure(canvas, figure, loc=(0, 0)): ''' PARAMETERS: canvas: tkinter.Canvas object figure: matplotlib figure object loc: 2-tuple (default: (0, 0)) RETURN: tkagg image object ''' figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas_agg.draw() figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(loc[0] + figure_w / 2, loc[1] + figure_h / 2, image=photo) tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2) return photo
layout) window.Finalize( ) # needed to access the canvas element prior to reading the window canvas_elem = window['canvas'] graph = FigureCanvasTkAgg(fig, master=canvas_elem.TKCanvas) canvas = canvas_elem.TKCanvas dpts = [randint(0, 10) for x in range(10000)] # Our event loop for i in range(len(dpts)): event, values = window.read(timeout=20) if event == 'Exit' or event is None: exit(69) ax.cla() ax.grid() ax.plot(range(20), dpts[i:i + 20], color='purple') graph.draw() figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds figure_w, figure_h = int(figure_w), int(figure_h) photo = Tk.PhotoImage(master=canvas, width=figure_w, height=figure_h) canvas.create_image(640 / 2, 480 / 2, image=photo) figure_canvas_agg = FigureCanvasAgg(fig) figure_canvas_agg.draw() tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
class PlotWindow(plt.Figure): """ Tk window containing a matplotlib plot. In addition to the functions described below, also supports all functions contained in matplotlib's Axes_ and Figure_ objects. .. _Axes: http://matplotlib.sourceforge.net/api/axes_api.html .. _Figure: http://matplotlib.sourceforge.net/api/figure_api.html Args: title (str): The title to be used for the initial window. visible (bool): Whether to actually display a Tk window (set to `False` to create and save plots without displaying a window). standalone (bool, optional): If `True`, plot windows will be kept open by keeping the Tk event loop alive. """ _tk_started = False # If this is True, uses Toplevel to create the window, otherwise creates a main window def __init__(self, title="Plotting Window", visible=True): plt.Figure.__init__(self) self.add_subplot(111) self.visible = visible self._destroyed = False if self.visible: # If visible, use Tk's frontend # Use the correct method to create a window, then set the tk_started flag to True self.canvas = FigureCanvasTkAgg( self, Toplevel() if self.__class__._tk_started else Tk()) self.__class__._tk_started = True self.title(title) self.make_window() self.show() else: self.canvas = FigureCanvasAgg(self) def make_window(self): """ Pack the plot and matplotlib toolbar into the containing Tk window. This method is called during initialization and it is unlikely you will need to call it elsewhere. """ self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self.toolbar = NavigationToolbar2Tk(self.canvas, self.canvas._master) self.toolbar.update() self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) def destroy(self): """ Destroy the Tk window. Note that after calling this method (or manually closing the Tk window), this :py:class:`PlotWindow` cannot be used. """ try: # Try and destroy the window self.canvas._master.destroy() except: pass # It was probably already destroyed self._destroyed = True def clear(self): """ Clear the plot, keeping the Tk window active. """ self.clf() self.add_subplot(111) if self.visible: self.show() def show(self): """ Update the canvas image (automatically called for most functions). """ try: self.canvas.draw() except Exception: self.canvas.show() def __getattr__(self, name): show = True if name.startswith('_'): name = name[1:] show = False if hasattr(self.axes[0], name): attr = getattr(self.axes[0], name) if hasattr(attr, '__call__'): if show: def tmp(*args, **kwargs): out = attr(*args, **kwargs) if self.visible: self.show() return out return tmp else: return attr else: return attr else: raise AttributeError("PlotWindow object has no attribute %s" % name) def title(self, title): """ Change the title of the Tk window """ self.canvas._master.title(title) def legend(self, *args): """ Create a legend for the figure (requires plots to have been made with labels) """ handles, labels = self.axes[0].get_legend_handles_labels() self.axes[0].legend(handles, labels) if self.visible: self.show() def save(self, fname, **kwargs): """ Save this plot as an image. File type determined by extension of filename passed in. See documentation for savefig_. .. _savefig: http://matplotlib.sourceforge.net/api/figure_api.html Args: fname: The file to create, which may be a path or a file-like object. """ self.savefig(fname, **kwargs) def stay(self): """ Start the Tkinter window's main loop (e.g., to keep the plot open at the end of the execution of a script) """ self.canvas._master.mainloop() def plot(self, *args, **kwargs): """ Plot lines and/or markers to the Axes. See pyplot_ for more information. .. _pyplot: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot """ self.__getattr__('plot')(*args, **kwargs)
class AlchemyYahoo(object): def __init__(self, stock): self.apikey = "8490c1022cc805b491e2cf81b243c07e1606282c" self.stock = stock self.todaydate = datetime.datetime.now() self.todaydatetimestamp = int(time.time()) self.startdate = str( (self.todaydate - datetime.timedelta(days=10)).date()) self.startdatetimestamp = int( datetime.datetime.strptime(self.startdate, '%Y-%m-%d').strftime("%s")) self.result = [] self.articlecount = [] self.stockdates = [] self.positive = "positive" self.negative = "negative" self.articlerow = 6 self.articlecol = 1 self.cellx = 250 self.celly = 100 self.articledata = None self.companyname = None self.articledatathread = ArticleDataThread(self.AlchemyURL) self.articledatathread.start() self.price = None self.change = None self.volume = None self.articlekeywords = [] self.givestockinfothread = GiveStockInfoThread(self.givestockinfo) self.givestockinfothread.start() self.drawgraph() self.graph = None self.listofarticlekeywords() def getcompanyname(self): Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" + self.stock + """/chartdata;type=quote;range=1d/csv""") data = requests.get(Url).text info = data.splitlines() companyline = info[2] companynamelist = companyline.split(":") self.companyname = companynamelist[1] def listofarticlekeywords(self): while self.articledata == None: time.sleep(.001) if self.articledata == False: return for i in range(len(self.articledata)): self.articlekeywords.append(self.getkeywords(i)) def geturlandtitle(self, info, newlist=None): if newlist == None: newlist = [] if type(info) == str or type(info) == int: return newlist if type(info) == list: for dictionaries in info: self.geturlandtitle(dictionaries, newlist) else: for key, value in info.items(): if type(value) == dict: if key == "url": newlist.append(info[key]) else: self.geturlandtitle(info[key], newlist) else: self.geturlandtitle(info[key], newlist) self.articledata = newlist def chartdata(self): stockinfo = [] Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" + self.stock + "/chartdata;type=quote;range=2m/csv") data = requests.get(Url).text info = data.splitlines() highline = info[14].split(",") #self.high=highline[1] lowline = info[15].split(":") #self.low=lowline[1].split(",")[0] for line in data.splitlines(): eachline = [] for info in line.split(","): if line[0].isdigit(): eachline += [info] stockinfo += [eachline] return stockinfo def AlchemyURL(self): companynamethread = threading.Thread(target=self.getcompanyname, args=()) companynamethread.start() while self.companyname == None: time.sleep(.0001) keys = [] QueryURL = ( """https://access.alchemyapi.com/calls/data/GetNews?apikey=8490c1022cc805b491e2cf81b243c07e1606282c&return=enriched.url.title,enriched.url.url&start=""" + str(self.startdatetimestamp) + "&end=" + str(self.todaydatetimestamp) + """&q.enriched.url.entities.entity=|text=""" + self.stock + """,type=company|&q.enriched.url.docSentiment.type=positive&q.enriched.url.taxonomy.taxonomy_.label=technology%20and%20computing&count=6&outputMode=json""" ) r = requests.get(QueryURL).text string = json.dumps(r) convertedtopython = json.loads(r) if convertedtopython["status"] == 'OK': geturlandtitlethread = GetUrlAndTitleThread( self.geturlandtitle, convertedtopython) geturlandtitlethread.start() else: self.articledata = False def draw_figure(self, canvas, loc=(650, 140)): #Draw a matplotlib figure onto a Tk canvas #loc: location of top-left corner of figure on canvas in pixels. #Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py self.figure_canvas_agg = FigureCanvasAgg(self.figure) self.figure_canvas_agg.draw() self.figure_x, self.figure_y, self.figure_w, self.figure_h = ( self.figure.bbox.bounds) self.figure_w, self.figure_h = int(self.figure_w), int(self.figure_h) self.photo = PhotoImage(master=canvas, width=self.figure_w, height=self.figure_h) # Position: convert from top-left anchor to center anchor canvas.delete(self.graph) self.graph = canvas.create_image(loc[0] + self.figure_w / 2, loc[1] + self.figure_h / 2, image=self.photo) # Unfortunatly, there's no accessor for the pointer to the native renderer tkagg.blit(self.photo, self.figure_canvas_agg.get_renderer()._renderer, colormode=2) # Return a handle which contains a reference to the photo object # which must be kept live or else the picture disappears #return self.photo #Don't create the image, store the image and then add it def drawgraph(self): #Learnt how to use matoplotlib from youtube videos while self.companyname == None: time.sleep(0.001) self.stockinfo = self.chartdata() date = [] closeprice = [] highprice = [] lowprice = [] openprice = [] for line in self.stockinfo: date.append(datetime.datetime.strptime(line[0], "%Y%m%d")) closeprice.append((float((line[1])))) highprice.append((float(line[2]))) lowprice.append((float((line[3])))) openprice.append((float((line[4])))) # Create the figure we desire to add to an existing canvas fig = plt.figure(facecolor="white", figsize=(7, 6), dpi=90) graph = plt.subplot(1, 1, 1) graph.plot(date, highprice, '#008080', label="High Price") graph.plot(date, lowprice, label="Low Price", linestyle=":", linewidth=2) graph.plot(date, openprice, label="Open Price", linestyle="--") graph.plot(date, closeprice, label="Close Price", linestyle="-.", linewidth=2) plt.legend(loc=2, fontsize="x-small", fancybox=True, shadow=True, frameon=True, framealpha=None) graph.grid(True, which="major", axis="both", color="red") plt.xlabel("Date", color="green", fontsize=11) plt.ylabel("Price", color="green", fontsize=11) graph.spines["bottom"].set_color("purple") graph.spines["top"].set_color("purple") graph.spines["right"].set_color("purple") graph.spines["left"].set_color("purple") graph.tick_params(axis="y", colors="navy") graph.tick_params(axis="x", colors="navy") plt.title(self.companyname, color="purple") graph.xaxis.set_major_locator(mticker.MaxNLocator(6)) graph.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d")) labelsx = graph.get_xticklabels() plt.setp(labelsx, rotation=30, fontsize=11) labelsy = graph.get_yticklabels() plt.setp(labelsy, rotation=0, fontsize=11) self.low, self.high = graph.get_ylim() plt.tight_layout() self.figure = fig def drawinformation(self, canvas): self.drawarticle = [] if self.articledata != False and self.articledata != None: gap = 0 while len(self.articledata) < 6: self.articledata.append({ "title": "Could not find enough article\ s in recent times" }) for article in self.articledata: left = 400 top = 160 + (gap * self.celly) if article[ "title"] != "Could not find enough articles in recent \ times. There's not much information about the stock in \ the news": self.drawarticle.append( canvas.create_text(left, top, text=article["title"], anchor=NW, width=210, fill="medium blue", font="Helvetica 13 underline")) gap += 1 else: self.drawarticle.append( canvas.create_text(left, top, text=article["title"], anchor=NW, width=210, fill="orangered2", font="Helvetica 13 underline")) gap += 1 else: canvas.create_text(400, 160, text="""You've exhausted your daily limit. \n\n Sincerely, \n Smart Trading.""", fill="darkorchid4", anchor=NW) def givestockinfo(self): self.volume = 0 Url = ("http://chartapi.finance.yahoo.com/instrument/1.0/" + self.stock + """/chartdata;type=quote;range=1d/csv""") data = requests.get(Url).text info = data.splitlines() lineforlastclose = info[8].split(":") self.lastclose = lineforlastclose[1] lastprice = info[-1] mostrecent = lastprice.split(",") self.price = mostrecent[1] self.change = float(self.price) - float(self.lastclose) alldata = data.splitlines() stockdata = [] for line in alldata: databydate = [] for info in line.split(","): if line[0].isdigit(): databydate += [info] stockdata += [databydate] for dates in stockdata: self.volume += int(dates[5]) self.volume = self.volume def drawstockinfo(self, canvas, gap): self.displaystockinfo = [] while self.price == None: time.sleep(.0001) price = round(float(self.price), 2) change = round(self.change, 2) left = 205 top = 170 + (gap * self.celly) self.displaystockinfo.append( canvas.create_text(left, top, text=self.stock, width=210, fill="red2", font="Helvetica 15")) self.displaystockinfo.append( canvas.create_line(96, 195 + (gap * self.celly), 317, 195 + (gap * self.celly), fill="grey")) self.displaystockinfo.append( canvas.create_line(250, 200 + (gap * self.celly), 250, 240 + (gap * self.celly), fill="grey")) self.displaystockinfo.append( canvas.create_line(160, 200 + (gap * self.celly), 160, 240 + (gap * self.celly), fill="grey")) self.displaystockinfo.append( canvas.create_text(100, 200 + (gap * self.celly), text="Price", anchor=NW, fill="gray25")) self.displaystockinfo.append( canvas.create_text(100, 220 + (gap * self.celly), text=price, anchor=NW)) self.displaystockinfo.append( canvas.create_text(175, 200 + (gap * self.celly), text="Volume", anchor=NW, fill="gray25")) self.displaystockinfo.append( canvas.create_text(175, 220 + (gap * self.celly), text=self.volume, anchor=NW)) self.displaystockinfo.append( canvas.create_text(260, 200 + (gap * self.celly), text="Change", anchor=NW, fill="gray25")) if change != None: if change < 0: self.displaystockinfo.append( canvas.create_text(260, 220 + (gap * self.celly), text=change, anchor=NW, fill="red")) else: self.displaystockinfo.append( canvas.create_text(260, 220 + (gap * self.celly), text=change, anchor=NW, fill="green")) gap += 1 def drawcurrentstock(self, canvas): self.displaycurrentstock = [] while self.price == None: time.sleep(.0001) price = round(float(self.price), 2) change = round(self.change, 2) self.displaycurrentstock.append( canvas.create_rectangle(800, 50, 1100, 110, outline="purple", width=3)) self.displaycurrentstock.append( canvas.create_rectangle(800, 50, 1100, 110, outline="red", width=2)) self.displaycurrentstock.append( canvas.create_text(830, 70, text=self.stock, fill="purple")) self.displaycurrentstock.append( canvas.create_text(830, 90, text="+", fill="green3", font="Helvetica 17 bold")) self.displaycurrentstock.append( canvas.create_text(870, 60, text="Price", anchor=NW, fill="gray25")) self.displaycurrentstock.append( canvas.create_text(870, 85, text=price, anchor=NW)) self.displaycurrentstock.append( canvas.create_text(945, 60, text="Volume", anchor=NW, fill="gray25")) self.displaycurrentstock.append( canvas.create_text(945, 85, text=self.volume, anchor=NW)) self.displaycurrentstock.append( canvas.create_text(1025, 60, text="Change", anchor=NW, fill="gray25")) self.displaycurrentstock.append( canvas.create_line(860, 60, 860, 100, fill="grey")) self.displaycurrentstock.append( canvas.create_line(935, 60, 935, 100, fill="grey")) self.displaycurrentstock.append( canvas.create_line(1015, 60, 1015, 100, fill="grey")) if change != None: if change < 0: self.displaycurrentstock.append( canvas.create_text(1025, 85, text=change, anchor=NW, fill="red")) else: self.displaycurrentstock.append( canvas.create_text(1025, 85, text=change, anchor=NW, fill="green")) def drawgraphbox(self, canvas, x, y): differenceinpixels = 415 differenceinprice = abs(self.high - self.low) change = differenceinprice / differenceinpixels top = 175 ydifference = y - top difference = (change * ydifference) canvas.create_rectangle(x - 30, y - 30, x + 30, y - 10, fill="white", outline="darkorchid4", width=2) canvas.create_rectangle(x - 30, y - 30, x + 30, y - 10, outline="white", width=1) canvas.create_text(x, y - 20, text=abs(round(float(self.high) - difference, 2)), fill="darkorchid4") def getkeywords(self, number): keywords = set() if self.articledata == None or self.articledata == False: return articles = self.articledata dictionary = articles[number] url = dictionary["url"] QueryURL = ( "http://gateway-a.watsonplatform.net/calls/url/URLGetRankedKeywords?apikey=8490c1022cc805b491e2cf81b243c07e1606282c&url=" + url + "&outputMode=json") r = requests.get(QueryURL).text string = json.dumps(r) convertedtopython = json.loads(r) if convertedtopython['status'] == 'OK': for keyword in convertedtopython['keywords']: if len(keywords) < 15: keywords.add(keyword["text"].strip()) else: break else: if len(keywords) == 0: keywords.add("We're sorry but you've hit the transactions per \ day.\n\n Sincerely, Smart Trading.") return keywords def __eq__(self, other): return isinstance(other, AlchemyYahoo) and self.stock == other.stock
def confusion_matrix(cm, labels, normalize=False): """ Create confusion matrix image plot Parameters: cm : Confusion matrix labels : Axis labels (strings) Returns: data : Confusion matrix image buffer """ if normalize: cm = cm.astype('float') * 10.0 / cm.sum(axis=1)[:, np.newaxis] cm = np.nan_to_num(cm, copy=True) cm = cm.astype('int') np.set_printoptions(precision=2) fig = matfig.Figure(figsize=(5, 5), dpi=96, facecolor='w', edgecolor='k') canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(1, 1, 1) ax.imshow(cm, cmap='jet') strlabels = map(str, labels) classes = [ re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in strlabels ] classes = ['\n'.join(wrap(cl, 40)) for cl in classes] tick_marks = np.arange(len(classes)) FONTSIZE = 12 ax.set_xlabel('Predicted', fontsize=FONTSIZE) ax.set_xticks(tick_marks) rotation = 90 if len(max(classes, key=len)) > 2 else 0 ax.set_xticklabels(classes, fontsize=FONTSIZE, rotation=rotation, ha='center') ax.xaxis.set_label_position('bottom') ax.xaxis.tick_bottom() ax.set_ylabel('Actual', fontsize=FONTSIZE) ax.set_yticks(tick_marks) ax.set_yticklabels(classes, fontsize=FONTSIZE, va='center') ax.yaxis.set_label_position('left') ax.yaxis.tick_left() for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): ax.text(j, i, format(cm[i, j], 'd') if cm[i, j] != 0 else '.', horizontalalignment='center', fontsize=FONTSIZE, verticalalignment='center', color='white') fig.set_tight_layout(True) canvas.draw() data = np.fromstring(canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(canvas.get_width_height()[::-1] + (3, )) return data