-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_app.py
249 lines (179 loc) · 8.19 KB
/
main_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# ====== IMPORTS ====== #
import tkinter as tk
from tkinter import ttk
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import json
import requests
from bs4 import BeautifulSoup
import os
import time
from tkcalendar import Calendar
def exec_downloading_data_code():
import downloading_data
exec_downloading_data_code()
# Create the main application window
root = tk.Tk()
# ====== GUI SETUP ====== #
root.title("US Bond Yield Curve")
root.geometry('1400x750+0+0')
root.resizable(True, True)
root.minsize(400, 400)
plt.style.use('dark_background')
notebook = ttk.Notebook(root)
# Reading the CSV file
df = pd.read_csv("Data/_US Bond Yield Data from 1990 to date.csv", sep=",")
# ====== DATE SELECTION ====== #
class TkLabel:
def __init__(self, text, column, row, font='Microsoft Sans Serif', fontsize=15, width=22, anchor='center', bg='black', fg='white'):
self.label = tk.Label(root, text=text, font=(font, fontsize), width=width, anchor=anchor, bg=bg, fg=fg)
self.label.grid(column=column, row=row, columnspan=1)
start_date_label = TkLabel('Animation start date', 1, 1)
end_date_label = TkLabel('Animation end date', 1, 3)
# First label and calendar
l1 = tk.Label(root, bg='black', fg='white', text='Select a date') # Label to display date
l1.grid(row=1, column=2)
cal1 = Calendar(root, selectmode='day')
cal1.grid(row=2, column=2, padx=20)
# Function to update first label
def update_label(event=None):
date_str = cal1.get_date()
date_obj = datetime.strptime(date_str, '%m/%d/%y')
l1.config(text=date_obj.strftime('%B %d, %Y'))
cal1.bind("<<CalendarSelected>>", update_label)
# Second label and calendar
l2 = tk.Label(root, bg='black', fg='white', text='Select a date') # Label to display date
l2.grid(row=3, column=2)
cal2 = Calendar(root, selectmode='day')
cal2.grid(row=4, column=2, padx=20)
# Function to update second label
def update_label2(event=None):
date_str = cal2.get_date()
date_obj = datetime.strptime(date_str, '%m/%d/%y')
l2.config(text=date_obj.strftime('%B %d, %Y'))
cal2.bind("<<CalendarSelected>>", update_label2)
# ====== GRAPHING AND ANIMATING ====== #
fig, ax = plt.subplots(figsize=(5, 3))
count = 0
x = df.columns.to_list()[1:]
ani = None
def plot_presets(date):
ax.set_title(f'United States Bond Yield Curve\n{date.strftime("%b %d, %Y")}', fontname='Microsoft Sans Serif', fontsize=6)
ax.set_xticks(x_pos)
ax.set_xticklabels(x, fontname='Microsoft Sans Serif', fontsize=5)
ax.set_xlabel('Tenor', fontname='Microsoft Sans Serif', fontsize=6)
ax.tick_params(axis='y', labelsize=5)
ax.set_ylabel('Yield Percentage', fontname='Microsoft Sans Serif', fontsize=6)
ax.set_ylim(0, 10)
def start_graph_today():
global canvas_start, ax, date, x_pos
ax.cla()
ax.text(16, 5, 'Loading', fontname='Microsoft Sans Serif')
'exec_downloading_data_code()'
ax.cla()
date = datetime.today()
count = len(df)-1
x_pos = [1, 2.5, 4, 6, 8, 11, 14, 17, 20, 24, 28, 32]
y_raw = df.loc[count, '1 Mo':'30 Yr'].to_list()
y = np.array(y_raw, dtype=np.double) # Data cleaning to be improved
nans, valid = np.isnan(y), np.logical_not(np.isnan(y))
y[nans] = np.interp(np.flatnonzero(nans), np.flatnonzero(valid), y[valid])
y[np.isnan(y)] = np.nan #
ax.plot(x_pos, y, '.-', markersize=2, linewidth=1)
plot_presets(date)
canvas_start = FigureCanvasTkAgg(fig, master=root)
canvas_start.get_tk_widget().grid(column=4, row=1, rowspan=100)
canvas_start.draw()
def update():
global count, end_count, ani, ax, date, x_pos
ax.cla()
startdate = l1['text']
while datetime.strptime(startdate, '%B %d, %Y').strftime('%m/%d/%Y') not in df.iloc[:, 0].values:
startdate = (datetime.strptime(startdate, '%B %d, %Y') + timedelta(days=1)).strftime('%B %d, %Y')
enddate = l2['text']
while datetime.strptime(enddate, '%B %d, %Y').strftime('%m/%d/%Y') not in df.iloc[:, 0].values:
enddate = (datetime.strptime(enddate, '%B %d, %Y') - timedelta(days=1)).strftime('%B %d, %Y')
count = np.where(df['Date'] == datetime.strptime(startdate, '%B %d, %Y').strftime('%m/%d/%Y'))[0][0]
end_count = np.where(df['Date'] == datetime.strptime(enddate, '%B %d, %Y').strftime('%m/%d/%Y'))[0][0]
def update_frame(frame):
global count, end_count
ax.clear()
x_pos = [1, 2.5, 4, 6, 8, 11, 14, 17, 20, 24, 28, 32]
y_raw = df.loc[count, '1 Mo':'30 Yr'].to_list()
y = np.array(y_raw, dtype=np.double) # Data cleaning to be improved
nans, valid = np.isnan(y), np.logical_not(np.isnan(y))
y[nans] = np.interp(np.flatnonzero(nans), np.flatnonzero(valid), y[valid])
y[np.isnan(y)] = np.nan #
ax.plot(x_pos, y, '.-', markersize=2, linewidth=1)
date_string = df.loc[count, 'Date']
date = datetime.strptime(date_string, '%m/%d/%Y')
plot_presets(date)
count += 1
if count > end_count:
ani.event_source.stop()
if ani is not None:
ani.event_source.stop()
ani = FuncAnimation(fig, update_frame, frames=len(df) - count, interval=10)
canvas.draw()
def stop():
ani.pause()
def resume():
ani.resume()
def compare():
global canvas_compare, ax, date, x_pos
ax.cla()
startdate = l1['text']
while startdate not in df.iloc[:, 0].values:
startdate = (datetime.strptime(startdate, '%B %d, %Y') + timedelta(days=1)).strftime('%B %d, %Y')
enddate = l2['text']
if datetime.strptime(enddate, '%B %d, %Y') >= datetime.strptime(startdate, '%B %d, %Y'):
while enddate not in df.iloc[:, 0].values:
enddate = (datetime.strptime(enddate, '%B %d, %Y') - timedelta(days=1)).strftime('%B %d, %Y')
ax.cla()
x_pos = [1, 2.5, 4, 6, 8, 11, 14, 17, 20, 24, 28, 32]
y_start_raw = df.loc[count, '1 Mo':'30 Yr'].to_list()
y_start = np.array(y_start_raw, dtype=np.double) # Data cleaning to be improved
nans, valid = np.isnan(y_start), np.logical_not(np.isnan(y_start))
y_start[nans] = np.interp(np.flatnonzero(nans), np.flatnonzero(valid), y_start[valid])
y_start[np.isnan(y_start)] = np.nan #
y_end_raw = df.loc[count, '1 Mo':'30 Yr'].to_list()
y_end = np.array(y_end_raw, dtype=np.double) # Data cleaning to be improved
nans, valid = np.isnan(y_end), np.logical_not(np.isnan(y_end))
y_end[nans] = np.interp(np.flatnonzero(nans), np.flatnonzero(valid), y_end[valid])
y_end[np.isnan(y_end)] = np.nan #
date_string = df.loc[count, 'Date']
date = datetime.strptime(date_string, '%m/%d/%Y')
ax.plot(x_pos, y_start, '.-', label=l1['text'], markersize=2, linewidth=1)
ax.plot(x_pos, y_end, '.-', label=l2['text'], markersize=2, linewidth=1)
leg = plt.legend(loc='best')
plot_presets(date)
canvas_compare = FigureCanvasTkAgg(fig, master=root)
canvas_compare.get_tk_widget().grid(column=4, row=1, rowspan=100)
canvas_compare.draw()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=4, row=1, rowspan=100)
graph_button = ttk.Button(root, text="⏵ Animate from/to", command=update)
graph_button.grid(column=1, row=5)
stop_button = ttk.Button(root, text="⏸ Pause", command=stop)
stop_button.grid(column=1, row=6)
resume_button = ttk.Button(root, text="⏵ Resume", command=resume)
resume_button.grid(column=1, row=7)
compare_button = ttk.Button(root, text="Compare", command=compare)
compare_button.grid(column=2, row=5)
def today_button_func():
if ani == True: pause()
start_graph_today()
today_button = ttk.Button(root, text="Today", command=today_button_func)
today_button.grid(column=4, row=101)
creditlabel = TkLabel('© 2024 Nicholas Tang\n(github: tang_lhnicholas)', 4, 102)
ax.set_title(f'United States Bond Yield Curve', fontname='Microsoft Sans Serif')
ax.set_xlabel('Tenor', fontname='Microsoft Sans Serif')
ax.set_ylabel('Yield Percentage', fontname='Microsoft Sans Serif')
ax.set_ylim(0, 10)
start_graph_today()
root.configure(background='black')
root.mainloop()