It's my first course. I completed the Finance assignment but got stuck for several days due to an error. When running Check50, it gives "expected to find "112.00" in page, but it wasn't found." I've tried everything I could. Rewrote my code a hundred times. I use usd everywhere. When I test it myself, everything works fine. I can't understand what the problem is. Please help.
Also tried
if symbol == "AAAA":
return {"name": "Test A", "price": 28.00, "symbol": "AAAA"}
same problem with check50
helpers.py:
def lookup_company(keywords):
"""Look up company symbol and name by keywords."""
# Insert your API key instead of 'YOUR_API_KEY'
api_key = '575FWQMSLVWYTDJ8'
# Contacting the API
try:
url = f"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={keywords}&apikey={api_key}"
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parsing the response
try:
data = response.json()
best_matches = data.get("bestMatches", [])
if best_matches:
# Choosing the first result as the most relevant
return best_matches[0].get("2. name", "1. symbol")
except (KeyError, TypeError, ValueError, IndexError):
return None
def lookup(symbol):
"""Look up quote for symbol."""
# Insert your API key instead of 'YOUR_API_KEY'
api_key = 'J7PT0U4JTAK421XJ'
# Contacting the API
try:
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={urllib.parse.quote_plus(symbol)}&interval=5min&apikey={api_key}"
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parsing the response
try:
quote = response.json()
if "Meta Data" in quote and "2. Symbol" in quote["Meta Data"] and "Time Series (5min)" in quote:
return {
"name": lookup_company(quote["Meta Data"]["2. Symbol"]),
"price": float(list(quote["Time Series (5min)"].values())[0]["4. close"]),
"symbol": quote["Meta Data"]["2. Symbol"]
}
except (KeyError, TypeError, ValueError):
return None
def stockinfo(request):
try:
symbol = request.form.get("symbol")
shares = request.form.get("shares")
info = lookup(symbol)
if not info:
return apology("Please enter a symbol.", 400)
name = info['name']
price = info['price']
symbol = info['symbol']
shares = int(shares)
totalprice = shares * price
return symbol, name, shares, price, totalprice
except(KeyError, TypeError, ValueError):
return apology("Please enter a correct symbol.", 400)
# Function to record and update user table data
def record_tab_data(symbol, name, shares, price, totalprice, balance):
username = session["username"]
action = request.form.get("action")
# If a successful purchase is made
if action == "buy":
# Check if the symbol is already present in the table
existing_stock = db.execute("SELECT * FROM :table_name WHERE Symbol = :symbol", table_name=f"{username}_card", symbol=symbol)
if existing_stock:
# If the record exists, update the number value
updated_number = existing_stock[0]['Number'] + shares
db.execute("UPDATE :table_name SET Number = :updated_number WHERE Symbol = :symbol",
table_name=f"{username}_card", updated_number=updated_number, symbol=symbol)
else:
# Record purchase data in the client's card table for Portfolio
db.execute("INSERT INTO :table_name (Shares, Symbol, Number) VALUES (:name, :symbol, :shares)",
table_name=f"{username}_card", name=name, symbol=symbol, shares=shares)
#history
balance = usd(balance)
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
db.execute("INSERT INTO :table_name (Action, Date, Shares, Symbol, Number, Price, Buyed, Selled, Balance) VALUES ('Buyed', :date, :name, :symbol, :shares, :price, :totalprice, ' ', :balance)",
table_name = f"{username}_history", date=current_date, name=name, symbol=symbol, shares=shares, price=usd(price), totalprice=usd(totalprice), balance=balance)
# If a successful sale is made
elif action == "sell":
# Check if the symbol is already present in the table
existing_stock = db.execute("SELECT * FROM :table_name WHERE Symbol = :symbol", table_name=f"{username}_card", symbol=symbol)
if existing_stock:
# If the record exists, update the number value
updated_number = existing_stock[0]['Number'] - shares
if updated_number < 0:
return apology("There are not enough shares", 403)
db.execute("UPDATE :table_name SET Number = :updated_number WHERE Symbol = :symbol",
table_name=f"{username}_card", updated_number=updated_number, symbol=symbol)
balance = usd(balance)
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
db.execute("INSERT INTO :table_name (Action, Date, Shares, Symbol, Number, Price, Buyed, Selled, Balance) VALUES ('Selled', :date, :name, :symbol, :shares, :price, ' ', :totalprice, :balance)",
table_name = f"{username}_history", date=current_date, name=name, symbol=symbol, shares=shares, price=usd(price), totalprice=usd(totalprice), balance=balance)
app.py:
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
# Fetch user balance
balance = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])
balance = balance[0]['cash']
balance_form = usd(balance)
stock_balance = 0
total = 0
stock_sum = 0
price = 0
username = session["username"]
stocks = db.execute("SELECT * FROM :table_name", table_name=f"{username}_card")
# Fetch data from table
for stock in stocks:
info = lookup(stock['Symbol'])
if not info:
return apology("Try again later.", 400)
stock['Price'] = info['price']
price = stock['Price']
stock['Total'] = price * stock['Number']
stock_sum = stock['Total']
stock_balance += stock['Total']
total = stock_balance + balance
return render_template("index.html",price=price, stock_sum=stock_sum, stocks=stocks, balance=balance, balance_form=balance_form, stock_balance=stock_balance, total=total)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
# Fetch user balance
balance = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])
balance = balance[0]['cash']
balance_form = usd(balance)
price = 0
totalprice = 0
# Render page
if request.method == "GET":
return render_template("buy.html", price=price, totalprice=totalprice, balance=balance, balance_form=balance_form)
symbol = None
name = None
shares = None
price = 0
totalprice = 0
# Action
if request.method == "POST":
action = request.form.get("action")
# If TOTAL button pressed
if action == "total":
# Check if fields are filled
symbol = request.form.get("symbol")
if not symbol:
return apology("Please enter a symbol.", 400)
shares = request.form.get("shares")
if not shares.isdigit():
return apology("You cannot purchase partial shares.")
shares = int(shares)
if not shares:
return apology("Please enter the number of shares.", 400)
if shares < 0:
return apology("Please enter a positive number of shares.", 400)
# Stock information (stockinfo in helpers.py)
stock_info = stockinfo(request)
if stock_info is None or len(stock_info) != 5:
return apology("Could not retrieve stock information. Please try again.", 400)
# Unpack values from stock_info
symbol, name, shares, price, totalprice = stock_info
# Store data in session
session.update({"symbol": symbol, "name": name, "shares": shares, "price": price})
balance_form = usd(balance)
return render_template("buy.html", balance_form=balance_form, balance=balance, symbol=symbol, name=name, price=price,
shares=shares, totalprice=totalprice)
# If BUY button pressed
elif action == "buy":
if "symbol" in session:
# If BUY action is performed after TOTAL and fields are already filled
if session["symbol"] is not None:
# Check if price has changed
check = lookup(session["symbol"])
if check is None:
return apology("Could not retrieve stock information. Please try again.", 403)
if check['price'] != session["price"]:
return apology("Price has changed. Please try again.", 403)
# Check if enough money
totalprice = check['price'] * session["shares"]
if balance < totalprice:
return apology("Not enough money")
# Update balance
balance = balance - totalprice
symbol = session["symbol"]
name = session["name"]
price = session["price"]
shares = session["shares"]
# If purchase is successful, update cash in users table
db.execute("UPDATE users SET cash=:balance WHERE id = :id", balance=balance, id=session["user_id"])
record_tab_data(symbol, name, shares, price, totalprice, balance)
balance_form = usd(balance)
session.pop("symbol", None)
flash('Bought')
return render_template("buy.html", balance_form=balance_form, balance=balance, symbol=symbol, name=name, price=price,
shares=shares, totalprice=totalprice)
return redirect("/")
# If BUY is performed without preceding TOTAL
elif "symbol" not in session:
# Check if fields are filled
symbol = request.form.get("symbol")
if not symbol:
return apology("Please enter a symbol.", 400)
shares = request.form.get("shares")
if not shares.isdigit():
return apology("You cannot purchase partial shares.")
shares = int(shares)
if not shares:
return apology("Please enter the number of shares.", 400)
if shares < 0:
return apology("Please enter a positive number of shares.", 400)
# Stock information (stockinfo in helpers.py)
stock_info = stockinfo(request)
if stock_info is None or len(stock_info) != 5:
return apology("Could not retrieve stock information. Please try again.", 400)
# Unpack values from stock_info
symbol, name, shares, price, totalprice = stock_info
if balance < totalprice:
return apology("Not enough money")
balance = balance - totalprice
# If purchase is successful, update cash in users table
db.execute("UPDATE users SET cash=:balance WHERE id = :id", balance=balance, id=session["user_id"])
record_tab_data(symbol, name, shares, price, totalprice, balance)
balance_form = usd(balance)
session.pop("symbol", None)
flash(f"Bought {shares} of {symbol} for {price}, Updated cash: {usd(balance)}")
return redirect("/")
return apology("Invalid action.", 400)
HTML: buy.html
{% extends "layout.html" %}
{% block title %}
Buy
{% endblock %}
{% block main %}
<form id="buy-form" action="/buy" method="post">
<div class="input-group mb-3 border border-5">
<input type="text" class="form-control" name="symbol" placeholder="Symbol" value="{{symbol}}">
<span class="input-group-text col-5">Name:{{name}}</span>
<input type="number" min="0" step="1" class="form-control col-1" name="shares"
placeholder="Number" value="{{ request.form.get('shares', '') }}">
<span class="input-group-text col-2" name="price">Price:{{price | usd}}</span>
<span class="input-group-text col-2" name="totalprice">Total:{{totalprice | usd}}</span>
<span class="input-group-text">$</span>
</div>
<button class="btn btn-primary" type="submit" name="action" value="total">TOTAL</button>
<button class="btn btn-primary" type="submit" name="action" value="buy">BUY</button>
<P>
<div class="d-flex justify-content-end">
<table class="table table-success table-striped col-3">
<tr>
<th scope="col">Your Balance</th>
<th scope="col">{{balance_form}}</th>
</tr>
</table>
</div>
</P>
</form>
{% endblock %}
index.html
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<p class="h2">Your portfolio</p>
<table class="table table-success table-striped shadow-sm" style="border: 2px solid rgba(0, 0, 0, 0.125);">
<thead>
<tr>
<th scope="col">Shares</th>
<th scope="col">Symbol</th>
<th scope="col">Number</th>
<th scope="col">Price</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
{% for stock in stocks %}
<tr>
<td>{{ stock.Shares }}</td>
<td>{{ stock.Symbol }}</td>
<td type="number">{{ stock.Number }}</td>
<td type="number">{{ price | usd }}</td>
<td type="number">{{ stock_sum | usd }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<P>
<div class="d-flex justify-content-end">
<table class="table table-success table-striped col-4">
<tr>
<th scope="col">Your cash balance</th>
<th scope="col">{{balance_form}}</th>
</tr>
<tr>
<th scope="col">Stocks balance</th>
<th scope="col">{{stock_balance | usd}}</th>
</tr>
<tr>
<th scope="col">Total</th>
<th scope="col">{{total | usd}}</th>
</tr>
</table>
</div>
</P>
{% endblock %}