-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQMCBT_01_acquire.py
403 lines (321 loc) · 10.8 KB
/
QMCBT_01_acquire.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#################################################
#################### IMPORTS ####################
#################################################
# ---------------- #
# Common Libraries #
# ---------------- #
import os
import requests
import numpy as np
import pandas as pd
# Working with Dates & Times
from sklearn.model_selection import TimeSeriesSplit
from datetime import timedelta, datetime
import statsmodels.api as sm
# to evaluate performance using rmse
from sklearn.metrics import mean_squared_error
from math import sqrt
# for tsa
import statsmodels.api as sm
# holt's linear trend model.
from statsmodels.tsa.api import Holt
# Plots, Graphs, & Visualization
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
from matplotlib.dates import DateFormatter
###########################################################
#################### TABLE OF CONTENTS ####################
###########################################################
def TOC():
"""
Prints a Table of Contents for quick reference of what functions are available for use.
"""
print("get_db_url(database) - Returns a formatted string using credentials stored in local env.py file that can be passed to a pandas read_sql() function.")
print()
print("SQL - These datasets are pulled from the Codeup SQL database using the get_db_url function and a local env.py module")
print("* new_titanic_df() - ")
print("* get_titanic_df() - ")
print("* new_iris_sql_df() - ")
print("* get_iris_sql_df() - ")
print("* new_telco_churn_df() - ")
print("* get_telco_churn_df() - ")
print("* get_store_data() - ")
print("* wrangle_store_data() - ")
print()
print("Seaborn - These datasets are pulled from the seaborn library and require that it is imported as sns")
print("* new_iris_sns_df() - ")
print("* get_iris_sns_df() - ")
print()
print("GitHub - These are datasets that can be found on Github and pulled using pandas read_csv function")
print("* get_opsd_data() - ")
print()
print("Codeup - These are datasets available on one of the Codeup servers as a csv file.")
print("* get_SAAS() - Read in saas data from cache or Codeup server then write to cache")
print()
print("")
######################################################
#################### ACQUIRE DATA ####################
######################################################
def get_db_url(database):
'''
DESCRIPTION:
Returns a formatted string using credentials stored in local env.py module that can be passed to a pandas read_sql function.
___________________________________
REQUIRED IMPORTS:
import pandas as pd
from env import user, password, host
___________________________________
ARGUMENTS:
database = 'this is the name of the database that you wish to retrieve'
'''
return f'mysql+pymysql://{user}:{password}@{host}/{database}'
# ----------------------- #
# TITANIC DATA (from SQL) #
# ----------------------- #
def new_titanic_df():
'''
DESCRIPTION:
This function reads the titanic data from the Codeup database into a DataFrame.
___________________________________
REQUIRED IMPORTS:
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
# Create SQL query.
sql_query = 'SELECT * FROM passengers'
# Read in DataFrame from Codeup database.
df = pd.read_sql(sql_query, get_db_url('titanic_db'))
return df
def get_titanic_df():
'''
DESCRIPTION:
This function reads in titanic data from Codeup database, writes data to
a csv file if a local file does not exist, and returns a DataFrame.
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
if os.path.isfile('titanic_df.csv'):
# If csv file exists, read in data from csv file.
df = pd.read_csv('titanic_df.csv', index_col=0)
else:
# Read fresh data from db into a DataFrame.
df = new_titanic_df()
# Write DataFrame to a csv file.
df.to_csv('titanic_df.csv')
return df
# -------------------- #
# IRIS DATA (from SQL) #
# -------------------- #
def new_iris_sql_df():
'''
DESCRIPTION:
This function reads the iris data from the Codeup database into a DataFrame.
___________________________________
REQUIRED IMPORTS:
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
# Create SQL query.
sql_query = 'SELECT species_id, species_name, sepal_length, sepal_width, petal_length, petal_width FROM measurements JOIN species USING(species_id)'
# Read in DataFrame from Codeup db.
df = pd.read_sql(sql_query, get_db_url('iris_db'))
return df
def get_iris_sql_df():
'''
DESCRIPTION:
This function reads in iris data from Codeup database, writes data to
a csv file if a local file does not exist, and returns a DataFrame.
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
if os.path.isfile('iris_sql_df.csv'):
# If csv file exists read in data from csv file.
df = pd.read_csv('iris_sql_df.csv', index_col=0)
else:
# Read fresh data from db into a DataFrame
df = new_iris_sql_df()
# Cache data
df.to_csv('iris_sql_df.csv')
return df
# ------------------------ #
# IRIS DATA (from SEABORN) #
# ------------------------ #
def new_iris_sns_df():
'''
DESCRIPTION:
This function reads the iris data from the seaborn database into a DataFrame.
___________________________________
REQUIRED IMPORTS:
import seaborn as sns
___________________________________
ARGUMENTS:
NONE
'''
# Read in DataFrame from pydata db.
df = sns.load_dataset('iris')
return df
def get_iris_sns_df():
'''
DESCRIPTION:
This function reads in iris data from seaborn database, writes data to
a csv file if a local file does not exist, and returns a DataFrame.
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
if os.path.isfile('iris_sns_df.csv'):
# If csv file exists read in data from csv file.
df = pd.read_csv('iris_sns_df.csv', index_col=0)
else:
# Read fresh data from db into a DataFrame
df = new_iris_sns_df()
# Cache data
df.to_csv('iris_sns_df.csv')
return df
# ----------------------- #
# TELCO DATA (from SQL) #
# ----------------------- #
def new_telco_churn_df():
'''
DESCRIPTION:
This function reads the telco_churn (NOT telco_normalized) data from the Codeup database into a DataFrame.
___________________________________
REQUIRED IMPORTS:
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
# Create SQL query.
sql_query = 'SELECT * FROM customers LEFT JOIN internet_service_types USING (internet_service_type_id) LEFT JOIN contract_types USING (contract_type_id) LEFT JOIN payment_types USING (payment_type_id);'
# Read in DataFrame from Codeup db.
df = pd.read_sql(sql_query, get_db_url('telco_churn'))
return df
def get_telco_churn_df():
'''
DESCRIPTION:
This function reads in telco_churn (NOT telco_normalized) data from Codeup database, writes data to
a csv file if a local file does not exist, and returns a DataFrame.
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
if os.path.isfile('telco_churn_df.csv'):
# If csv file exists read in data from csv file.
df = pd.read_csv('telco_churn_df.csv', index_col=0)
else:
# Read fresh data from telco db into a DataFrame
df = new_telco_churn_df()
# Cache data
df.to_csv('telco_churn_df.csv')
return df
# --------------------- #
# STORE DATA (from SQL) #
# --------------------- #
def new_store_data():
'''
DESCRIPTION:
Returns a dataframe of all store data in the tsa_item_demand database and saves a local copy as a csv file.
___________________________________
REQUIRED IMPORTS:
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
# Create query for read_sql function
query = '''
SELECT *
FROM items
JOIN sales USING(item_id)
JOIN stores USING(store_id)
'''
df = pd.read_sql(query, get_db_url('tsa_item_demand'))
df.to_csv('tsa_store_data.csv', index=False)
return df
def get_store_data():
'''
DESCRIPTION:
Checks for a local cache of tsa_store_data.csv and if not present,
will run the new_store_data() function which acquires data from Codeup's mysql server
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
'''
filename = 'tsa_store_data.csv'
if os.path.isfile(filename):
df = pd.read_csv(filename)
else:
df = new_store_data()
return df
# ----------------------- #
# OPSD DATA (from GitHub) #
# ----------------------- #
def get_opsd_data():
"""
DESCRIPTION:
Read in OPS data from local cache if it exists, otherwise pull it from github source and cache it.
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
"""
if os.path.exists('opsd.csv'):
return pd.read_csv('opsd.csv')
else:
df = pd.read_csv('https://raw.githubusercontent.com/jenfly/opsd/master/opsd_germany_daily.csv')
df.to_csv('opsd.csv', index=False)
return df
# ----------------------- #
# SAAS DATA (from Codeup) #
# ----------------------- #
def get_saas():
"""
DESCRIPTION:
Read in saas data from cache or Codeup server then write to cache
___________________________________
REQUIRED IMPORTS:
import os
import pandas as pd
___________________________________
ARGUMENTS:
NONE
"""
filename = 'saas.csv'
if os.path.isfile(filename):
df = pd.read_csv(filename)
else:
url = 'https://ds.codeup.com/saas.csv'
df = pd.read_csv(url)
df.to_csv('saas.csv', index=False)
return df