-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexchange_chart.py
More file actions
95 lines (68 loc) · 2.45 KB
/
exchange_chart.py
File metadata and controls
95 lines (68 loc) · 2.45 KB
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
import datetime
try:
import urllib.request as urllib_request
except ImportError: # Pyton 2.7
import urllib2 as urllib_request
import json
try:
import tkinter
except ImportError: # python 2.7
import Tkinter as tkinter
def draw_axes():
canvas.configure(scrollregion=(0, -y_origin, x_origin / 2, y_origin + label_height))
canvas.create_line(0, y_origin, x_origin, y_origin, width=2)
canvas.create_line(0, 0, 0, y_origin * 2, width=2)
def print_label(x, label):
canvas.create_text(x * bar_width * 2, y_origin, text=label, anchor='nw')
def draw_bar(x, y, bar_colour):
x_pos = x * bar_width * 2 + bar_width
y_height = y * bar_scaling
canvas.create_rectangle(x_pos - bar_width + bar_spacing, y_origin - 2, x_pos + bar_width, y_origin - y_height,
fill=bar_colour, outline=bar_colour)
def generate_year_month(now):
start_month = now.month - 11
start_year = now.year
if start_month < 0:
start_month = 12 + start_month
start_year -= 1
for count in range(12):
yield start_year, start_month
start_month += 1
if start_month > 12:
start_year += 1
start_month = 1
mainWindow = tkinter.Tk()
mainWindow.title("USD Exchange Rates")
mainWindow.geometry('1024x768')
canvas = tkinter.Canvas(mainWindow, width=800, height=600)
canvas.grid(row=1, column=0)
canvas.update()
x_origin = canvas.winfo_width()
y_origin = canvas.winfo_height() / 2
bar_width = 11
bar_spacing = 4
bar_scaling = 150
label_height = 40
draw_axes()
chart_data = [('AUD', 'blue'), ('GBP', 'red'), ('EUR', 'green')]
# draw the key
row_y_position = 0
for currency, colour in chart_data:
canvas.create_text(x_origin / 2, row_y_position, text=currency, anchor='nw', fill=colour)
row_y_position += 20
bar_x = 0
# get the data for the last 12 months.
current_date = datetime.datetime.utcnow()
for year, month in generate_year_month(current_date):
month_start = '{0}-{1:02d}-01'.format(year, month)
# print(month_start)
data_values = urllib_request.urlopen('http://api.fixer.io/{}?base=USD'.format(month_start)).read()
# print(data_values)
dict1 = json.loads(data_values.decode('utf-8'))
# print(dict1)
rates = dict1['rates']
print_label(bar_x + 1, "{}\n{}".format(datetime.date(year, month, 1).strftime('%B')[:3], year))
for currency, colour in chart_data:
draw_bar(bar_x, rates[currency], colour)
bar_x += 1
mainWindow.mainloop()