python tushare Tkinter 가 구축 한 간단 한 주식 시각 화 조회 시스템(Beta v 0.13)

선언:
이번 에는 지난번 에 회사 정보 내용 과 주식 기본 면 지표 옵션 카드 를 새로 추 가 했 습 니 다.주식 기본 면 지표 옵션 카드 는 matplotlib 가 쓴 것 입 니 다.plt.subplot2grid()서브 맵 으로 쓴 것 입 니 다.메 인 그림 을 쓰 지 않 았 습 니 다.그 사이 에 제목 이 없 는 중국어 말 을 만 났 습 니 다.쓰 자마자 어 지 럽 히 고 인터넷 에서 많은 해결 방법 을 사 용 했 습 니 다.현재 도 풀 리 지 않 습 니 다.먼저 기록 하고 나중에 시간 이 있 으 면 해결 하 겠 습 니 다.만약 당신 에 게 해결 방법 이 있다 면 반드시 가르쳐 주 십시오.정말 이 문 제 는 저 에 게 하루 가 넘 게 걸 렸 습 니 다.만약 에 matplotlib 로 만 도형 을 출력 한다 면 어 지 러 운 문제 인터넷 의 많은 방법 도 해결 할 수 있 습 니 다.저도 도대체 제 가 쓴 코드 가 어디 에 중국어 와 충돌 하 는 지 잘 모 르 겠 습 니 다.한 시간 동안 코드 도 약간 어 지 러 워 지기 시 작 했 습 니 다.나중에 쓸 수록 어 지 러 워 질 것 입 니 다.한두 가지 기능 을 더 쓰 고 시간 을 내 서 코드 를 간결 하 게 하 세 요.업 데 이 트 된 코드 는 다음 과 같 습 니 다.

import pandas as pd
import tushare as ts
import mplfinance as mpf
import tkinter.tix as tix
from tkinter import ttk
import tkinter.font as tf
from tkinter.constants import *
import matplotlib.pyplot as plt
import matplotlib.dates as mdates  #   
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

pro = ts.pro_api('  tushare          token     ,                    ,  ')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# pd.set_option()  pycharm         
pd.set_option('expand_frame_repr', False) # True        。   False        
pd.set_option('display.max_columns', None) #      
# pd.set_option('display.max_rows', None) #      
pd.set_option('colheader_justify', 'centre') #     

root = tix.Tk() #      
screenWidth = root.winfo_screenwidth() #          
screenHeight = root.winfo_screenheight()
x, y = int(screenWidth / 4), int(screenHeight / 4) #           (x, y),         
width = int(screenWidth / 2) #                  
height = int(screenHeight / 2)
root.geometry('{}x{}+{}+{}'.format(width, height, x, y)) #             
root.title('Wilbur        ')
# root.resizable(0, 0) #        ,      ,       
root.iconbitmap('ZHY.ico') #          ,         icon               

#        
main_frame = tix.Frame(root, width=screenWidth, height=screenHeight,
            relief=tix.SUNKEN, bg='#353535', bd=5, borderwidth=4)
main_frame.pack(fill=BOTH, expand=0)

#                 
code_frame = tix.Frame(main_frame, borderwidth=1, bg='#353535')
code_frame.pack()
#     ‘    '
stock_label = tix.Label(code_frame, text='    ', bd=1)
stock_label.pack(side=LEFT)
#          
input_code_var = tix.StringVar()
code_widget = tix.Entry(code_frame, textvariable=input_code_var, borderwidth=1, justify=CENTER)
# input_code_get = input_code_var.set(input_code_var.get()) #        
code_widget.pack(side=LEFT, padx=4)

#                  
input_date_frame = tix.Frame(main_frame, borderwidth=1, bg='#353535')
input_date_frame.pack()
#     ‘    '
date_start_label = tix.Label(input_date_frame, text='    ', bd=1)
date_start_label.pack(side=LEFT)
#            
input_startdate_var = tix.StringVar()
startdate_widget = tix.Entry(input_date_frame, textvariable=input_startdate_var, borderwidth=1, justify=CENTER)
input_startdate_get = input_startdate_var.set(input_startdate_var.get()) #        
startdate_widget.pack(side=LEFT, padx=4)
#     ‘    '
date_end_label = tix.Label(input_date_frame, text='    ', bd=1)
date_end_label.pack(side=LEFT)
#            
input_enddate_var = tix.StringVar()
enddate_widget = tix.Entry(input_date_frame, textvariable=input_enddate_var, borderwidth=1, justify=CENTER)
input_enddate_get = input_enddate_var.set(input_enddate_var.get()) #        
enddate_widget.pack(side=LEFT, padx=4)


#                .sz .sh
def code_name_transform(get_stockcode): #                    
  str_stockcode = str(get_stockcode)
  str_stockcode = str_stockcode.strip() #         
  if 6 > len(str_stockcode) > 0:
    str_stockcode = str_stockcode.zfill(6) + '.SZ' # zfill()            ,       ,    0
  if len(str_stockcode) == 6:
    if str_stockcode[0:1] == '0':
      str_stockcode = str_stockcode + '.SZ'
    if str_stockcode[0:1] == '3':
      str_stockcode = str_stockcode + '.SZ'
    if str_stockcode[0:1] == '6':
      str_stockcode = str_stockcode + '.SH'
  return str_stockcode


tabControl = ttk.Notebook(root) #   Notebook
stock_graphics_daily = tix.Frame(root, borderwidth=1, bg='#353535', relief=tix.RAISED) #        K  
# stock_graphics_daily.pack(expand=1, fill=tk.BOTH, anchor=tk.CENTER)
stock_graphics_daily_basic = tix.Frame(root, borderwidth=1, bg='#353535', relief=tix.RAISED) #            
stock_graphics_week = tix.Frame(root, borderwidth=1, bg='#353535', relief=tix.RAISED)
stock_graphics_month = tix.Frame(root, borderwidth=1, bg='#353535', relief=tix.RAISED)
company_information = tix.Frame(root, borderwidth=1, bg='#353535', relief=tix.RAISED)

tabControl.add(stock_graphics_daily, text=' K  ') #       K      Notebook
tabControl.add(stock_graphics_daily_basic, text='     ')
tabControl.add(stock_graphics_week, text=' K  ')
tabControl.add(stock_graphics_month, text=' K  ')
tabControl.add(company_information, text='    ')
tabControl.pack(expand=1, fill="both") #        
tabControl.select(stock_graphics_daily) #      K    


#           
def go():
  #   stock_graphics_daily        ,winfo_children()            ,
  #                        ,         ,               
  for widget_daily in stock_graphics_daily.winfo_children():
    widget_daily.destroy()
  for widget_daily_basic in stock_graphics_daily_basic.winfo_children():
    widget_daily_basic.destroy()
  for widget_week in stock_graphics_week.winfo_children():
    widget_week.destroy()
  for widget_month in stock_graphics_month.winfo_children():
    widget_month.destroy()
  for widget_company_information in company_information.winfo_children():
    widget_company_information.destroy()

  stock_name = input_code_var.get()
  code_name = code_name_transform(stock_name)
  start_date = input_startdate_var.get()
  end_date = input_enddate_var.get()

  stock_data = pro.daily(ts_code=code_name, start_date=start_date, end_date=end_date)
  stock_daily_basic = pro.daily_basic(ts_code=code_name, start_date=start_date, end_date=end_date,
                    fields='close,trade_date,turnover_rate,volume_ratio,pe,pb')
  stock_week_data = pro.weekly(ts_code=code_name, start_date=start_date, end_date=end_date)
  stock_month_data = pro.monthly(ts_code=code_name, start_date=start_date, end_date=end_date)
  stock_name_change = pro.namechange(ts_code=code_name, fields='ts_code,name')
  stock_information = pro.stock_company(ts_code=code_name, fields='introduction,main_business,business_scope')

  #      
  data = stock_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']] # :      ,   date ,open    
  data = data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High', 'low': 'Low',
                'vol': 'Volume'}) #     ,          
  data.set_index('Date', inplace=True) #   date    ,      ,         object   ,       。
  #  object      DateIndex   ,pd.DatetimeIndex          ,              index。
  data.index = pd.DatetimeIndex(data.index)
  data = data.sort_index(ascending=True) #        ,      

  #          
  stock_daily_basic.set_index('trade_date', inplace=True) #   date    ,      ,         object   ,       。
  #  object      DateIndex   ,pd.DatetimeIndex          ,              index。
  stock_daily_basic.index = pd.DatetimeIndex(stock_daily_basic.index)
  stock_daily_basic = stock_daily_basic.sort_index(ascending=True) #        ,      
  print(stock_daily_basic)

  #      
  week_data = stock_week_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
  week_data = week_data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High',
                     'low': 'Low', 'vol': 'Volume'}) #     ,          
  week_data.set_index('Date', inplace=True) #   date    ,      ,         object   ,       。
  #  object      DateIndex   ,pd.DatetimeIndex          ,              index。
  week_data.index = pd.DatetimeIndex(week_data.index)
  week_data = week_data.sort_index(ascending=True) #        ,      

  #      
  month_data = stock_month_data.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
  month_data = month_data.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close', 'high': 'High',
                      'low': 'Low', 'vol': 'Volume'}) #     ,          
  month_data.set_index('Date', inplace=True) #   date    ,      ,         object   ,       。
  #  object      DateIndex   ,pd.DatetimeIndex          ,              index。
  month_data.index = pd.DatetimeIndex(month_data.index)
  month_data = month_data.sort_index(ascending=True) #        ,      

  #       
  stock_company_code = stock_name_change.at[0, 'ts_code']
  stock_company_name = stock_name_change.at[0, 'name']
  stock_introduction = stock_information.at[0, 'introduction']
  stock_main_business = stock_information.at[0, 'main_business']
  stock_business_scope = stock_information.at[0, 'business_scope']

  # K      
  daily_fig, axlist = mpf.plot(data, type='candle', mav=(5, 10, 20), volume=True,
                 show_nontrading=False, returnfig=True)
  #                     ,    matplotlib       ,          ,             month_fig   
  plt_stock_daily_basic = plt.figure(facecolor='white')
  plt.suptitle('Daily Basic Indicator', size=10)

  fig_close = plt.subplot2grid((3, 2), (0, 0), colspan=2) #        ,     3 ,    2 ,  (0,0),    2 
  fig_close.set_title('Close Price')
  plt.xticks(stock_daily_basic.index, rotation=45) #   x       ,               
  fig_close.plot(stock_daily_basic.index, stock_daily_basic['close'])
  plt.xlabel('Trade Day')
  plt.ylabel('Close')
  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # O xS   @   (  )
  plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1)) # O xS   g 

  fig_turnover_rate = plt.subplot2grid((3, 2), (1, 0)) #        ,     3 ,    2 ,  (1,0)
  fig_turnover_rate.set_title('Turnover Rate')
  plt.xticks(stock_daily_basic.index, rotation=45) #   x       ,               
  fig_turnover_rate.bar(stock_daily_basic.index, stock_daily_basic['turnover_rate'], facecolor='red')
  plt.xlabel('Trade Day')
  plt.ylabel('Turnover Rate')
  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # O xS   @   (  )
  plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # O xS   g 

  fig_volume_ratio = plt.subplot2grid((3, 2), (2, 0)) #        ,     3 ,    2 ,  (1,2)
  fig_volume_ratio.set_title('Volume Ratio')
  plt.xticks(stock_daily_basic.index, rotation=45) #   x       ,               
  fig_volume_ratio.bar(stock_daily_basic.index, stock_daily_basic['volume_ratio'])
  plt.xlabel('Trade Day')
  plt.ylabel('Volume Ratio')
  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m')) # O xS   @   (  )
  plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # O xS   g 

  fig_pe = plt.subplot2grid((3, 2), (1, 1)) #        ,     3 ,    2 ,    3 , 1 
  fig_pe.set_title('PE')
  plt.xticks(stock_daily_basic.index, rotation=45) #   x       ,               
  fig_pe.plot(stock_daily_basic.index, stock_daily_basic['pe'])
  plt.xlabel('Trade Day')
  plt.ylabel('PE')
  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m')) # O xS   @   (  )
  plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # O xS   g 

  fig_pb = plt.subplot2grid((3, 2), (2, 1)) #        ,     3 ,    2 ,    3 , 2 
  fig_pb.set_title('PB')
  plt.xticks(stock_daily_basic.index, rotation=45) #   x       ,               
  fig_pb.plot(stock_daily_basic.index, stock_daily_basic['pb'])
  plt.xlabel('Trade Day')
  plt.ylabel('PB')
  plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m')) # O xS   @   (  )
  plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # O xS   g 
  plt_stock_daily_basic.tight_layout(h_pad=-2, w_pad=0) #           

  week_fig, axlist = mpf.plot(week_data, type='candle', mav=(5, 10, 20), volume=True,
                show_nontrading=False, returnfig=True)
  month_fig, axlist = mpf.plot(month_data, type='candle', mav=(5, 10, 20), volume=True,
                 show_nontrading=False, returnfig=True)

  canvas_daily = FigureCanvasTkAgg(daily_fig, master=stock_graphics_daily) #   tkinter   
  canvas_daily.draw()
  toolbar_daily = NavigationToolbar2Tk(canvas_daily, stock_graphics_daily)
  toolbar_daily.update() #          
  canvas_daily._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)

  canvas_stock_daily_basic = FigureCanvasTkAgg(plt_stock_daily_basic, master=stock_graphics_daily_basic)
  canvas_stock_daily_basic.draw()
  toolbar_stock_daily_basic = NavigationToolbar2Tk(canvas_stock_daily_basic, stock_graphics_daily_basic)
  toolbar_stock_daily_basic.update() #          
  canvas_stock_daily_basic._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)
  plt.close()

  canvas_week = FigureCanvasTkAgg(week_fig, master=stock_graphics_week) #   tkinter   
  canvas_week.draw()
  toolbar_week = NavigationToolbar2Tk(canvas_week, stock_graphics_week)
  toolbar_week.update() #          
  canvas_week._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)

  canvas_month = FigureCanvasTkAgg(month_fig, master=stock_graphics_month) #   tkinter   
  canvas_month.draw()
  toolbar_month = NavigationToolbar2Tk(canvas_month, stock_graphics_month)
  toolbar_month.update() #          
  canvas_month._tkcanvas.pack(side=BOTTOM, fill=BOTH, expand=1)

  company_text = tix.Text(company_information, bg='white', undo=True, wrap=tix.CHAR)

  company_text.insert(tix.INSERT, stock_company_code)
  company_text.tag_add('tag1', '1.0', '1.9')
  company_text.tag_config('tag1', foreground='red', justify=CENTER)
  company_text.insert(tix.INSERT, '
') company_text.insert(tix.INSERT, stock_company_name) company_text.tag_add('tag2', '2.0', '2.9') company_text.tag_config('tag2', foreground='red', justify=CENTER) company_text.insert(tix.INSERT, '
') company_text.insert(tix.INSERT, ' ') company_text.insert(tix.INSERT, ' :') company_text.tag_add('tag3', '3.3', '3.9') company_text.tag_config('tag3', foreground='red', font=tf.Font(family='SimHei', size=12)) company_text.insert(tix.INSERT, stock_introduction) company_text.tag_add('tag4', '3.9', 'end') company_text.tag_config('tag4', foreground='black', spacing1=20, spacing2=10, font=tf.Font(family='SimHei', size=12)) company_text.insert(tix.INSERT, '
') company_text.insert(tix.INSERT, ' ') company_text.insert(tix.INSERT, ' :') company_text.tag_add('tag5', '4.4', '4.12') company_text.tag_config('tag5', foreground='blue') company_text.insert(tix.INSERT, stock_main_business) company_text.tag_add('tag6', '4.12', 'end') company_text.tag_config('tag6', spacing1=20, spacing2=10, font=tf.Font(family='SimHei', size=12)) company_text.insert(tix.INSERT, '
') company_text.insert(tix.INSERT, ' ') company_text.insert(tix.INSERT, ' :') company_text.tag_add('tag7', '5.4', '5.9') company_text.tag_config('tag7', foreground='#cc6600') company_text.insert(tix.INSERT, stock_business_scope) company_text.tag_add('tag8', '5.9', 'end') company_text.tag_config('tag8', spacing1=20, spacing2=10, font=tf.Font(family='SimHei', size=12)) company_text.insert(tix.INSERT, '
') company_text.pack(fill=BOTH, expand=1) # search_frame = tix.Frame(main_frame, borderwidth=1, bg='#353535', relief=tix.SUNKEN) search_frame.pack() # stock_find = tix.Button(search_frame, text=' ', width=5, height=1, command=go) stock_find.pack() root.mainloop()
효과 그림:
在这里插入图片描述
在这里插入图片描述
python tushare Tkinter 가 구축 한 간단 한 주식 시각 화 조회 시스템(Beta v 0.13)에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 python tushare 시각 화 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기