-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.py
416 lines (293 loc) · 11.2 KB
/
server.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
from jinja2 import StrictUndefined
from flask import Flask, render_template, request, flash, redirect, session, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from model import connect_to_db, db, User, User_Company, Company, DailyPrice
import datetime as dt
import json
import pandas
import pandas_datareader.data as pan
from pandas_datareader._utils import RemoteDataError
import datetime
import requests
app = Flask(__name__)
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"
app.jinja_env.undefined = StrictUndefined
@app.route('/search')
def get_company_info():
"""Make the search box active and help users look for company info"""
ticker = request.args.get('ticker')
api_request = requests.get("https://cloud.iexapis.com/stable/stock/"+ ticker +
"/company/quote?token=pk_ab6548b1284345368ccec6e806e70415")
ticker_api = api_request.json()
return render_template("comp_info.html", ticker=ticker, ticker_api = ticker_api)
@app.route('/')
def index():
return render_template("homepage.html")
@app.route('/add_stock')
def add_stock_to_port():
return render_template("charts.html")
@app.route('/chart.json')
def get_chart():
ticker = request.args.get('comp') # args is for finding GET parameters
tickers = DailyPrice.query.filter_by(ticker=ticker).all()
dates = []
close_prices = []
for t in tickers:
dates.append(t.date.strftime("%a, %d %B %Y"))
close_prices.append(t.close_p)
dates.reverse()
close_prices.reverse()
data_dict = {
"dates": dates,
"close_prices": close_prices
}
return jsonify(data_dict)
@app.route('/variation.json')
def daily_price_variation():
"""Calculate the daily price variation"""
ticker = request.args.get('comp')
tickers = DailyPrice.query.filter_by(ticker=ticker).all()
# Return daily price variation in percentage
dates = []
per_daily_price_list = []
for t in tickers:
per = round(((float(t.open_p - t.close_p)/abs(t.open_p))*100),2)
per_daily_price_list.append(per)
dates.append(t.date.strftime("%a, %d %B %Y"))
data_dict = {
"labels": dates,
"datasets": [
{
# "label": false,
"barPercentage": 0.5,
"barThickness" :2,
"maxBarThickness": 3,
"minBarLength":1,
"backgroundColor": 'rgb(144,238,144)',
"borderColor": 'rgb(144,238,144)',
"data":per_daily_price_list
}
]
}
return jsonify(data_dict)
@app.route("/login", methods=["GET"])
def login_form():
"""login form."""
return render_template("login_form.html")
@app.route("/register", methods=["GET"])
def register_form():
"""register form."""
return render_template("register.html")
@app.route("/register", methods=["POST"])
def register_create():
"""Users need to login"""
fname = request.form["firstname"]
lname = request.form["lastname"]
email = request.form["email"]
password = request.form["password"]
new_user = User(fname=fname, lname=lname, email=email, password=password)
db.session.add(new_user)
db.session.commit()
flash('Registration successful! Please login.')
return redirect("/login")
@app.route("/login", methods=["POST"])
def login_process():
"""Create login process"""
email = request.form["email"]
password = request.form["password"]
try:
user = User.query.filter_by(email=email).one()
if not user:
flash("No such users")
return redirect("/login")
if user.password != password:
flash("Incorrect password")
return redirect("/login")
else:
session["user_id"] = user.user_id
flash("Logged in!")
return redirect("/")
except NoReultFound:
flash("Login Failed!, invalid Email or password")
return redirect('/register')
@app.route("/logout")
def logout():
"""logout form"""
del session["user_id"]
flash("Logged Out.")
return redirect("/")
@app.route("/add_portfolio", methods=['POST'])
def add_to_profolio():
"""Users enter a ticker on the chart page and add it to their portfolio"""
ticker = request.form["ticker"] # is for finding POST parameters
user_id = session.get("user_id")
if not user_id:
return redirect("/login")
new_ticker = User_Company(ticker=ticker, user_id=user_id)
db.session.add(new_ticker)
db.session.commit()
user = User.query.get(user_id)
return redirect("/user_stock")
@app.route("/user_stock")
def add_stock():
"""Look up user id and find all the tickers for that user id"""
user = User.query.get(session['user_id'])
tickers = user.companies
response_list = []
for each_ticker in tickers:
api = requests.get("https://cloud.iexapis.com/stable/stock/"+ each_ticker.ticker
+"/quote?token=pk_ab6548b1284345368ccec6e806e70415")
ticker_api = api.json()
response_list.append(ticker_api)
try:
start = dt.datetime(2019, 11, 10)
end = dt.datetime(2019, 11, 26)
reTurn_list = []
risk_list =[]
ticker_list = []
for each_ticker in tickers:
df = pan.DataReader(each_ticker.ticker, 'av-daily', start, end,
api_key="pk_ab6548b1284345368ccec6e806e70415")['close']
per_ticker = df.pct_change()
reTurn = round(per_ticker.mean(),5)
reTurn_list.append(reTurn)
max_ReTurn= max(reTurn_list)
risk = round(per_ticker.std(),5)
risk_list.append(risk)
max_risk= max(risk_list)
ticker_list.append(each_ticker.ticker)
new_dict1 = dict(zip(ticker_list, risk_list))
max1 = max(new_dict1, key=new_dict1.get)
new_dict2 = dict(zip(ticker_list, reTurn_list))
max2 = max(new_dict2, key=new_dict2.get)
return render_template("myportfolio.html",
ticker_data=response_list,
new_dict2=new_dict2,
new_dict1=new_dict1,
max1 = max1,
max2 = max2)
except RemoteDataError:
return redirect("/")
# @app.route("/delete", methods=['POST'])
# def delete_stock():
# """Delete stock method"""
# item = request.form.get("delete_ticker")
# delete_item = User_Company.query.filter_by(ticker=item).first()
# db.session.delete(delete_item)
# db.session.commit()
# return redirect('/user_stock')
@app.route("/user_portfolio")
def go_to_portfolio():
return redirect("/user_stock")
@app.route("/correlation.json")
def analyze_corr():
"""Correlation analysis between two companies"""
ticker1 = request.args.get("ticker1")
ticker2 = request.args.get("ticker2")
#set the time frame to fetch stock data
start = dt.datetime(2019, 11, 7)
end = dt.datetime(2019, 12, 7)
df1 = pan.DataReader(ticker1, 'av-daily', start, end,
api_key="pk_ab6548b1284345368ccec6e806e70415")['close']
df2 = pan.DataReader(ticker2, 'av-daily', start, end,
api_key="pk_ab6548b1284345368ccec6e806e70415")['close']
per_ticker1 = df1.pct_change()
per_ticker2 = df2.pct_change()
# Convert pandas series data structure to a dict
datasets = []
ticker1_dict = per_ticker1.to_dict()
dataset1 = {"label":ticker1,
"borderColor": "blue",
"showLine":False,
"pointRadius": 7,
"pointBackgroundColor": "blue",
"data": []}
for d1, per1 in ticker1_dict.items():
if d1 != '2019-11-07':
dataset1["data"].append({"x":d1, "y":per1})
datasets.append(dataset1)
ticker2_dict = per_ticker2.to_dict()
dataset2 = {
"label": ticker2,
"borderColor": "green",
"showLine":False,
"pointRadius": 7,
"pointBackgroundColor": "green",
"data": []
}
for d2, per2 in ticker2_dict.items():
if d2 != '2019-11-07':
dataset2["data"].append({"x":d2, "y":per2})
datasets.append(dataset2)
data_dict = {
"datasets": datasets
}
print(data_dict)
return jsonify(data_dict)
@app.route("/risk_return_analysis.json")
def create_risk_return():
"""Pull all tickers for that user"""
user = User.query.get(session['user_id'])
tickers = user.companies
start = dt.datetime(2019, 11, 10)
end = dt.datetime(2019, 11, 26)
reTurn_list = []
risk_list =[]
data_list = []
ticker_list = []
for each_ticker in tickers:
df = pan.DataReader(each_ticker.ticker, 'av-daily', start, end,
api_key="pk_ab6548b1284345368ccec6e806e70415")['close']
per_ticker = df.pct_change()
reTurn = round(per_ticker.mean(),5)
reTurn_list.append(reTurn)
risk = round(per_ticker.std(),5)
risk_list.append(risk)
data_list.append({"x":reTurn, "y":risk})
ticker_list.append(each_ticker.ticker)
data_dict = {
"datasets": [{
"label": "Risk And Return",
"showLine":False,
"borderColor": "blue",
"pointRadius": 7,
"pointBackgroundColor": "aqua",
"data": data_list
}]
}
return jsonify(data_dict)
@app.route("/sector")
def create_sector():
""" Find a sector which has the highest 1 day performance"""
api_request = requests.get("https://www.alphavantage.co/query?function=SECTOR&apikey=pk_ab6548b1284345368ccec6e806e70415")
sector_p = api_request.json()
list_p = [
sector_p["Rank B: 1 Day Performance"]["Consumer Discretionary"],
sector_p["Rank B: 1 Day Performance"]["Information Technology"],
sector_p["Rank B: 1 Day Performance"]["Health Care"],
sector_p["Rank B: 1 Day Performance"]["Financials"],
sector_p["Rank B: 1 Day Performance"]["Real Estate"],
sector_p["Rank B: 1 Day Performance"]["Energy"],
sector_p["Rank B: 1 Day Performance"]["Materials"],
sector_p["Rank B: 1 Day Performance"]["Consumer Staples"],
sector_p["Rank B: 1 Day Performance"]["Utilities"],
sector_p["Rank B: 1 Day Performance"]["Industrials"]
]
highest_p = max(list_p)
return render_template("sector.html", sector_p = sector_p, highest_p=highest_p)
@app.route("/ticker_lookup")
def lookup_ticker():
""" Help users to find stocks which they want to add to their portfolios"""
key_word = request.args.get('name')
api_name = requests.get("https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords="+
str(key_word) +"&apikey=pk_ab6548b1284345368ccec6e806e70415")
name_api = api_name.json()
return render_template("ticker_lookup.html", name_api=name_api)
if __name__ == "__main__":
# Do not debug for demo
app.debug = False
connect_to_db(app)
# Use the DebugToolbar
DebugToolbarExtension(app)
app.run(host="0.0.0.0")