0

I am working on pset7 finance quote and my code isn't displaying anything in the form that returns the data about the stock to the user. I did some research in the forums and it sounds like there was a change to the API and some updates were needed to helpers.py. I made them but it didn't seem to change anything and I'm wondering if I've made the wrong combination of changes to helpers.py or if it is my code in application.py and the two html templates I created. I actually created a copy of helpers.py called helperstest.py, pulled out everything but the lookup function, added a get_string to input the stock symbol and tried to print what it was returning but it didn't print anything. I tried it with various combinations of the updates to helpers.py but nothing worked.

The things I changed in helpers.py are as follows:

changed:

url = f"https://www.alphavantage.co/query?apikey={os.getenv('API_KEY')}&datatype=csv&function=TIME_SERIES_INTRADAY&interval=1min&symbol={symbol}"

to:

url = f"https://www.alphavantage.co/query?apikey={os.getenv('API_KEY')}&datatype=csv&function=TIME_SERIES_DAILY&interval=1min&symbol={symbol}" 

(i.e., replaced INTRADAY with DAILY)

changed the last part of the try function from:

        return {
        "price": price,
        "symbol": symbol.upper()
    }

to:

        return {
        "name": row[1],
        "price": price,
        "symbol": row[0].upper()
    }

My code for helpers.py, quote function, quote.html and quotedisplay.html are as follows (will make the html pages prettier once it's working under the hood).

helpers.py:

import csv
import os
import urllib.request

from flask import redirect, render_template, request, session
from functools import wraps


def apology(message, code=400):
"""Render message as an apology to user."""
def escape(s):
    """
    Escape special characters.

    https://github.com/jacebrowning/memegen#special-characters
    """
    for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
                     ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
        s = s.replace(old, new)
    return s
return render_template("apology.html", top=code, bottom=escape(message)), code


def login_required(f):
"""
Decorate routes to require login.

http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
    if session.get("user_id") is None:
        return redirect("/login")
    return f(*args, **kwargs)
return decorated_function


def lookup(symbol):
"""Look up quote for symbol."""

# Reject symbol if it starts with caret
if symbol.startswith("^"):
    return None

# Reject symbol if it contains comma
if "," in symbol:
    return None

# Query Alpha Vantage for quote
# https://www.alphavantage.co/documentation/
try:

    # GET CSV
    url = f"https://www.alphavantage.co/query?apikey={os.getenv('API_KEY')}&datatype=csv&function=TIME_SERIES_DAILY&interval=1min&symbol={symbol}"
    webpage = urllib.request.urlopen(url)

    # Parse CSV
    datareader = csv.reader(webpage.read().decode("utf-8").splitlines())

    # Ignore first row
    next(datareader)

    # Parse second row
    row = next(datareader)

    # Ensure stock exists
    try:
        price = float(row[4])
    except:
        return None

    # Return stock's name (as a str), price (as a float), and (uppercased) symbol (as a str)
    return {
        "name": row[1],
        "price": price,
        "symbol": row[0].upper()
    }

except:
    return None


def usd(value):
"""Format value as USD."""
return f"${value:,.2f}"

quote function:

@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""

# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":

    # Make sure fields aren't left blank
    # Else apologize
    if not request.form.get("symbol"):
        # return apology (relevant error message, e.g., "Missing username!")
        return apology("please enter a stock symbol (e.g., AMZN)", 403)
    else:
        quote = lookup("symbol")
        return render_template("quotedisplay.html", displayquote=quote)

else:
    return render_template("quote.html")

quote.html:

{% extends "layout.html" %}

{% block title %}
Quote
{% endblock %}

{% block main %}

<form action="/quote" method="post">
    <div class="form-group">
        <input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="e.g., AMZN" type="text"/>
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>
{% endblock %}

quote display.html

{% extends "layout.html" %}

{% block title %}
Quote Display
{% endblock %}

{% block main %}

<form action="/quotedisplay" method="get">
    <div class="form-group">
        <p>
            QUOTE<br>
            Name: {{ displayquote.name }}<br>
            Price: {{ displayquote.price }}<br>
            Symbol: {{ displayquote.symbol }}<br>
        </p>
    </div>
</form>
{% endblock %}
1
  • After further research I found that I was using some yahoo code. I changed it to return { "name": symbol.upper(), # for backward compatibility with Yahoo "price": price, "symbol": symbol.upper() } but it didn't seem to make a difference.
    – CM23
    Jun 9, 2018 at 18:55

1 Answer 1

1

Never mind. I feel like an idiot. I figured out what was wrong and have now fixed it. I was not calling the lookup function properly.

You must log in to answer this question.

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