1

What am I missing?? from other posts I have read this error typically results from formatting issues. I believe in my code the place to use USD() is on the index page, but it's not resolving the error.

app.py

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""
    # Fetch the user's portfolio and cash balance
    portfolio = db.execute("SELECT symbol, shares FROM portfolio WHERE user_id = ?", session["user_id"])
    cash_balance = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]["cash"]

    # Fetch the current price for each stock and calculate the total value of the holdings
    stocks = []
    total_value = cash_balance

    for row in portfolio:
        stock_info = lookup(row["symbol"])
        current_price = stock_info["price"]
        holding_value = current_price * row["shares"]

        stocks.append({
            "symbol": row["symbol"],
            "shares": row["shares"],
            "price": current_price,
            "value": holding_value,
        })

        total_value += holding_value

    return render_template("index.html", stocks=stocks, cash_balance=usd(cash_balance), total_value=usd(total_value))


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "POST":
        symbol = request.form.get("symbol_input")
        shares = request.form.get("shares")

        # Ensure the symbol is not blank and exists
        if not symbol or not lookup(symbol):
            return apology("Invalid stock symbol", 400)

        # Ensure the shares input is a positive integer
        try:
            shares = int(shares)
            if shares <= 0:
                raise ValueError
        except ValueError:
            return apology("Invalid number of shares", 400)

        # Get the stock's current price
        stock_info = lookup(symbol)
        current_price = stock_info["price"]

        # Get the user's current cash balance
        user_cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]["cash"]

        # Calculate the total cost of the shares
        total_cost = shares * current_price

        # Check if the user can afford the shares
        if user_cash < total_cost:
            return apology("Insufficient funds", 400)

        # Update the user's cash balance
        db.execute("UPDATE users SET cash = cash - ? WHERE id = ?", total_cost, session["user_id"])

        # Insert the transaction into a transactions table
        db.execute("INSERT INTO transactions (user_id, symbol, shares, price, date) VALUES (?, ?, ?, ?, ?)",
                    session["user_id"], symbol, shares, current_price, datetime.now())

        # Update the user's portfolio
        portfolio = db.execute("SELECT shares FROM portfolio WHERE user_id = ? AND symbol = ?", session["user_id"], symbol)

        if len(portfolio) == 0:
            # Insert a new row if the user doesn't own any shares of this stock
            db.execute("INSERT INTO portfolio (user_id, symbol, shares) VALUES (?, ?, ?)", session["user_id"], symbol, shares)
        else:
            # Update the shares count if the user already owns shares of this stock
            db.execute("UPDATE portfolio SET shares = shares + ? WHERE user_id = ? AND symbol = ?", shares, session["user_id"], symbol)

        flash("Purchase successful!")
        return redirect("/")

    return render_template("buy.html")

index.html

    {% extends "layout.html" %}
    
    {% block title %}
        Portfolio
    {% endblock %}

{% block main %}
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Symbol</th>
                <th>Shares</th>
                <th>Current Price</th>
                <th>Total Value</th>
            </tr>
        </thead>
        <tbody>
            {% for stock in stocks %}
                <tr>
                    <td>{{ stock.symbol }}</td>
                    <td>{{ stock.shares }}</td>
                    <td>${{ stock.price|round(2) }}</td>
                    <td>${{ stock.value|round(2) }}</td>
                </tr>
            {% endfor %}
            <tr>
                <td colspan="3"><strong>Cash Balance</strong></td>
                <td><strong>${{ cash_balance }}</strong></td>
            </tr>
            <tr>
                <td colspan="3"><strong>Grand Total</strong></td>
                <td><strong>${{ total_value }}</strong></td>
            </tr>
        </tbody>
    </table>
{% endblock %}
2

0

You must log in to answer this question.

Browse other questions tagged .