-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
506 lines (410 loc) · 16.5 KB
/
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
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import json
import pandas as pd
import requests
import pymysql
import pymongo
import sqlalchemy
from sqlalchemy import create_engine
from flask import Flask, request, render_template, jsonify, make_response, redirect
import os
import re
from collections import Counter
import plotly.express as px
from plotly import graph_objects as go
from plotly.tools import FigureFactory as FF
from CK_dbFunctions import view_exists, get_dataframe_from_db, insert_user
# Imports added by TK for machine learning
from itertools import product
from datetime import datetime
import warnings
import numpy as np
from scipy import stats
import statsmodels.api as sm
from kmodes.kmodes import KModes
app = Flask(__name__)
# # # # # # # # # # # # # # # #
# Heroku check
is_heroku = False
if 'IS_HEROKU' in os.environ:
is_heroku = True
if is_heroku == True:
# if IS_HEROKU is found in the environment variables, then use the rest
# NOTE: you still need to set up the IS_HEROKU environment variable on Heroku (it is not there by default)
mongoConn = os.environ.get('mongoConn')
remote_db_endpoint = os.environ.get('remote_db_endpoint')
remote_db_port = os.environ.get('remote_db_port')
remote_db_name = os.environ.get('remote_db_name')
remote_db_user = os.environ.get('remote_db_user')
remote_db_pwd = os.environ.get('remote_db_pwd')
accessToken = os.environ.get('accessToken')
market_API = os.environ.get('market_API')
else:
# use the config.py file if IS_HEROKU is not detected
from config import mongoConn, remote_db_endpoint, remote_db_port, remote_db_name, remote_db_user, remote_db_pwd, accessToken, market_API
# # # # # # # # # # # # # # # #
## MY SQL CONN
pymysql.install_as_MySQLdb()
engine = create_engine(f"mysql://{remote_db_user}:{remote_db_pwd}@{remote_db_endpoint}:{remote_db_port}/{remote_db_name}")
# # # # # # # # # # # # # # # #
## ROUTES
@app.route("/", methods=['GET', 'POST'])
def index():
return render_template("index.html")
@app.route("/about", methods=['GET', 'POST'])
def about():
return render_template("about.html")
@app.route("/coin/<int:coinid>", methods=['GET', 'POST'])
def coin(coinid):
# print(coinid)
df = get_dataframe_from_db('vwCoins')
df = df.loc[df['CoinID'] == coinid]
dfh = get_dataframe_from_db('vwCoinHistory')
dfh = dfh.loc[dfh['CoinID'] == coinid]
Token = df.iloc[0]['TokenName']
url = f"https://api.nomics.com/v1/currencies/ticker?key={market_API}&ids={Token}&interval=1d,7d,30d&per-page=100&page=1"
print(url)
response = requests.get(url)
dfm = pd.DataFrame(response.json())
return render_template(
"coin.html"
, coin_view=df.to_dict(orient='records')
, coin_history=dfh.to_dict(orient='records')
, market_data=dfm.to_dict(orient='records')
)
@app.route("/learn", methods=['GET', 'POST'])
def learn():
return render_template("learn.html")
@app.route("/coinsearch")
def coinsearch():
return render_template("coinsearch.html", accessToken=accessToken)
@app.route("/countries-map", methods=['GET', 'POST'])
def countries_map():
return render_template("countries-map.html")
@app.route("/compare-price-dash", methods=['GET', 'POST'])
def compare_dash():
return render_template("compare-price-dash.html")
########################
## GET DATA FROM DB RETURN JSON
@app.route("/api/view/<db_view_name>")
def get_db_view(db_view_name):
df = get_dataframe_from_db(db_view_name)
_json = df.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
@app.route("/api/view/<db_view_name>/<key>/<val>")
def get_db_view_kv(db_view_name, key, val):
df = get_dataframe_from_db(db_view_name)
df = df.loc[ df[key] == val ]
_json = df.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
@app.route("/surveyview", methods=['GET', 'POST'])
def surveyview():
id = 0
if request.method == 'POST':
id = insert_user(request)
return render_template("surveyview.html", userid=id)
@app.route("/map")
def map():
return render_template("map.html", accessToken=accessToken)
@app.route("/exchanges")
def exchanges():
dfe = get_dataframe_from_db('exchangeList')
exchanges = dfe.to_dict(orient='records')
return render_template("exchanges.html", exchanges=exchanges)
@app.route("/api/ticker", methods=['GET'])
def ticker():
response = requests.get('https://crypt-keeper.herokuapp.com/api/view/vwCoins')
tdf = pd.DataFrame(response.json())
Coins = tdf['TokenName'][0:100]
CoinList = Coins.astype(str).values.tolist()
Token = ','.join(CoinList)
# print(Token)
url = f"https://api.nomics.com/v1/currencies/ticker?key={market_API}&ids={Token}&interval=1d,7d,30d&per-page=100&page=1"
# print(url)
response = requests.get(url)
df = pd.DataFrame(response.json())
df_merged = pd.merge(tdf, df, left_on='TokenName', right_on='id')
_json = df_merged.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
# Tom's price predictor
## this is the method that accepts a POST request
# @app.route("/price-prediction-data", methods=['GET', 'POST'])
# def price_prediction_data():
# coin_of_interest = request.form['CoinName']
# print('test'+coin_of_interest)
# #Connect to Amazon SQL
# conn = engine.connect()
# # Grab coin prices
# query = '''
# SELECT
# RecordDate,
# OpenPrice,
# High,
# Low,
# ClosingPrice,
# AdjClose,
# Volume,
# c.CoinName,
# cph.TokenName
# FROM
# CoinPriceHistory cph
# INNER JOIN Coins c
# ON cph.CoinID = c.CoinID
# ORDER BY
# RecordDate
# '''
# coin_raw = pd.read_sql(query, conn)
# # Grab coin names
# query = '''
# SELECT CoinName FROM Coins
# '''
# coin_names = pd.read_sql(query,conn)
# # NEED TO IMPLEMENT: LINK TO PRICE-PREDICT.HTML
# # Get coin-of-interest from user
# # coin_of_interest = request.form['coi']
# # NEED TO IMPLMENT: PASS RESPONSE BACK TO PRICE-PREDICT.HTML
# # Determine if coin is in db
# # For now, we print it to the terminal.
# if coin_names[coin_names['CoinName']==coin_of_interest].any().bool():
# print("We got your coin!")
# else:
# print('We NO got your coin')
# # Clean data
# coin_history = coin_raw[coin_raw['CoinName']==coin_of_interest]
# coin_history['RecordDate'] = pd.to_datetime(coin_history['RecordDate'], errors='coerce')
# coin_history.rename(columns={'RecordDate':'Timestamp','OpenPrice':'Open', 'ClosingPrice':'Close'}, inplace=True)
# coin_history.set_index('Timestamp', inplace=True)
# coin_history.drop(['AdjClose', 'Volume', 'CoinName', 'TokenName'], axis=1, inplace=True)
# coin_history = coin_history[coin_history['Close']!=0]
# # Transform data for ARIMA
# coin_history['Box'], lmbda = stats.boxcox(coin_history.Close)
# coin_history['BoxDiff'] = coin_history.Box - coin_history.Box.shift(12)
# coin_history['BoxDiff2'] = coin_history.BoxDiff - coin_history.BoxDiff.shift(1)
# # Optimize ARIMA Prediction
# Qs = range(0, 2)
# qs = range(0, 3)
# Ps = range(0, 3)
# ps = range(0, 3)
# D=1
# d=1
# parameters = product(ps, qs, Ps, Qs)
# parameters_list = list(parameters)
# results = []
# best_aic = float("inf")
# warnings.filterwarnings('ignore')
# #for param in parameters_list:
# param = parameters_list[0]
# try:
# model=sm.tsa.statespace.SARIMAX(coin_history.Box, order=(param[0], d, param[1]),
# seasonal_order=(param[2], D, param[3], 12)).fit(disp=-1)
# except:
# print('Data cannot be conditioned for ARIMA model. Sorry!') # Need to send this back to user
# aic = model.aic
# if aic < best_aic:
# best_model = model
# best_aic = aic
# best_param = param
# results.append([param, model.aic])
# #Generate Price Prediction Data
# def invboxcox(y,lmbda):
# if lmbda == 0:
# return(np.exp(y))
# else:
# return(np.exp(np.log(lmbda*y+1)/lmbda))
# coin_history_with_predictions = coin_history[['Close']]
# coin_history_with_predictions['Forecast'] = invboxcox(best_model.predict(start = 0, end=(len(coin_history_with_predictions)-1)), lmbda)
# prediction_dates = [datetime(2021, 4, 30), datetime(2021, 5, 31), datetime(2021, 6, 30),
# datetime(2021, 7, 31), datetime(2021, 8, 31), datetime(2021, 9, 30), datetime(2021, 10, 31),
# datetime(2021, 11, 30), datetime(2021, 12, 31)]
# future = pd.DataFrame(index=prediction_dates, columns= coin_history.columns)
# future['Forecast'] = invboxcox(best_model.forecast(steps=len(future)), lmbda).tolist()
# coin_history_with_predictions = pd.concat([coin_history_with_predictions, future])
# coin_history_with_predictions['Coin'] = coin_of_interest
# graph = coin_history_with_predictions.reset_index().rename(columns={'index':'Date'})
# graph2 = graph[['Coin','Date', 'Close', 'Forecast']]
# # Return Price Prediction Data to Plotly
# _json = graph2.to_json(orient='records')
# resp = make_response(_json)
# resp.headers['content-type'] = 'application/json'
# return resp
## This is the method that uses the query string
@app.route("/price-prediction-data", methods=['GET', 'POST'])
def price_prediction_data():
coin_of_interest = request.args.get('CoinName')
print('test'+coin_of_interest)
#Connect to Amazon SQL
conn = engine.connect()
# Grab coin prices
query = '''
SELECT
RecordDate,
OpenPrice,
High,
Low,
ClosingPrice,
AdjClose,
Volume,
c.CoinName,
cph.TokenName
FROM
CoinPriceHistory cph
INNER JOIN Coins c
ON cph.CoinID = c.CoinID
ORDER BY
RecordDate
'''
coin_raw = pd.read_sql(query, conn)
# Grab coin names
query = '''
SELECT CoinName FROM Coins
'''
coin_names = pd.read_sql(query,conn)
# NEED TO IMPLEMENT: LINK TO PRICE-PREDICT.HTML
# Get coin-of-interest from user
# coin_of_interest = request.form['coi']
# NEED TO IMPLMENT: PASS RESPONSE BACK TO PRICE-PREDICT.HTML
# Determine if coin is in db
# For now, we print it to the terminal.
if coin_names[coin_names['CoinName']==coin_of_interest].any().bool():
print("We got your coin!")
else:
print('We NO got your coin')
# Clean data
coin_history = coin_raw[coin_raw['CoinName']==coin_of_interest]
coin_history['RecordDate'] = pd.to_datetime(coin_history['RecordDate'], errors='coerce')
coin_history.rename(columns={'RecordDate':'Timestamp','OpenPrice':'Open', 'ClosingPrice':'Close'}, inplace=True)
coin_history.set_index('Timestamp', inplace=True)
coin_history.drop(['AdjClose', 'Volume', 'CoinName', 'TokenName'], axis=1, inplace=True)
coin_history = coin_history[coin_history['Close']!=0]
# Transform data for ARIMA
coin_history['Box'], lmbda = stats.boxcox(coin_history.Close)
coin_history['BoxDiff'] = coin_history.Box - coin_history.Box.shift(12)
coin_history['BoxDiff2'] = coin_history.BoxDiff - coin_history.BoxDiff.shift(1)
# Optimize ARIMA Prediction
Qs = range(0, 2)
qs = range(0, 3)
Ps = range(0, 3)
ps = range(0, 3)
D=1
d=1
parameters = product(ps, qs, Ps, Qs)
parameters_list = list(parameters)
results = []
best_aic = float("inf")
warnings.filterwarnings('ignore')
#for param in parameters_list:
param = parameters_list[0]
try:
model=sm.tsa.statespace.SARIMAX(coin_history.Box, order=(param[0], d, param[1]),
seasonal_order=(param[2], D, param[3], 12)).fit(disp=-1)
except:
print('Data cannot be conditioned for ARIMA model. Sorry!') # Need to send this back to user
aic = model.aic
if aic < best_aic:
best_model = model
best_aic = aic
best_param = param
results.append([param, model.aic])
#Generate Price Prediction Data
def invboxcox(y,lmbda):
if lmbda == 0:
return(np.exp(y))
else:
return(np.exp(np.log(lmbda*y+1)/lmbda))
coin_history_with_predictions = coin_history[['Close']]
coin_history_with_predictions['Forecast'] = invboxcox(best_model.predict(start = 0, end=(len(coin_history_with_predictions)-1)), lmbda)
prediction_dates = [datetime(2021, 4, 30), datetime(2021, 5, 31), datetime(2021, 6, 30),
datetime(2021, 7, 31), datetime(2021, 8, 31), datetime(2021, 9, 30), datetime(2021, 10, 31),
datetime(2021, 11, 30), datetime(2021, 12, 31)]
future = pd.DataFrame(index=prediction_dates, columns= coin_history.columns)
future['Forecast'] = invboxcox(best_model.forecast(steps=len(future)), lmbda).tolist()
coin_history_with_predictions = pd.concat([coin_history_with_predictions, future])
coin_history_with_predictions['Coin'] = coin_of_interest
graph = coin_history_with_predictions.reset_index().rename(columns={'index':'Date'})
graph2 = graph[['Coin','Date', 'Close', 'Forecast']]
# Return Price Prediction Data to Plotly
_json = graph2.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
@app.route("/user-centroid-data", methods=["GET", "POST"])
def user_centroid_data():
# Connect to Amazon mySQL
conn = engine.connect()
# Get user data
query = '''
SELECT
*
FROM
CryptoSurveyData
'''
users = pd.read_sql(query, conn)
users.set_index('Entry', inplace=True)
people_list = ['User', 'FirstName', 'LastName', 'City', 'State', 'Zip', 'Lat', 'Lng']
attribute_list = ['Age', 'Gender', 'Known', 'Understanding', 'HaveInvested', 'CryptoSafe', 'CryptoConcern', 'MoreRiskCryptoStock']
people = users[people_list]
attributes = users[attribute_list]
# Cluster users
model = KModes(n_clusters=3, init='Huang', n_init=1, verbose=1, random_state=4)
clusters = model.fit_predict(attributes)
# Identify centroids
centroids = pd.DataFrame(model.cluster_centroids_, columns=attribute_list)
attributes.insert(0, "cluster", clusters, False)
# attributes['cluster'] = clusters
marketing_df = people.merge(attributes, how='inner', left_index=True, right_index=True)
_json = centroids.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
@app.route("/user-clusters-data", methods=["GET", "POST"])
def user_clusters_data():
centroid_choice = request.args.get('CentroidChoice')
print('test'+centroid_choice)
# Connect to Amazon mySQL
conn = engine.connect()
# Get user data
query = '''
SELECT
*
FROM
CryptoSurveyData
'''
users = pd.read_sql(query, conn)
users.set_index('Entry', inplace=True)
people_list = ['User', 'FirstName', 'LastName', 'City', 'State', 'Zip', 'Lat', 'Lng']
attribute_list = ['Age', 'Gender', 'Known', 'Understanding', 'HaveInvested', 'CryptoSafe', 'CryptoConcern', 'MoreRiskCryptoStock']
people = users[people_list]
attributes = users[attribute_list]
# Cluster users
model = KModes(n_clusters=3, init='Huang', n_init=1, verbose=1, random_state=4)
clusters = model.fit_predict(attributes)
# Identify centroids
centroids = pd.DataFrame(model.cluster_centroids_, columns=attribute_list)
attributes.insert(0, "cluster", clusters, False)
# attributes['cluster'] = clusters
marketing_df = people.merge(attributes, how='inner', left_index=True, right_index=True)
print(centroid_choice)
marketing_targets = marketing_df[marketing_df.cluster == int(centroid_choice)]
_json = marketing_targets.to_json(orient='records')
resp = make_response(_json)
resp.headers['content-type'] = 'application/json'
return resp
@app.route("/cluster-users")
def user_cluster():
return render_template("cluster-users.html")
@app.route("/price-predict")
def price_predict():
return render_template("price-predict.html")
# @app.route("/price-prediction-data-test", methods=['GET', 'POST'])
# def price_prediction_data_test():
# CoinName = request.form['CoinName']
# return CoinName
# run the app in debug mode
if __name__ == "__main__":
app.secret_key = os.urandom(24)
app.run(debug=True)