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.
The environment is shown below. ・ Windows10 ・ Python3 (anaconda) Development was mainly done in jupyter-lab.
I will briefly explain the contents of the code. If you just want the results, you can refer to the final "final code".
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.
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
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
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)
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()
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.
If you fill in the conditions based on this, you can get the following results.
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