-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.py
344 lines (237 loc) · 10.9 KB
/
application.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
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from flask_session import session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
import datetime
from helpers import apology, login_required, lookup, usd
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
#app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
session(app)
# Configure CS50 Library to use SQLite database
db = SQL(os.environ.get("DATABASE_URL"))
# Make sure API key is set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
stocks = db.execute("SELECT company, SUM(quantity) AS quantities FROM buylist WHERE user_id = :u_id GROUP BY company HAVING SUM(quantity) > 0", u_id = session['user_id'])
cash = db.execute("SELECT cash FROM users WHERE id = :u_id", u_id=session['user_id'] )
quotes={}
current_cash = round((cash[0]['cash']), 2)
for stock in stocks:
quotes[stock['company']] = lookup(stock['company'])
return render_template("index.html", quotes=quotes, stocks=stocks, cash=current_cash)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
stocks = ['MSFT', 'AMZN', 'GOOG', 'AAPL', 'FB']
stock_data={}
for a in stocks:
stock_data[a] = lookup(a)
if request.method == "POST":
sym = lookup(request.form.get("symbol"))
if sym == None:
flash("Enter Valid Symbol")
return render_template("buy.html")
else:
user = db.execute("SELECT * FROM users WHERE id = :u_id", u_id = session['user_id'])
funds = float(user[0]['cash'])
no_of_shares = request.form.get("shares")
total_price = float(no_of_shares) * float(sym['price'])
if funds < total_price:
flash("Not enough funds")
return render_template("buy.html")
elif funds >= total_price:
funds -= total_price
update_cash = db.execute("UPDATE users SET cash = :funds WHERE id = :u_id", funds = funds, u_id = session['user_id'])
transaction = db.execute("INSERT INTO buylist(user_id, company, quantity, price, total, trans, transacted) VALUES(:u_id, :comp, :qty, :price, :total, 'BUY', :date)", u_id=session['user_id'], comp=sym['symbol'], qty=no_of_shares, price=sym['price'], total=total_price, date=datetime.datetime.now())
flash("Bought")
return redirect("/")
return render_template("buy.html", stock_data=stock_data)
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
data = db.execute("SELECT company, quantity, price, total, transacted FROM buylist WHERE user_id = :u_id", u_id = session['user_id'])
return render_template("history.html", data=data)
@app.route("/account", methods=["GET", "POST"])
@login_required
def account():
"""Show Account Details"""
if request.method == "POST":
return render_template("change.html")
return render_template("account.html")
@app.route("/change", methods=["GET", "POST"])
@login_required
def change():
"""change password"""
if request.method == "POST":
pass_hash = generate_password_hash(request.form.get("new password"))
current_pass = db.execute("SELECT hash FROM users WHERE id = :u_id", u_id = session['user_id'])
#if new password matches old password
if check_password_hash(current_pass[0]['hash'], request.form.get("new password")):
flash("New Password cannot be same as old password")
return render_template("change.html")
elif not check_password_hash(pass_hash, request.form.get("reconfirm password")):
flash("Passwords do not match")
return render_template("change.html")
elif not request.form.get("new password") or not request.form.get("reconfirm password"):
flash("Password cannot be blank")
return render_template("change.html")
else:
change_password = db.execute("UPDATE users SET hash=:passw WHERE id = :u_id", passw=pass_hash, u_id=session['user_id'])
flash("password successfully changed")
return redirect("/")
return render_template("change.html")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
flash ("Must provide username")
return render_template("login.html")
# Ensure password was submitted
elif not request.form.get("password"):
flash ("Must provide password")
return render_template("login.html")
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
flash ("Invalid username and/or password")
return render_template("login.html")
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/stocks")
@login_required
def stocks():
"""""show top stocks """""
stocks = ['MSFT', 'AMZN', 'GOOG', 'AAPL', 'FB', 'INTC', 'CSCO','CMCSA', 'PEP', 'ADBE', 'NVDA', 'NFLX', 'PYPL', 'COST', 'AMGN', 'AVGO', 'TXN']
stock_data={}
for a in stocks:
stock_data[a] = lookup(a)
return render_template("stocks.html", stock_data=stock_data)
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method =="POST":
sym = lookup(request.form.get("symbol"))
#ensure symbol not empty form and valid
if sym == None:
flash("Enter Valid Symbol")
return render_template("quote.html")
else:
return render_template("show_quote.html", sym=sym)
return render_template("quote.html")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "POST":
#generate password hash
pass_hash = generate_password_hash(request.form.get("password"))
check_user = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
#ensure username submitted
if not request.form.get("username"):
flash("Must Provide Username")
return render_template("register.html")
#return apology("must provide username", 403)
# Ensure password was submitted
elif not request.form.get("password"):
flash("Must Provide Password")
return render_template("register.html")
#return apology("must provide password", 403)
#ensure passwords match
elif request.form.get("password") != request.form.get("reconfirm password"):
flash("passwords do not match")
return render_template("register.html")
#ensure unique username
elif len(check_user) != 0:
flash("Username already taken")
return render_template("register.html")
else:
rows = db.execute("INSERT INTO users(username, hash, cash) VALUES(:username, :pass_hash, 10000)",
username=request.form.get("username"), pass_hash=pass_hash)
flash("Successly Registered, please log in")
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
check_stock = db.execute("SELECT company FROM buylist WHERE user_id = :u_id GROUP BY company HAVING SUM(quantity) > 0", u_id = session['user_id'])
"""Sell shares of stock"""
if request.method == "POST":
#{'name': 'Apple, Inc.', 'price': 110.44, 'symbol': 'AAPL'}
comp = lookup(request.form.get("symbol"))
number = int(request.form.get("shares"))
#check if they that many shares
act_qty = db.execute("SELECT SUM(quantity) AS quantities FROM buylist WHERE user_id = :u_id AND company = :comp", u_id = session['user_id'], comp=comp['symbol'])
amt =db.execute("SELECT cash FROM users WHERE id = :u_id", u_id=session['user_id'])
balance = amt[0]['cash']
act = act_qty[0]['quantities']
if act < number:
flash("Not enough shares")
return render_template("sell.html", check_stock=check_stock)
else:
act -= number
total= float(comp['price']) * number
number = -(number)
new_bal = balance + total
db.execute("INSERT INTO buylist(user_id, company, quantity, price, total, trans, transacted) VALUES(:u_id, :comp, :qty, :price, :total , 'SELL', :date)", u_id=session['user_id'], comp=comp['symbol'], qty=number, price=comp['price'], total=total, date=datetime.datetime.now())
db.execute("UPDATE users SET cash = :cash WHERE id = :u_id", u_id = session['user_id'], cash = new_bal)
flash("Sold")
return redirect("/")
return render_template("sell.html", check_stock=check_stock)
@app.route("/leaderboard")
@login_required
def leaderboard():
ranks = db.execute("SELECT username, cash FROM users ORDER BY cash DESC LIMIT 10;")
return render_template("leaderboard.html", ranks=ranks)
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
# Listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)