-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
277 lines (212 loc) · 7.87 KB
/
main.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from dotenv import load_dotenv, find_dotenv
from datetime import datetime, timedelta
from weatherstack import WeatherStack
import matplotlib.pyplot as plt
from numbar import printNumBar
from owm import OWM_OneCall
from dateutil import rrule
import random
import os
load_dotenv(find_dotenv())
WEATHERSTACK_API_KEY = os.getenv("WEATHERSTACK_API")
OWM_API_KEY = os.getenv("OWM_API")
lat = os.getenv("LATITUDE")
lon = os.getenv("LONGITUDE")
def get_data():
now_timestamp = datetime.now()
five_days_ago = now_timestamp - timedelta(days=5)
days = [
dt.date() for dt in rrule.rrule(
rrule.DAILY,
dtstart=five_days_ago.date(),
until=now_timestamp.date()
)
]
data = []
wswx = WeatherStack(WEATHERSTACK_API_KEY)
owmwx = OWM_OneCall(OWM_API_KEY)
date_count = 0
total_dates = 0
for day in days:
hours = [hour for hour in range(24)]
total_dates = len(days) * len(hours)
for hr in hours:
top_hour = datetime(day.year, day.month, day.day, hr)
print(
printNumBar(
date_count,
total_dates,
decimals=0,
length=60,
bar_label=f"{int(round((date_count/total_dates) * 100))}%",
print_output=False
),
end='\r'
)
date_count += 1
if (top_hour >= five_days_ago) and ((top_hour + timedelta(hours=1)) < datetime.now()):
while True:
next_datetime = datetime(
day.year, day.month, day.day, hr, random.randint(0, 59))
if next_datetime >= five_days_ago:
next_element = {}
next_element['date'] = next_datetime
wswx.fetch_weather(lat, lon, next_datetime)
next_element['weatherstack'] = wswx.weather_data
owmwx.fetch_weather(lat, lon, next_datetime)
next_element['owm'] = owmwx.weather_data
data.append(next_element)
break
return data
def get_chart_data(parameter, data):
x_axis = []
ws_parameter = []
owm_parameter = []
for datum in data:
x_axis.append(datum.get('date', ''))
ws_data = datum.get('weatherstack', 0)
ws_parameter.append(ws_data.__getattribute__(parameter))
owm_data = datum.get('owm', 0)
owm_parameter.append(owm_data.__getattribute__(parameter))
chart_data = {}
chart_data['x-axis'] = x_axis
chart_data['ws-parameter'] = ws_parameter
chart_data['owm-parameter'] = owm_parameter
return chart_data
def show_chart(parameter, data):
chart_data = get_chart_data(parameter, data)
x_axis = chart_data['x-axis']
ws_parameter = chart_data['ws-parameter']
owm_parameter = chart_data['owm-parameter']
fig, ax = plt.subplots()
fig.canvas.set_window_title(f"{parameter.title()}")
fig.autofmt_xdate()
ax.plot(
x_axis,
ws_parameter,
label='Weatherstack',
color='Blue',
linewidth=3.0
)
ax.plot(
x_axis,
owm_parameter,
label='Open Weather Map',
color='Orange',
linewidth=3.0
)
plt.title(
f"API Data Comparison - {parameter.title()}"
)
ax.legend(loc='best')
ax.grid(True, linestyle=':', which='major', axis='y')
plt.show()
def print_data(data):
field_data = [
{'name': 'temperature', 'parameter': 'temp'},
{'name': 'feels like', 'parameter': 'feelslike'},
{'name': 'pressure', 'parameter': 'pressure'},
{'name': 'dew point', 'parameter': 'dewpoint'},
{'name': 'humidity', 'parameter': 'humidity'},
{'name': 'clouds', 'parameter': 'clouds'},
{'name': 'visibility', 'parameter': 'visibility'},
{'name': 'wind speed', 'parameter': 'wind_speed'},
{'name': 'wind direction', 'parameter': 'wind_dir'},
]
print()
for datum in data:
print(datum.get('date', None))
for fd in field_data:
print(
f"\t{fd['name']:14}:\t{datum['owm'].__getattribute__(fd['parameter'])}\t{datum['weatherstack'].__getattribute__(fd['parameter'])}")
def save_data(data):
filename = 'wx_data.csv'
file = open(filename, "w")
file.write(
"date,owm temp,ws temp,owm feelslike,ws feelslike,owm pressure,ws pressure,owm dewpoint,ws dewpoint,owm humidity,ws humidity,owm clouds,ws clouds,owm visibility,ws visibility,owm wind_speed,ws wind_speed,owm wind_dir,ws wind_dir\n")
for datum in data:
file.write(f"{datum.get('date', None)},{datum['owm'].temp},{datum['weatherstack'].temp},{datum['owm'].feelslike},{datum['weatherstack'].feelslike},{datum['owm'].pressure},{datum['weatherstack'].pressure},{datum['owm'].dewpoint},{datum['weatherstack'].dewpoint},{datum['owm'].humidity},{datum['weatherstack'].humidity},{datum['owm'].clouds},{datum['weatherstack'].clouds},{datum['owm'].visibility},{datum['weatherstack'].visibility},{datum['owm'].wind_speed},{datum['weatherstack'].wind_speed},{datum['owm'].wind_dir},{datum['weatherstack'].wind_dir}\n")
file.close()
print(f"data saved to {filename}")
def display_title_bar():
if os.name == 'nt': # for windows
os.system('cls')
else: # for mac and linux(here, os.name is 'posix')
os.system('clear')
print("\t********************************")
print("\t****** Weather API Test ******")
print("\t********************************")
def show_menu():
active_menu = 'main'
print("\n\t[1] Get Data from APIs")
print("\t[2] Print Weather Data")
print("\t[3] Save Weather Data")
print("\t[t] Display Temp Chart")
print("\t[p] Display Pressure Chart")
print("\t[d] Display Dew Point Chart")
print("\t[h] Display Humidity Chart")
print("\t[c] Display Cloud Chart")
print("\t[v] Display Visibility Chart")
print("\t[ws] Display Wind Speed Chart")
print("\t[wd] Display Wind Direction Chart")
print("\t[q] Quit")
return input("\n\tSelection? ")
wx_data = None
command = ''
display_title_bar()
while command != 'q':
command = show_menu()
display_title_bar()
if command == '1':
wx_data = get_data()
print()
input("PRESS ENTER TO CONTINUE")
display_title_bar()
elif command == '2':
if wx_data != None:
print_data(wx_data)
print()
input("PRESS ENTER TO CONTINUE")
display_title_bar()
elif command == '3':
if wx_data != None:
save_data(wx_data)
print()
input("PRESS ENTER TO CONTINUE")
display_title_bar()
elif command == 't':
if wx_data != None:
show_chart('temp', wx_data)
display_title_bar()
elif command == 'f':
if wx_data != None:
show_chart('feelslike', wx_data)
display_title_bar()
elif command == 'p':
if wx_data != None:
show_chart('pressure', wx_data)
display_title_bar()
elif command == 'd':
if wx_data != None:
show_chart('dewpoint', wx_data)
display_title_bar()
elif command == 'h':
if wx_data != None:
show_chart('humidity', wx_data)
display_title_bar()
elif command == 'c':
if wx_data != None:
show_chart('clouds', wx_data)
display_title_bar()
elif command == 'v':
if wx_data != None:
show_chart('visibility', wx_data)
display_title_bar()
elif command == 'ws':
if wx_data != None:
show_chart('wind_speed', wx_data)
display_title_bar()
elif command == 'wd':
if wx_data != None:
show_chart('wind_dir', wx_data)
display_title_bar()