前言:
最近感覺代碼寫的越來越亂了,各種變數名稱跟函式讓我頭腦混亂,估計寫完這個后,我要花一些時間來整理鞏固下基礎知識了,寫完下面的這些臃腫代碼,暫停段時間理下思路,既然發現了自己的不足就應該去彌補,而不是視若無睹,
以下代碼比上一次添加了大盤指數指標的資訊展示,添加了大盤K線樣式屬性,其他的好像也沒什么改變了,代碼效果圖如下:
import pandas as pd
import tushare as ts
import mplfinance as mpf
import tkinter as tk
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 # 處理日期
import matplotlib as mpl # 用于設定曲線引數
from cycler import cycler # 用于定制線條顏色
import datetime
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 = tk.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_window = tk.PanedWindow(root) # 設定視窗管理,將主視窗分成左右兩部分
main_window.pack(fill='both', expand=1)
main_frame = tk.Frame(main_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN, bg='#353535', bd=5,
borderwidth=4)
main_window.pack(fill=BOTH, expand=1)
main_window.add(main_frame) # 將功能主框架添加到左邊視窗
# 創建圖形顯示主框架
graphic_main_frame = tk.Frame(main_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN, bg='#353535',
bd=5, borderwidth=4)
main_window.pack(fill=BOTH, expand=0)
main_window.add(graphic_main_frame) # 將查詢主框架添加到右邊視窗
def stockindex_function():
# 必須添加以下控制元件銷毀代碼,不然點擊一次按鈕框架長生一次,顯示的畫面會多一次,你可以將下面的代碼洗掉測驗看下
for widget_graphic_main_frame in graphic_main_frame.winfo_children():
widget_graphic_main_frame.destroy()
# 在右邊視窗的graphic_main_frame框架下再創建視窗
# opaqueresize該選項的值為 False,窗格的尺寸在用戶釋放滑鼠的時候才更新到新的位置
stockindex_information_window = tk.PanedWindow(graphic_main_frame, opaqueresize=False)
stockindex_information_window.pack(fill=BOTH, expand=1)
# 在company_information_window視窗下設定指數資訊顯示功能
stockindex_text = tk.Text(stockindex_information_window, bg='white', undo=True, wrap=tix.CHAR)
stockindex_information_window.add(stockindex_text, width=200)
# 首先獲取今天時間,然后先嘗試獲取今天的資料,然后今天回傳空值,則獲取昨天的資料顯示
now_time = datetime.datetime.now()
# 轉化成tushare的時間格式
strf_time = now_time.strftime('%Y%m%d')
shsz_index_dailybasic = pro.index_dailybasic(trade_date=strf_time, fields='ts_code,trade_date,total_mv, '
'float_mv,total_share,float_share,'
'free_share,turnover_rate,'
'turnover_rate_f,pe,pb')
sh_index_daily = pro.index_daily(ts_code='000001.SH', trade_date=strf_time)
sz_index_daily = pro.index_daily(ts_code='399001.SZ', trade_date=strf_time)
cy_index_daily = pro.index_daily(ts_code='399006.SZ', trade_date=strf_time)
zx_index_daily = pro.index_daily(ts_code='399005.SZ', trade_date=strf_time)
print(sh_index_daily)
if shsz_index_dailybasic.empty:
now_time = datetime.datetime.now() - datetime.timedelta(days=1)
strf_time = now_time.strftime('%Y%m%d')
shsz_index_dailybasic = pro.index_dailybasic(trade_date=strf_time, fields='ts_code,trade_date,total_mv, '
'float_mv,total_share,float_share,'
'free_share,turnover_rate,'
'turnover_rate_f,pe,pb')
sh_index_daily = pro.index_daily(ts_code='000001.SH', trade_date=strf_time)
sz_index_daily = pro.index_daily(ts_code='399001.SZ', trade_date=strf_time)
cy_index_daily = pro.index_daily(ts_code='399006.SZ', trade_date=strf_time)
zx_index_daily = pro.index_daily(ts_code='399005.SZ', trade_date=strf_time)
print(sh_index_daily)
# 資料處理,將ts_code作為索引,方便準確呼叫資料,保留兩位小數
shsz_index_dailybasic.set_index('ts_code', inplace=True)
# 資料獲取
sh_total_mv = round(shsz_index_dailybasic.at['000001.SH', 'total_mv']/100000000, 2) # 元轉換成億單位
sh_float_mv = round(shsz_index_dailybasic.at['000001.SH', 'float_mv']/100000000, 2)
sh_total_share = round(shsz_index_dailybasic.at['000001.SH', 'total_share']/10000000000, 2) # 股轉化成億手
sh_float_share = round(shsz_index_dailybasic.at['000001.SH', 'float_share']/10000000000, 2)
sh_free_share = round(shsz_index_dailybasic.at['000001.SH', 'free_share']//10000000000, 2)
sh_turnover_rate = shsz_index_dailybasic.at['000001.SH', 'turnover_rate']
sh_pe = shsz_index_dailybasic.at['000001.SH', 'pe']
sh_pb = shsz_index_dailybasic.at['000001.SH', 'pb']
sh_close = sh_index_daily.at[0, 'close']
sh_pre_close = sh_index_daily.at[0, 'pre_close']
sh_pct_chg = sh_index_daily.at[0, 'pct_chg']
sh_vol = round(sh_index_daily.at[0, 'vol']/100000000, 2) # 手轉化成億手
sh_amount = round(sh_index_daily.at[0, 'amount']/100000, 2) # 千元轉換成億元
# 資料呼叫
# 在文本框第一行添加股票代碼,文字紅色,居中顯示
stockindex_text.insert(tk.INSERT, '上證指數')
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總市值(億):')
stockindex_text.insert(tk.INSERT, sh_total_mv)
stockindex_text.tag_add('tag1', '1.0', '1.9') # 設定選定的內容
stockindex_text.tag_config('tag1', foreground='red', justify=CENTER)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通市值(億):')
stockindex_text.insert(tk.INSERT, sh_float_mv)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總股本(億手):')
stockindex_text.insert(tk.INSERT, sh_total_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通股本(億手):')
stockindex_text.insert(tk.INSERT, sh_float_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '自由流通股本(億手):')
stockindex_text.insert(tk.INSERT, sh_free_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '換手率:')
stockindex_text.insert(tk.INSERT, sh_turnover_rate)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市盈率:')
stockindex_text.insert(tk.INSERT, sh_pe)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市凈率:')
stockindex_text.insert(tk.INSERT, sh_pb)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '收盤點位:')
stockindex_text.insert(tk.INSERT, sh_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '昨日收盤點:')
stockindex_text.insert(tk.INSERT, sh_pre_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '漲跌幅(%):')
stockindex_text.insert(tk.INSERT, sh_pct_chg)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交量(億手):')
stockindex_text.insert(tk.INSERT, sh_vol)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交額(億):')
stockindex_text.insert(tk.INSERT, sh_amount)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.tag_add('content1', '2.0', 'end') # 設定選定的內容
stockindex_text.tag_config('content1', foreground='blue')
sz_total_mv = round(shsz_index_dailybasic.at['399001.SZ', 'total_mv'] / 100000000, 2) # 轉換成億單位
sz_float_mv = round(shsz_index_dailybasic.at['399001.SZ', 'float_mv'] / 100000000, 2)
sz_total_share = round(shsz_index_dailybasic.at['399001.SZ', 'total_share'] / 10000000000, 2) # 轉化成億手
sz_float_share = round(shsz_index_dailybasic.at['399001.SZ', 'float_share'] / 10000000000, 2)
sz_free_share = round(shsz_index_dailybasic.at['399001.SZ', 'free_share'] // 10000000000, 2)
sz_turnover_rate = shsz_index_dailybasic.at['399001.SZ', 'turnover_rate']
sz_pe = shsz_index_dailybasic.at['399001.SZ', 'pe']
sz_pb = shsz_index_dailybasic.at['399001.SZ', 'pb']
sz_close = sz_index_daily.at[0, 'close']
sz_pre_close = sz_index_daily.at[0, 'pre_close']
sz_pct_chg = sz_index_daily.at[0, 'pct_chg']
sz_vol = round(sz_index_daily.at[0, 'vol']/100000000, 2) # 手轉化成億手
sz_amount = round(sz_index_daily.at[0, 'amount']/100000, 2) # 千元轉換成億元
stockindex_text.insert(tk.INSERT, '深證指數')
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總市值(億):')
stockindex_text.insert(tk.INSERT, sz_total_mv)
stockindex_text.tag_add('tag2', '15.0', '15.9') # 設定選定的內容,
stockindex_text.tag_config('tag2', foreground='red', justify=CENTER)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通市值(億):')
stockindex_text.insert(tk.INSERT, sz_float_mv)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總股本(億手):')
stockindex_text.insert(tk.INSERT, sz_total_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通股本(億手):')
stockindex_text.insert(tk.INSERT, sz_float_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '自由流通股本(億手):')
stockindex_text.insert(tk.INSERT, sz_free_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '換手率:')
stockindex_text.insert(tk.INSERT, sz_turnover_rate)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市盈率:')
stockindex_text.insert(tk.INSERT, sz_pe)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市凈率:')
stockindex_text.insert(tk.INSERT, sz_pb)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '收盤點位:')
stockindex_text.insert(tk.INSERT, sz_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '昨日收盤點:')
stockindex_text.insert(tk.INSERT, sz_pre_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '漲跌幅(%):')
stockindex_text.insert(tk.INSERT, sz_pct_chg)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交量(億手):')
stockindex_text.insert(tk.INSERT, sz_vol)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交額(億):')
stockindex_text.insert(tk.INSERT, sz_amount)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.tag_add('content2', '16.0', 'end') # 設定選定的內容
stockindex_text.tag_config('content2', foreground='DarkViolet')
cy_total_mv = round(shsz_index_dailybasic.at['399006.SZ', 'total_mv'] / 100000000, 2) # 轉換成億單位
cy_float_mv = round(shsz_index_dailybasic.at['399006.SZ', 'float_mv'] / 100000000, 2)
cy_total_share = round(shsz_index_dailybasic.at['399006.SZ', 'total_share'] / 10000000000, 2) # 轉化成億手
cy_float_share = round(shsz_index_dailybasic.at['399006.SZ', 'float_share'] / 10000000000, 2)
cy_free_share = round(shsz_index_dailybasic.at['399006.SZ', 'free_share'] // 10000000000, 2)
cy_turnover_rate = shsz_index_dailybasic.at['399006.SZ', 'turnover_rate']
cy_pe = shsz_index_dailybasic.at['399006.SZ', 'pe']
cy_pb = shsz_index_dailybasic.at['399006.SZ', 'pb']
cy_close = sh_index_daily.at[0, 'close']
cy_pre_close = cy_index_daily.at[0, 'pre_close']
cy_pct_chg = cy_index_daily.at[0, 'pct_chg']
cy_vol = round(cy_index_daily.at[0, 'vol']/100000000, 2) # 手轉化成億手
cy_amount = round(cy_index_daily.at[0, 'amount']/100000, 2) # 千元轉換成億元
stockindex_text.insert(tk.INSERT, '創業板指數')
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總市值(億):')
stockindex_text.insert(tk.INSERT, cy_total_mv)
stockindex_text.tag_add('tag3', '29.0', '29.9') # 設定選定的內容,
stockindex_text.tag_config('tag3', foreground='red', justify=CENTER)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通市值(億):')
stockindex_text.insert(tk.INSERT, cy_float_mv)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總股本(億手):')
stockindex_text.insert(tk.INSERT, cy_total_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通股本(億手):')
stockindex_text.insert(tk.INSERT, cy_float_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '自由流通股本(億手):')
stockindex_text.insert(tk.INSERT, cy_free_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '換手率:')
stockindex_text.insert(tk.INSERT, cy_turnover_rate)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市盈率:')
stockindex_text.insert(tk.INSERT, cy_pe)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市凈率:')
stockindex_text.insert(tk.INSERT, cy_pb)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '收盤點位:')
stockindex_text.insert(tk.INSERT, cy_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '昨日收盤點:')
stockindex_text.insert(tk.INSERT, cy_pre_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '漲跌幅(%):')
stockindex_text.insert(tk.INSERT, cy_pct_chg)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交量(億手):')
stockindex_text.insert(tk.INSERT, cy_vol)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交額(億):')
stockindex_text.insert(tk.INSERT, cy_amount)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.tag_add('content3', '30.0', 'end') # 設定選定的內容
stockindex_text.tag_config('content3', foreground='DarkCyan')
zx_total_mv = round(shsz_index_dailybasic.at['399005.SZ', 'total_mv'] / 100000000, 2) # 轉換成億單位
zx_float_mv = round(shsz_index_dailybasic.at['399005.SZ', 'float_mv'] / 100000000, 2)
zx_total_share = round(shsz_index_dailybasic.at['399005.SZ', 'total_share'] / 10000000000, 2) # 轉化成億手
zx_float_share = round(shsz_index_dailybasic.at['399005.SZ', 'float_share'] / 10000000000, 2)
zx_free_share = round(shsz_index_dailybasic.at['399005.SZ', 'free_share'] // 10000000000, 2)
zx_turnover_rate = shsz_index_dailybasic.at['399005.SZ', 'turnover_rate']
zx_pe = shsz_index_dailybasic.at['399005.SZ', 'pe']
zx_pb = shsz_index_dailybasic.at['399005.SZ', 'pb']
zx_close = zx_index_daily.at[0, 'close']
zx_pre_close = zx_index_daily.at[0, 'pre_close']
zx_pct_chg = zx_index_daily.at[0, 'pct_chg']
zx_vol = round(zx_index_daily.at[0, 'vol']/100000000, 2) # 手轉化成億手
zx_amount = round(zx_index_daily.at[0, 'amount']/100000, 2) # 千元轉換成億元
stockindex_text.insert(tk.INSERT, '中小板指數')
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總市值(億):')
stockindex_text.insert(tk.INSERT, zx_total_mv)
stockindex_text.tag_add('tag4', '43.0', '43.9') # 設定選定的內容,
stockindex_text.tag_config('tag4', foreground='red', justify=CENTER)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通市值(億):')
stockindex_text.insert(tk.INSERT, zx_float_mv)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '總股本(億手):')
stockindex_text.insert(tk.INSERT, zx_total_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '流通股本(億手):')
stockindex_text.insert(tk.INSERT, zx_float_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '自由流通股本(億手):')
stockindex_text.insert(tk.INSERT, zx_free_share)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '換手率:')
stockindex_text.insert(tk.INSERT, zx_turnover_rate)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市盈率:')
stockindex_text.insert(tk.INSERT, zx_pe)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '市凈率:')
stockindex_text.insert(tk.INSERT, zx_pb)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '收盤點位:')
stockindex_text.insert(tk.INSERT, zx_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '昨日收盤點:')
stockindex_text.insert(tk.INSERT, zx_pre_close)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '漲跌幅(%):')
stockindex_text.insert(tk.INSERT, zx_pct_chg)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交量(億手):')
stockindex_text.insert(tk.INSERT, zx_vol)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '成交額(億):')
stockindex_text.insert(tk.INSERT, zx_amount)
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.tag_add('content4', '44.0', 'end') # 設定選定的內容
stockindex_text.tag_config('content4', foreground='Sienna')
stockindex_text.insert(tk.INSERT, '\n')
stockindex_text.insert(tk.INSERT, '資料交易日:')
stockindex_text.insert(tk.INSERT, strf_time)
stockindex_text.tag_add('content5', '58.0', 'end') # 設定選定的內容
stockindex_text.tag_config('content5', foreground='Crimson')
stockindex_window = tk.PanedWindow(orient='vertical', opaqueresize=False)
stockindex_information_window.add(stockindex_window)
stockindex_sh_frame = tk.Frame(stockindex_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN,
bg='#353535', bd=5, borderwidth=4)
stockindex_sh_frame.pack(fill=BOTH)
stockindex_window.add(stockindex_sh_frame, height=screenHeight/2)
stockindex_sz_frame = tk.Frame(stockindex_window, width=screenWidth, height=screenHeight, relief=tk.SUNKEN,
bg='#353535', bd=5, borderwidth=4)
stockindex_sz_frame.pack(fill=BOTH)
stockindex_window.add(stockindex_sz_frame)
for widget_stockindex_sh_frame in stockindex_sh_frame.winfo_children():
widget_stockindex_sh_frame.destroy()
for widget_stockindex_sz_frame in stockindex_sz_frame.winfo_children():
widget_stockindex_sz_frame.destroy()
for widget_stockindex_text in stockindex_text.winfo_children():
widget_stockindex_text.destroy()
# 上證指數
index_data_sh = pro.index_daily(ts_code='000001.SH', start_date=20100101)
# 日資料處理
# :取所有行資料,后面取date列,open列等資料
index_data_sh = index_data_sh.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
index_data_sh = index_data_sh.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close',
'high': 'High', 'low': 'Low', 'vol': 'Volume'}) # 更換列名,為后面函式變數做準備
index_data_sh.set_index('Date', inplace=True) # 設定date列為索引,覆寫原來索引,這個時候索引還是 object 型別,就是字串型別,
# 將object型別轉化成 DateIndex 型別,pd.DatetimeIndex 是把某一列進行轉換,同時把該列的資料設定為索引 index,
index_data_sh.index = pd.DatetimeIndex(index_data_sh.index)
index_data_sh = index_data_sh.sort_index(ascending=True) # 將時間順序升序,符合時間序列
# print(index_data_sh)
# 設定marketcolors,up:設定K線線柱顏色,up意為收盤價大于等于開盤價,down:與up相反,這樣設定與國內K線顏色標準相符
# edge:K線線柱邊緣顏色(i代表繼承自up和down的顏色),wick:燈芯(上下影線)顏色,volume:成交量直方圖的顏色,inherit:是否繼承,選填
sh_mc = mpf.make_marketcolors(up='red', down='green', edge='i', wick='i', volume='in', inherit=True)
# 設定圖形風格,gridaxis:設定網格線位置,gridstyle:設定網格線線型,y_on_right:設定y軸位置是否在右
sh_s = mpf.make_mpf_style(gridaxis='both', gridstyle='-.', y_on_right=False, marketcolors=sh_mc)
# 設定線寬
mpl.rcParams['lines.linewidth'] = .5
# 設定均線顏色,這里可以設定6條均線的顏色
mpl.rcParams['axes.prop_cycle'] = cycler(color=['dodgerblue', 'deeppink', 'navy', 'teal', 'maroon', 'darkorange'])
index_sh_fig, axlist = mpf.plot(index_data_sh, type='candle', mav=(5, 10, 20), volume=True,
show_nontrading=False, returnfig=True, style=sh_s)
canvas_index_sh = FigureCanvasTkAgg(index_sh_fig, master=stockindex_sh_frame) # 設定tkinter繪制區
canvas_index_sh.draw()
toolbar_index_sh = NavigationToolbar2Tk(canvas_index_sh, stockindex_sh_frame)
toolbar_index_sh.update() # 顯示圖形導航工具條
canvas_index_sh._tkcanvas.pack(fill=BOTH, expand=1)
# 深圳指數
index_data_sz = pro.index_daily(ts_code='399001.SZ', start_date=20100101)
# 日資料處理
# :取所有行資料,后面取date列,open列等資料
index_data_sz = index_data_sz.loc[:, ['trade_date', 'open', 'close', 'high', 'low', 'vol']]
index_data_sz = index_data_sz.rename(columns={'trade_date': 'Date', 'open': 'Open', 'close': 'Close',
'high': 'High', 'low': 'Low', 'vol': 'Volume'}) # 更換列名,為后面函式變數做準備
index_data_sz.set_index('Date', inplace=True) # 設定date列為索引,覆寫原來索引,這個時候索引還是 object 型別,就是字串型別,
# 將object型別轉化成 DateIndex 型別,pd.DatetimeIndex 是把某一列進行轉換,同時把該列的資料設定為索引 index,
index_data_sz.index = pd.DatetimeIndex(index_data_sh.index)
index_data_sz = index_data_sz.sort_index(ascending=True) # 將時間順序升序,符合時間序列
# print(index_data_sz)
index_sz_fig, axlist = mpf.plot(index_data_sz, type='candle', mav=(5, 10, 20), volume=True,
show_nontrading=False, returnfig=True)
canvas_index_sz = FigureCanvasTkAgg(index_sz_fig, master=stockindex_sz_frame) # 設定tkinter繪制區
canvas_index_sz.draw()
toolbar_index_sz = NavigationToolbar2Tk(canvas_index_sz, stockindex_sz_frame)
toolbar_index_sz.update() # 顯示圖形導航工具條
canvas_index_sz._tkcanvas.pack(fill=BOTH, expand=1)
def stock_query_function():
# 必須添加以下控制元件銷毀代碼,不然點擊一次按鈕框架長生一次,顯示的畫面會多一次,你可以將下面的代碼洗掉測驗看下
for widget_graphic_main_frame in graphic_main_frame.winfo_children():
widget_graphic_main_frame.destroy()
# 在主框架下創建股票代碼輸入子框架
code_frame = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535')
code_frame.pack()
# 創建標簽‘股票代碼’
stock_label = tk.Label(code_frame, text='股票代碼', bd=1)
stock_label.pack(side=LEFT)
# 創建股票代碼輸入框
input_code_var = tk.StringVar()
code_widget = tk.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 = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535')
input_date_frame.pack()
# 創建標簽‘開始日期’
date_start_label = tk.Label(input_date_frame, text='開始日期', bd=1)
date_start_label.pack(side=LEFT)
# 創建開始日期代碼輸入框
input_startdate_var = tk.StringVar()
startdate_widget = tk.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 = tk.Label(input_date_frame, text='結束日期', bd=1)
date_end_label.pack(side=LEFT)
# 創建結束日期代碼輸入框
input_enddate_var = tk.StringVar()
enddate_widget = tk.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)
# 創建Notebook標簽選項卡
tabControl = ttk.Notebook(graphic_main_frame)
stock_graphics_daily = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED) # 增加新選項卡日K線圖
# stock_graphics_daily.pack(expand=1, fill=tk.BOTH, anchor=tk.CENTER)
stock_graphics_daily_basic = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED) # 增加新選項卡基本面指標
stock_graphics_week = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)
stock_graphics_month = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.RAISED)
company_information = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tk.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(): # 圖形輸出渲染
# 以下函式作用是省略輸入代碼后綴.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
# 清除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')) # 設定X軸主刻度顯示的格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1)) # 設定X軸主刻度的間距
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')) # 設定X軸主刻度顯示的格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # 設定X軸主刻度的間距
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')) # 設定X軸主刻度顯示的格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # 設定X軸主刻度的間距
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')) # 設定X軸主刻度顯示的格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # 設定X軸主刻度的間距
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')) # 設定X軸主刻度顯示的格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2)) # 設定X軸主刻度的間距
plt_stock_daily_basic.tight_layout(h_pad=-2, w_pad=0) # 解決子圖圖形重疊問題
# 周K線圖形輸出
week_fig, axlist = mpf.plot(week_data, type='candle', mav=(5, 10, 20), volume=True,
show_nontrading=False, returnfig=True)
# 月k線圖形輸出
month_fig, axlist = mpf.plot(month_data, type='candle', mav=(5, 10, 20), volume=True,
show_nontrading=False, returnfig=True)
# 將獲得的圖形渲染到畫布上
# 日K線圖形渲染到tkinter畫布上
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)
# 基本面指標圖形渲染到tkinter畫布上
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()
# 周K線圖形渲染到tkinter畫布上
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)
# 月K線圖形渲染到tkinter畫布上
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_information框架下設定文字選項卡功能內容
company_text = tk.Text(company_information, bg='white', undo=True, wrap=tix.CHAR)
# 在文本框第一行添加股票代碼,文字紅色,居中顯示
company_text.insert(tk.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(tk.INSERT, '\n')
company_text.insert(tk.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(tk.INSERT, '\n')
company_text.insert(tk.INSERT, ' ')
company_text.insert(tk.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(tk.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(tk.INSERT, '\n')
company_text.insert(tk.INSERT, ' ')
company_text.insert(tk.INSERT, '主要業務及產品:')
company_text.tag_add('tag5', '4.4', '4.12')
company_text.tag_config('tag5', foreground='blue')
company_text.insert(tk.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(tk.INSERT, '\n')
company_text.insert(tk.INSERT, ' ')
company_text.insert(tk.INSERT, '經營范圍:')
company_text.tag_add('tag7', '5.4', '5.9')
company_text.tag_config('tag7', foreground='#cc6600')
company_text.insert(tk.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(tk.INSERT, '\n')
company_text.pack(fill=BOTH, expand=1)
# 在主框架下創建查詢按鈕子框架
search_frame = tk.Frame(graphic_main_frame, borderwidth=1, bg='#353535', relief=tix.SUNKEN)
search_frame.pack(before=tabControl) # 必須加上before,否則控制元件則會出現在底部,除非tabControl設定了bottom布局屬性
# 創建查詢按鈕并設定功能
stock_find = tk.Button(search_frame, text='查詢', width=5, height=1, command=go)
stock_find.pack()
stockIndex_label_button = tk.Button(main_frame, text='全景指數', command=stockindex_function)
stockIndex_label_button.pack(fill=X)
query_label_button = tk.Button(main_frame, text='查詢', command=stock_query_function)
query_label_button.pack(fill=X)
root.mainloop()


tushare注冊鏈接:LINK
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/191897.html
標籤:其他
上一篇:八數碼寬度優先極簡版
