Let's make a GUI with python.

Introduction

Thanks. I will post an article for the first time in a long time. This is Wamaro. Due to recent circumstances, I am hiding scraping. In the old days, I heard scraping and asked, "What? What is it? I was thinking, but now I have a strong feeling that I have to scrape. I really feel that people's ideas change depending on their position and the times. By the way, with that in mind, I've been working on a program that I've completely rid of. Even now, I am writing without being blamed by anyone for encapsulation or learning the code. The program is said to be a tool. So there is no point in writing without a purpose. You don't even have to learn. Therefore, the madman forcibly creates a purpose. That's the reason. So, this time, I would like to make a GUI using python. Specifically, after entering the company code and the specified period, I would like to write the code of the application (which is ridiculous) that displays the transition of the stock price during that period.

environment

The environment is shown below. ・ Windows10 ・ Python3 (anaconda) Development was mainly done in jupyter-lab.

Outline of the contents of the code

I will briefly explain the contents of the code. If you just want the results, you can refer to the final "final code".

Required library

The library used this time is shown below.


from pandas_datareader import data
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
%matplotlib inline

The main feeling is as follows. ・ Pandas: For data processing -Matplotlib: For graph display (% matplotlib inline is used when displaying graphs in jupyter system.) ・ Numpy: For calculation -Tkinter: For GUI creation. (There are many types, but tkinter is included in anaconda by default, so it is easy to use.)

I am using an orthodox library like this.

Function definition

I have defined some functions this time. There are two main. ・ Function to acquire stock price data -A function that calculates and displays a graph when a button is pressed

Function to get stock price data

After getting the stock price data from the company code, I defined a function that calculates the 5,25,50 day average, adds it to the data, and returns it. This is a round pakuri of kinocode.


def company_stock(start,end,company_code):
    df = data.DataReader(company_code,'stooq')
    df = df[(df.index <=end)&(df.index >=start)]

    date=df.index
    price=df['Close']

    span01 = 5
    span02 = 25
    span03 = 50

    df['sma01'] = price.rolling(window=span01).mean()
    df['sma02'] = price.rolling(window=span02).mean()
    df['sma03'] = price.rolling(window=span03).mean()
    
    return df

A function that calculates and displays a graph when a button is pressed

The event when the button is pressed is defined as a function. I am defining a function that gets a value from text, gets stock price data, and displays it in a GUI with a graph.


##click event
def btn_click():
    company_code = txtBox.get()
    start = txtBox2.get()
    end = txtBox3.get()

    df = company_stock(start,end,company_code)
    date=df.index
    price=df['Close']
    
    #plt.figure(figsize=(20,10))
    
    fig = Figure(figsize=(6,6), dpi=100)
    plt = fig.add_subplot(2,1,1)
    plt.plot(date,price,label=company_code)
    plt.plot(date,df['sma01'],label='sma01')
    plt.plot(date,df['sma02'],label='sma02')
    plt.plot(date,df['sma03'],label='sma03')
    
    plt.set_title(company_code)
    plt.set_xlabel('date')
    plt.set_ylabel('price')
    #plt.title(company_code)
    #plt.xlabel('date')
    #plt.ylabel('price')
    plt.legend()

    plt = fig.add_subplot(2,1,2)
    plt.bar(date,df['Volume'],label='Volume',color='grey')
    plt.legend()


    canvas = FigureCanvasTkAgg(fig, master=root)  # Generate canvas instance, Embedding fig in root
    canvas.draw()
    canvas.get_tk_widget().place(x=10, y=120)

GUI settings

Code to set the GUI. Arrangement and screens are created by trial and error. Button events are set by associating "command = btn_click" with the function. (I thought it would be understandable if I wrote it quite a bit.)

# Figure instance
fig = plt.Figure(figsize=(6,6), dpi=100)

root = tk.Tk()
root.title("stock analsis")
root.geometry("620x740")

#Write text
label = tk.Label(root, text="Company code")
label.place(x=10, y=10)

label2 = tk.Label(root, text="start date")
label2.place(x=120, y=10)

label3 = tk.Label(root, text="End date")
label3.place(x=230, y=10)

#Write a button
txtBox = tk.Entry()
txtBox.configure(state='normal', width=15)
txtBox.place(x=10, y=40)

txtBox2 = tk.Entry()
txtBox2.configure(state='normal', width=15)
txtBox2.place(x=120, y=40)

txtBox3 = tk.Entry()
txtBox3.configure(state='normal', width=15)
txtBox3.place(x=230, y=40)

#Install the button
button = tk.Button(text='Stock price display', width=20, command=btn_click)
button.place(x=10, y=80)


#Draw a graph
canvas = FigureCanvasTkAgg(fig, master=root)  # Generate canvas instance, Embedding fig in root
canvas.draw()
canvas.get_tk_widget().place(x=10, y=120)

root.mainloop()

Final code

The final code looks like this: (Just connect the cord from above.) For the time being, if you copy this, it will probably work!

stock_analysis.py



from pandas_datareader import data
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
%matplotlib inline

def company_stock(start,end,company_code):
    df = data.DataReader(company_code,'stooq')
    df = df[(df.index <=end)&(df.index >=start)]

    date=df.index
    price=df['Close']

    span01 = 5
    span02 = 25
    span03 = 50

    df['sma01'] = price.rolling(window=span01).mean()
    df['sma02'] = price.rolling(window=span02).mean()
    df['sma03'] = price.rolling(window=span03).mean()
    
    return df

#click event
def btn_click():
    company_code = txtBox.get()
    start = txtBox2.get()
    end = txtBox3.get()

    df = company_stock(start,end,company_code)
    date=df.index
    price=df['Close']
    
    #plt.figure(figsize=(20,10))
    
    fig = Figure(figsize=(6,6), dpi=100)
    plt = fig.add_subplot(2,1,1)
    plt.plot(date,price,label=company_code)
    plt.plot(date,df['sma01'],label='sma01')
    plt.plot(date,df['sma02'],label='sma02')
    plt.plot(date,df['sma03'],label='sma03')
    
    plt.set_title(company_code)
    plt.set_xlabel('date')
    plt.set_ylabel('price')
    #plt.title(company_code)
    #plt.xlabel('date')
    #plt.ylabel('price')
    plt.legend()

    plt = fig.add_subplot(2,1,2)
    plt.bar(date,df['Volume'],label='Volume',color='grey')
    plt.legend()


    canvas = FigureCanvasTkAgg(fig, master=root)  # Generate canvas instance, Embedding fig in root
    canvas.draw()
    canvas.get_tk_widget().place(x=10, y=120)

# Figure instance
fig = plt.Figure(figsize=(6,6), dpi=100)

root = tk.Tk()
root.title("stock analsis")
root.geometry("620x740")

#Write text
label = tk.Label(root, text="Company code")
label.place(x=10, y=10)

label2 = tk.Label(root, text="start date")
label2.place(x=120, y=10)

label3 = tk.Label(root, text="End date")
label3.place(x=230, y=10)

#Write a button
txtBox = tk.Entry()
txtBox.configure(state='normal', width=15)
txtBox.place(x=10, y=40)

txtBox2 = tk.Entry()
txtBox2.configure(state='normal', width=15)
txtBox2.place(x=120, y=40)

txtBox3 = tk.Entry()
txtBox3.configure(state='normal', width=15)
txtBox3.place(x=230, y=40)

#Install the button
button = tk.Button(text='Stock price display', width=20, command=btn_click)
button.place(x=10, y=80)


#Draw a graph
canvas = FigureCanvasTkAgg(fig, master=root)  # Generate canvas instance, Embedding fig in root
canvas.draw()
canvas.get_tk_widget().place(x=10, y=120)

root.mainloop()

The company code is obtained from the Stock Exchange Site as shown in the figure below. image.png

If you fill in the conditions based on this, you can get the following results.

image.png

in conclusion

For the time being, I knew how to display the graph on the GUI, so I thought it would be easier to display the graph and consider it. I got smarter again. But I want to remember it. (I forgot how to use SSH outside the LAN, which I had a lot of trouble with recently, and felt the fragility of people's memory.)

Recommended Posts

Let's make a GUI with python.
Let's make a graph with python! !!
Let's make a shiritori game with Python
Let's make a voice slowly with Python
Let's make a web framework with Python! (1)
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
Make a fortune with Python
Let's replace UWSC with Python (5) Let's make a Robot
[Let's play with Python] Make a household account book
Let's make a breakout with wxPython
Let's make a simple game with Python 3 and iPhone
Make a recommender system with python
Let's make a supercomputer with xCAT
[Super easy] Let's make a LINE BOT with Python.
Let's make a websocket client with Python. (Access token authentication)
Let's create a free group with Python
Let's make a simple language with PLY 1
[Python] Let's make matplotlib compatible with Japanese
Let's make a tic-tac-toe AI with Pylearn 2
Let's make a combination calculation in Python
Make a desktop app with Python with Electron
Let's make a web chat using WebSocket with AWS serverless (Python)!
Make a Twitter trend bot with heroku + Python
I made a GUI application with Python + PyQt5
[Python] Make a game with Pyxel-Use an editor-
I want to make a game with Python
You can easily create a GUI with Python
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Try to make a dihedral group with Python
Let's make a module for Python using SWIG
Open a file dialog with a python GUI (tkinter.filedialog)
[Ev3dev] Let's make a remote control program by Python with RPyC protocol
Let's make a Discord Bot.
Let's run Excel with Python
Let's make Othello with wxPython
Make Puyo Puyo AI with Python
[GUI with Python] PyQt5-Layout management-
Let's make dice with tkinter
Make a bookmarklet in Python
Let's write python with cinema4d.
Create a directory with python
Let's make a rock-paper-scissors game
Let's build git-cat with Python
[GUI with Python] PyQt5 -Preparation-
Make a fire with kdeplot
[GUI with Python] PyQt5 -Paint-
Make one repeating string with a Python regular expression.
Try to make a command standby tool with python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Make a simple Slackbot with interactive button in python
Make a breakpoint on the c layer with python
Let's make dependency management with pip a little easier
[For play] Let's make Yubaba a LINE Bot (Python)
Make a CSV formatting tool with Python Pandas PyInstaller
Let's make a Mac app with Tkinter and py2app
Let's make a spherical grid with Rhinoceros / Grasshopper / GHPython
What is God? Make a simple chatbot with python
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script