关于python:python可视化小程序实际利率与黄金价格走势图

4次阅读

共计 4504 个字符,预计需要花费 12 分钟才能阅读完成。

from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import *
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
import mpl_toolkits.axisartist as AA
from mpl_toolkits.axisartist.axislines import SubplotZero
import pylab
pylab.mpl.rcParams[‘font.sans-serif’] = [‘SimHei’] #显示中文
plt.rcParams[‘axes.unicode_minus’]=False #用于解决不能显示负号的问题
class Application(Frame):

def __init__(self,master=None):
    super().__init__(master)
    self.master = master
    self.pack() #应用 pack 布局管理器
    self.config(width=1100, height=500) #退出控件后批改此参数即可晓得含意
    self.creatWidget()
    #用于管制按钮应用程序,若某个 Flag 为 0,示意该 Button 操作未实现
    self.selectFileDGS10Flag = 0
    self.selectFileT10YIEFlag = 0
    self.selectFileXauFlag = 0
    self.SavePathFlag = 0
def creatWidget(self):
    #text,command,bg 参数与 place 办法里的 x,y 参数,见效果图即可
    #或者手动批改后查看异同
    #控件 - 图片示意图
    self.imageShow = Text(self,width=130,height=35)
    self.imageShow.place(x=15,y=25)
    #控件 - 上传文件按钮
    btnSelectFileDGS10 = Button(self,text="抉择 DGS10 文件",command=self.selectFileDGS10,bg="blue") 
    btnSelectFileDGS10.place(x=950,y=30)
    btnSelectFileT10YIE = Button(self, text="抉择 T10YIE 文件", command=self.selectFileT10YIE, bg="blue")
    btnSelectFileT10YIE.place(x=950, y=80)
    btnSelectFileXau = Button(self, text="抉择 Xau 文件", command=self.selectFileXau, bg="blue")
    btnSelectFileXau.place(x=959, y=130)
    #控件 - 设置存储地位按钮
    btnSavePath = Button(self, text="设置保留地位", command=self.SavePath, bg="green")
    btnSavePath.place(x=959, y=180)
    #控件 - 生成图片按钮
    btn = Button(self,text="生成图片", command=self.generateImage, bg="green")
    btn.place(x=969, y=230)
def generateImage(self):
    #若未实现上传文件,则弹出 Error 窗口
    #此处只有当三个 Flag 均为 1 时,才能够持续往下执行
    if(self.selectFileDGS10Flag == 0 or self.selectFileT10YIEFlag == 0  or self.selectFileXauFlag == 0):
        messagebox.showinfo("Error","请先上传文件")     
        return
    #若未设置图片存储门路,则弹出 Error 窗口
    if(self.SavePathFlag == 0):
        messagebox.showinfo("Error","请先设置保留门路")     
        return
    #pd.read_csv 读取文件,文件门路即为 askdirectory 函数读取后果
    #数据从 2019 年 7 月 19 日开始切片,前提应用 parse_dates=True 将工夫解析为工夫对象
    #na_values 将特定字符串辨认成 Nan
    #index_col 设置 df 索引
    self.dfDGS10 = pd.read_csv(self.pathDGS10, index_col="DATE", parse_dates=True, na_values=["."])["2019-7-19":]
    self.dfT10YIE = pd.read_csv(self.pathT10YIE, index_col="DATE", parse_dates=True, na_values=["."])["2019-7-19":]
    self.srAu = pd.read_csv(self.pathXau, header=None, names=["DATE", "open", "high", "low", "close", "v"],
                       parse_dates=True)["close"]["2019-7-19":]
    #从新结构一个 DataFrame
    #realRate 为实在利率,即名义利率 - 通货膨胀率
    self.realRate = pd.DataFrame({"realRate": (self.dfDGS10["DGS10"] - self.dfT10YIE["T10YIE"]), "DGS10": self.dfDGS10["DGS10"],
                             "T10YIE": self.dfT10YIE["T10YIE"], "au": self.srAu})
    #dropna-how:筛选形式 -‘any’,示意该行 / 列只有有一个以上的空值,就删除该行 / 列;‘all’,示意该行 / 列全副都为空值,就删除该行 / 列。realRate = self.realRate.dropna(how="any")
    fig, ax = plt.subplots(figsize=(100, 50))
    plt.title("理论利率与黄金价格走势图", fontsize=140)
    #设置左边的坐标轴
    ax2 = ax.twinx()
    ax2.tick_params(labelsize=100) #设置刻度大小
    ax2.yaxis.set_major_locator(ticker.MultipleLocator(50))# 设置黄金价格刻度距离
    ax2.set_ylabel("黄金价格 /$",size=120)# 设置 label 名称与大小
    #设置坐标轴
    ax.tick_params(labelsize=100)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(100))
    ax.set_ylabel("利率 /%",size=120)
    #画图 - 各参数具体含意参照效果图即可
    ax.plot(realRate.index, realRate["DGS10"], "-.g", label="美国十年期国债收益率 /%", linewidth=10)
    ax.plot(realRate.index, realRate["T10YIE"], "-.b", label="10-Year Breakeven Inflation Rate/%", linewidth=10)
    ax.plot(realRate.index, realRate["realRate"], "-.r", label="理论利率 /%", linewidth=20)
    #应用 ax 的 label 代替 ax2 的 label,[商品期货](https://www.gendan5.com/futures/cf.html) 或可将 ax2 的 legend 退出到 ax 的 legend 中
    ax.plot([], [], "-.y", label="黄金价格 /$", linewidth=20)
    ax2.plot(realRate.index, realRate["au"], "-.y", label="黄金价格", linewidth=20)
    #legeng 大小与地位,upper left 即为左上角
    ax.legend(fontsize=100,loc="upper left")
    #栅格 grid
    ax.grid(linestyle=":", color="b", linewidth=5)
    self.imagePathPng = self.SavePath + "/result.png"
    plt.savefig(self.imagePathPng,dpi=10,bbox_inches='tight')
    #将保留到指定门路的图片从新读取并插入到 Text 控件中
    self.photo = PhotoImage(file=self.imagePathPng)
    self.imageShow.image_create(1.0,image=self.photo)
#应用 askopenfilename 获取文件绝对路径
#应用 askdirectory 获取文件夹绝对路径
#当胜利实现读取操作后将 Flag 设置为 1
def selectFileDGS10(self):
    self.pathDGS10 = askopenfilename(title="上传文件")
    if len(self.pathDGS10) != 0:
        self.selectFileDGS10Flag = 1
def selectFileT10YIE(self):
    self.pathT10YIE = askopenfilename(title="上传文件")
    if len(self.pathT10YIE) != 0:
        self.selectFileT10YIEFlag = 1
def selectFileXau(self):
    self.pathXau = askopenfilename(title="上传文件")
    if len(self.pathXau) != 0:
        self.selectFileXauFlag = 1
def SavePath(self):
    self.SavePath = askdirectory(title="设置存储地位")
    if len(self.SavePath) != 0:
        self.SavePathFlag = 1

if name == ‘__main__’:

root = Tk()
root.title("理论利率与黄金价格走势图") #窗口名称
root.geometry("1100x500+200+50") #主窗口地位与大小 / 此处含意为宽度 1100,高度 500,+200 示意距右边屏幕间隔,+50 示意间隔上边屏幕间隔
root.resizable(0,0) #不可伸缩大小,集体习惯应用固定窗口大小,而后应用 pack 布局设置好相对地位
app = Application(master=root)
root.mainloop()  #进入事件循环 
正文完
 0