Lab 9


How to Submit

Submit what you’ve done for Lab 9 by 2022-03-07T08:30:00-05:00.

  1. Download your Finance HTML, CSS, and Python files from by control-clicking or right-clicking on each file (or the Finance folder) and choosing Download….
  2. Go to the CS50 for MBAs Gradescope page.
  3. Click Lab 9: Finance Part 2.
  4. Drag and drop your files to the area that says “Drag & Drop.”
  5. Click Upload.

If you run into any trouble with the above steps, email!

Adding a visualization with Matplotlib, a Python plotting library

If interested in continuing to work on your site by adding a visualization of historical data, consider following along here!

We’ll first need to add some HTML that will contain the image we’ll eventually render to our user. The below will suffice, by creating an <img> element that has a source image set to static/plot.png. We’ll create plot.png in the static folder soon. The alt tag here simply tells a reader, automated or human, what the image is about.

<div class="container-fluid">
    <img src="static/plot.png" alt="Historical timeseries data for "/>

Where should you add this code, though? Tinker with it once we’ve created our function to render the image!

Below is a definition for create_timeseries, which takes the data returned to us by db.execute and creates a plot of price against time. Some parts still need to be filled in, though! Remember that db.execute returns to us a list of Python dictionaries, where each element in the list corresponds to one row in our SQL table. So stocks, in this instance, is also a list of dictionaries.

You might find the Matplotlib Reference useful!

def create_timeseries(stocks):
    """A helper function to create an image using stock data"""
    x_axis = range() # TODO: The x axis should range from 0 to the number of data points we have.
    y_axis = [] # TODO: the y axis should be a list of prices, one for each data point
    plt.figure(figsize=(8, 4), dpi=100) #
    plt.xlabel() # TODO: Name the x axis
    plt.ylabel() # TODO: Name the y axis
    plt.plot(x_axis, y_axis)

Play with the above and see if you can get something working! If feeling stuck, feel free to email or take a look at the staff solution below.

Want to see the staff's solution?
def create_timeseries(stocks):
    """A helper function to create an image using stock data"""
    x_axis = range(len(stocks))
    y_axis = [stock["price"] for stock in stocks]
    plt.figure(figsize=(8, 4), dpi=100)
    plt.plot(x_axis, y_axis)