I'm working on the index portion of the finance pset. I can't get the stock information to show up in the html table. I'm having a difficult time thinking how to loop through the stock information without having to create a new dictionary with the new data. Could someone help me with this direction that I'm taking? And can someone give me a "better" approach? I feel like this is not the "best" way to solve this problem. Hopefully the code appears correctly, I'm still learning how to use this site.
@app.route("/") @login_required def index():
"""Show portfolio of stocks"""
#set portfolio GROUPED BY symbol
portfolio = db.execute("SELECT symbol, SUM(shares) AS share_total FROM portfolio WHERE user_id = :user_id GROUP BY symbol", user_id = session["user_id"])
row = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])
remaining_cash = row[0]["cash"]
total_holding_value = 0
stock_info = {}
for stock in portfolio:
symbol = stock["symbol"]
shares = stock["share_total"]
quote = lookup(symbol)
price = quote["price"]
holding_value = shares * price
total_holding_value += holding_value
stock_info.update({"symbol":symbol, "shares":shares, "price":price, "holding_value":holding_value})
grand_total = total_holding_value + remaining_cash
return render_template("index.html", stock_info = stock_info, remaining_cash = remaining_cash, grand_total = grand_total)
{% extends "layout.html" %}
{% block title %}
Portfolio
{% endblock %}
{% block main %}
<table class="table table-bordered">
<thead>
<th>Symbol</th>
<th>Shares</th>
<th>Price</th>
<th>Total</th>
</thead>
<tbody>
{% for stock in stock_info %}
<tr>
<td>{{ stock.symbol }}</td>
<td>{{ stock.shares }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.holding_value }}</td>
</tr>
{% endfor %}
<tr>
<td></td>
<td></td>
<td>Remaining Balance:</td>
<td>{{ remaining_cash }}</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Grand Total:</td>
<td>{{ grand_total }}</td>
</tr>
</tbody>
</table>
{% endblock %}
One problem is here stock_info.update({"symbol":symbol, "shares":shares, "price":price, "holding_value":holding_value})
. From the python doc [empashis added].
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
Chances are you want to send a list of dictionaries to the html. Consider declaring stock_info
a list, and using the append
method to add each stock.