2

I have a lot of work from finance 2017, but it seems to use a different API than what I used last year. How do I update my code to use this new API? Or can I just use the one from last year? (I don't remember where/what that API was) So here's my previous code, help with how to update it to work with this API (Hopefully easily to do) would be great, Thanks!

    import os

    from cs50 import SQL
    from flask import Flask, flash, redirect, render_template, request, session
    from flask_session import Session
    from tempfile import mkdtemp
    from werkzeug.exceptions import default_exceptions
    from werkzeug.security import check_password_hash, generate_password_hash

    from helpers import apology, login_required, lookup, usd

    # Ensure environment variable is set
    if not os.environ.get("API_KEY"):
        raise RuntimeError("API_KEY not set")

    # 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("sqlite:///finance.db")


    @app.route("/")
    @login_required
    def index():
        """Show portfolio of stocks"""

    # Once a user makes a purchase they will be redirected to their index page
    # Edit that to reflect the user's portfolio

    # Get symbol, shares, cash from databases
        purchases = db.execute("SELECT stock, SUM(shares) as sumshares FROM transactions WHERE user_id = :user_id GROUP BY stock ORDER BY stock ASC", user_id = session["user_id"])
        usercash = db.execute("SELECT cash FROM users WHERE id = :id", id = session["user_id"])
        usercash = int(usercash[0]["cash"])

        # Declare variable for running total of stock value
    totalvalstock = 0
        # PDHTEFW7T4KOTDHI
        # Purchases query will return dicts, loop to iterate over list of dicts.
    for purchase in purchases:
        purchase['stock'] = purchase["stock"]
        shares = purchase['sumshares']
        purchase['symbol'] = purchase['stock']
        currentstock = lookup(purchase['stock'])
        purchase['price'] = currentstock['price']
        purchase['singlestocktotal'] = purchase['sumshares'] * purchase['price']
        purchase["totalvalstock"] = round(purchase['singlestocktotal'],2)
        totalvalstock += purchase['totalvalstock']

    # calculate total of all stock holdings at their current price and whatever cash the user has left.
    grandtotalstocks = round(totalvalstock,2)
    overalltotal = round(grandtotalstocks + usercash,2)
    # call render_template and pass variables to html template
    return render_template("index.html", purchases=purchases, usercash=usercash, grandtotalstocks=grandtotalstocks,overalltotal=overalltotal,)

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

        shares = float(request.form.get("shares"))
        newshares = float(request.form.get("shares"))
        stock = lookup(request.form.get("symbol"))
        if not stock:
            return apology("Invalid Symbol")

        elif not shares:
            return apology("shares must be more than 0")


        price = stock['price']

        if shares <= 0:
            return apology("shares must be > 0")

        cash_balance = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])

        total_cost = shares * price

        if total_cost <= cash_balance[0]["cash"]:
            user_id = session["user_id"]
            cash_remaining = cash_balance[0]["cash"] - total_cost
            #db.execute("INSERT INTO transactions (user_id, stock, price, num_shares, total_cost) \
            #VALUES (:user_id, :stock, :price, :num_shares, :total_cost)",
            #user_id=session["user_id"], stock=stock, price=price, num_shares=num_shares, total_cost=total_cost)
            #PDHTEFW7T4KOTDHI
            db.execute("INSERT INTO transactions (user_id, stock, price, shares, total_cost) \
            VALUES (:user_id, :stock, :price, :shares, :total_cost)",
            user_id=session["user_id"], stock=stock["symbol"], price=price, shares=shares, total_cost=total_cost),
            db.execute("UPDATE users SET cash=:new_cash WHERE id=:user_id;", new_cash=cash_remaining, user_id=user_id)
            #db.execute("INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares) \
            #ON DUPLICATE KEY UPDATE portfolio set shares = shares + :newshares WHERE user_id = user_id AND stock = stock", \
            #user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)

            db.execute("INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares) \
            ON DUPLICATE KEY UPDATE shares = shares + :newshares", user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)
            db.execute("UPDATE portfolio SET shares = shares + :newshares WHERE user_id = user_id AND stock = stock\
            ", user_id=session["user_id"], stock=stock["symbol"], shares = shares, newshares = newshares)
            #"INSERT INTO portfolio (user_id, stock, shares) VALUES (:user_id, :stock, :shares)", user_id=session["user_id"], stock=stock["symbol"], shares=shares)
            #return apology("good")

        #return apology("Looks good")

            return render_template("buy.html")

        else:
            return apology("You can't afford that many shares")

    else:

        return render_template("buy.html")


    @app.route("/history")
    @login_required
    def history():
        """Show history of transactions"""
        return apology("TODO")


    @app.route("/login", methods=["GET", "POST"])
    def login():
    """Log user in"""

    # Forget any user_id
    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"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # 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")):
            return apology("invalid username and/or password", 403)

        # 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("/quote", methods=["GET", "POST"])
    @login_required
    def quote():
    """Get stock quote."""
    if request.method == "GET":
        return render_template("quote.html")
    else:
        symbol = request.form.get("symbol")
        results= lookup(symbol)
        if not results:
            return apology("invalid stock symbol")
        else:
            return render_template("quoted.html", quoted = results)


    @app.route("/register", methods=["GET", "POST"])
    def register():
    """Register user."""

    session.clear()
    if request.method == "POST": #POST CONDITIONAL

        #eturn render_template("register.html") # TRIED RETURNING TEMPLATE AT START

        if not request.form.get("username"):
            return apology("must provide username")

        elif not request.form.get("password"):
            return apology("must provide password")

        elif not request.form.get("confirmation"):
            return apology("must confirm password")

        elif not request.form.get("password") == request.form.get("confirmation"):
            return apology("password must match password confirmation")

        hash = generate_password_hash(request.form.get("password"))

        result = db.execute("INSERT INTO users (username, hash) VALUES(:username, :hash)", username=request.form.get("username"), hash=hash)
        if not result:
            return apology("username is already taken")

        session["user_id"] = result
        #session["user_id"] = result[0]["id"]

        return render_template("index.html")


    else:
        return render_template("register.html")

    @app.route("/sell", methods=["GET", "POST"])
    @login_required
    def sell():
    """Sell shares of stock"""
    #return apology("TODO")
    # PDHTEFW7T4KOTDHI
    if request.method == "POST":

        shares = int(request.form.get("shares"))
        stock = lookup(request.form.get("symbol"))
        #stockprice = stock['price']
        if not stock:
            return apology("Invalid Symbol")

        if shares <= 0:
            return apology("shares must be > 0")
        amount = int(shares) * stock["price"]

        db.execute("UPDATE users SET cash = cash + :amount WHERE id = :userID", amount=amount, userID=session["user_id"])
        db.execute("INSERT INTO transactions (user_id, stock, shares, amount, price) VALUES (:user_id, :stock, :shares, :amount, :price)", user_id=session["user_id"], stock = stock["symbol"], shares = shares, amount = amount, price = stock["price"])
        db.execute("UPDATE transactions SET shares = shares - :shares WHERE user_id = :user_id AND stock = :stock", shares = shares, user_id=session["user_id"], stock = stock["symbol"])

        return apology("good")

    else:

        return render_template("sell.html")


    def errorhandler(e):
    """Handle error"""
    return apology(e.name, e.code)


    # listen for errors
    for code in default_exceptions:
    app.errorhandler(code)(errorhandler)

1 Answer 1

0

From the 2019 CS50 pset 7 documentation on this page https://docs.cs50.net/2018/x/psets/7/finance/finance.html

while reading the doc i noticed the a new API was introduce other than of last year's. check this section from the doc which says

If you’re not quite sure what it means to buy and sell stocks (i.e., shares of a company), head to http://www.investopedia.com/university/stocks/ for a tutorial.

You’re about to implement C$50 Finance, a web app via which you can manage portfolios of stocks. Not only will this tool allow you to check real stocks' actual prices and portfolios' values, it will also let you buy (okay, "buy") and sell (okay, "sell") stocks by querying IEX for stocks' prices.

Indeed, IEX lets you download stock quotes via URLs like https://api.iextrading.com/1.0/stock/NFLX/quote. Notice how Netflix’s symbol (NFLX) is embedded in this URL; that’s how IEX knows whose data to return.

Let’s turn our attention now to the app’s distribution code!

On checking the API doc i also noticed the API doesnt use authentication which means you dont need API key to access their contents

Authentication

The IEX API is currently open and does not require authentication to access its data.

The pset7 source code in application.py file does have API stuff see below code

import os

from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions
from werkzeug.security import check_password_hash, generate_password_hash

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("sqlite:///finance.db")

So i will recommend you to download the new source code and merge it with yours from http://cdn.cs50.net/2018/x/psets/7/finance/finance.zip

Hope you understood?

4
  • Why am I downloading the 2018 version as the new source code and how do I merge it?
    – Joel Banks
    Commented Mar 3, 2019 at 0:36
  • You are downloading just to update your program, you should merge it by transferring your changes made on old source to the new source.
    – myckhel
    Commented Mar 3, 2019 at 9:47
  • The only part I need now is where to get the API key from the 2018 version. I can't remember where I had to go to find it
    – Joel Banks
    Commented Mar 3, 2019 at 18:32
  • i checked the 2018 finance pset but its same as 2019 i suggest you forget about the former API and use the new one
    – myckhel
    Commented Mar 4, 2019 at 9:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .