2017-05-14 280 views
1

我正在做一些簡單的繪製圖表的應用程序。我從雅虎財經獲得股票數據,我無法管理股票的「動態」選擇。 我敢肯定,我的「generateChard」功能工作正常,因爲如果我擺脫應用程序的運行過程中選擇股票,在編譯之前設定的股票名稱 - 它工作正常使用matplotlib和tkinter的動態繪圖圖表

import matplotlib 

matplotlib.use("TkAgg") 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg 
from matplotlib.figure import Figure 
import matplotlib.animation as animation 
import matplotlib.pyplot as plt 
from matplotlib import style 
import matplotlib.dates as mdates 

import tkinter as tk 
from tkinter import * 

import urllib 
import json 

import pandas as pd 
import numpy as np 

style.use("dark_background") 

LARGE_FONT = ("Verdana", 12) 

f = Figure(figsize=(5, 5), dpi=100) 
graph = f.add_subplot(111) 


def bytespdate2num(fmt, encoding='utf-8'): 
    strconverter = mdates.strpdate2num(fmt) 

    def bytesconverter(b): 
     s = b.decode(encoding) 
     return strconverter(s) 

    return bytesconverter 


def generateChart(stock): 
    graph.clear() 
    stockPriceUrl = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=6m/csv' 

    sourceCode = urllib.request.urlopen(stockPriceUrl).read().decode() 

    stockData = [] 
    splitSource = sourceCode.split('\n') 

    for line in splitSource: 
     splitLine = line.split(',') 
     if len(splitLine) == 6: 
      if 'values' not in line and 'labels' not in line: 
       stockData.append(line) 

    date, closePrice, highPrice, lowPrice, openPrice, volume = np.loadtxt(stockData, delimiter=',', unpack=True, 
                      converters={0: bytespdate2num('%Y%m%d')}) 
    graph.plot_date(date, closePrice, '') 


class StockAnalyser(tk.Tk): 
    def __init__(self, *args, **kwargs): 
     tk.Tk.__init__(self, *args, **kwargs) 
     container = tk.Frame(self) 

     tk.Tk.wm_title(self, "Stock Analyser") 
     tk.Tk.minsize(self, width=350, height=200) 

     container.pack(side="top", fill="both", expand=True) 

     container.grid_rowconfigure(0, weight=1) 
     container.grid_columnconfigure(0, weight=1) 

     self.frames = {} 

     for F in (StartPage, StartPage2): 
      frame = F(container, self) 
      self.frames[F] = frame 
      frame.grid(row=0, column=0, sticky="nsew") 

     self.show_frame(StartPage) 

    def show_frame(self, cont): 
     frame = self.frames[cont] 
     frame.tkraise() 


class StartPage(tk.Frame): 
    def __init__(self, parent, controller): 
     tk.Frame.__init__(self, parent) 
     label = tk.Label(self, text="Pick graph stock exchange", font="LARGE_FONT") 
     label.pack(pady=10, padx=10) 

     stockEntry = tk.Entry(self) 
     stockEntry.pack() 

     button = tk.Button(self, text="next", 
          command=lambda: prepChart()) 
     button.pack() 

     def prepChart(): 
      generateChart(stockEntry.get()) 
      controller.show_frame(StartPage2) 


class StartPage2(tk.Frame): 
    def __init__(self, parent, controller): 
     tk.Frame.__init__(self, parent) 
     label = tk.Label(self, text="Graph page", font="LARGE_FONT") 
     label.pack(pady=10, padx=10) 

     button = tk.Button(self, text="back to home page", 
          command=lambda: controller.show_frame(StartPage)) 
     button.pack() 

     canvas = FigureCanvasTkAgg(f, self) 
     canvas.show() 

     toolbar = NavigationToolbar2TkAgg(canvas, self) 
     canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) 
     canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) 
     toolbar.update() 


app = StockAnalyser() 
app.mainloop() 
+0

http://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib/4098938#4098938 –

+0

謝謝!我設法解決這個問題,添加'動畫'功能和標誌,決定是否應該執行動畫。也許這不是最好的選擇,但與國旗完美的作品:) – ares1337

回答

0

我設法解決這個問題,通過添加動畫功能。我創建全局標誌 - boolStartRefresingData,並設置股票名稱也全球化,所以我可以做這樣的事情:

def animate(self): 
    if boolStartRefreshingData==True: 
     generateChart() 

ani = animation.FuncAnimation(figure,animate,10) 

我變更標識值爲true,單擊該按鈕時,然後我改成了假的函數的結尾繪製圖