<jupyter_start><jupyter_text>Economics 101B Spring 2018 Pre-Semester Exercises Professor DeLong  Our Computing Environment, Jupyter notebooksThis webpage is called a Jupyter notebook. A notebook is a place to write programs and view their results.  Text cellsIn a notebook, each rectangle containing text or code is called a *cell*.Text cells (like this one) can be edited by double-clicking on them. They're written in a simple format called [Markdown](http://daringfireball.net/projects/markdown/syntax) to add formatting and section headings.  You don't need to learn Markdown, but you might want to.After you edit a text cell, click the "run cell" button at the top that looks like ▶| to confirm any changes. (Try not to delete the instructions of the lab.) **Question 1.1.1.** This paragraph is in its own text cell.  Try editing it so that this sentence is the last sentence in the paragraph, and then click the "run cell" ▶| button .  This sentence, for example, should be deleted.  So should this one.  Code cellsOther cells contain code in the Python 3 language. Running a code cell will execute all of the code it contains.To run the code in a code cell, first click on that cell to activate it.  It'll be highlighted with a little green or blue rectangle.  Next, either press ▶| or hold down the `shift` key and press `return` or `enter`.Try running this cell:<jupyter_code>print("Hello, World!")<jupyter_output>Requirement already up-to-date: okpy in /Users/alexchan/anaconda3/lib/python3.5/site-packages
Requirement already up-to-date: requests==2.12.4 in /Users/alexchan/anaconda3/lib/python3.5/site-packages (from okpy)
=====================================================================
Assignment: Intro Notebook
OK, version v1.12.8
=====================================================================<jupyter_text>And this one:<jupyter_code>print("\N{WAVING HAND SIGN}, \N{EARTH GLOBE ASIA-AUSTRALIA}!")<jupyter_output><empty_output><jupyter_text>The fundamental building block of Python code is an expression. Cells can contain multiple lines with multiple expressions. When you run a cell, the lines of code are executed in the order in which they appear. Every `print` expression prints a line. Run the next cell and notice the order of the output.<jupyter_code>print("First this line is printed,")
print("and then this one.")<jupyter_output><empty_output><jupyter_text>**Question 1** Change the cell above so that it prints out:    First this line,    then the whole 🌏,    and then this one.*Hint:* If you're stuck on the Earth symbol for more than a few minutes, try talking to a neighbor or a TA.  That's a good idea for any lab problem.  Writing Jupyter notebooksYou can use Jupyter notebooks for your own projects or documents.  When you make your own notebook, you'll need to create your own cells for text and code.To add a cell, click the + button in the menu bar.  It'll start out as a text cell.  You can change it to a code cell by clicking inside it so it's highlighted, clicking the drop-down box next to the restart (⟳) button in the menu bar, and choosing "Code".**Question 2** Add a code cell below this one.  Write code in it that prints out:       A whole new cell! ♪🌏♪(That musical note symbol is like the Earth symbol.  Its long-form name is `\N{EIGHTH NOTE}`.)Run your cell to verify that it works.  1.4. ErrorsPython is a language, and like natural human languages, it has rules.  It differs from natural language in two important ways:1. The rules are *simple*.  You can learn most of them in a few weeks and gain reasonable proficiency with the language in a semester.2. The rules are *rigid*.  If you're proficient in a natural language, you can understand a non-proficient speaker, glossing over small mistakes.  A computer running Python code is not smart enough to do that.Whenever you write code, you'll make mistakes.  When you run a code cell that has errors, Python will sometimes produce error messages to tell you what you did wrong.Errors are okay; even experienced programmers make many errors.  When you make an error, you just have to find the source of the problem, fix it, and move on.We have made an error in the next cell.  Run it and see what happens.<jupyter_code>print("This line is missing something."<jupyter_output><empty_output><jupyter_text>You should see something like this (minus our annotations):The last line of the error output attempts to tell you what went wrong.  The *syntax* of a language is its structure, and this `SyntaxError` tells you that you have created an illegal structure.  "`EOF`" means "end of file," so the message is saying Python expected you to write something more (in this case, a right parenthesis) before finishing the cell.There's a lot of terminology in programming languages, but you don't need to know it all in order to program effectively. If you see a cryptic message like this, you can often get by without deciphering it.  (Of course, if you're frustrated, ask a neighbor or a TA for help.)Try to fix the code above so that you can run the cell and see the intended message instead of an error.  1.5. Submitting your workAll assignments in the course will be distributed as notebooks like this one, and you will submit your work from the notebook. We will use a system called OK that checks your work and helps you submit. At the top of each assignment, you'll see a cell like the one below that prompts you to identify yourself. Run it and follow the instructions.<jupyter_code># Don't change this cell; just run it. 
# The result will give you directions about how to log in to the submission system, called OK.
# Once you're logged in, you can run this cell again, but it won't ask you who you are because
# it remembers you. However, you will need to log in once per assignment.
from client.api.notebook import Notebook
ok = Notebook('intro.ok')
_ = ok.auth(force=True, inline=True)<jupyter_output><empty_output><jupyter_text>When you finish an assignment, you need to submit it by running the submit command below. It's OK to submit multiple times, OK will only try to grade your final submission for each assignment. Don't forget to submit your lab assignment at the end of section, even if you haven't finished everything.<jupyter_code>_ = ok.submit()<jupyter_output><empty_output><jupyter_text>Now that you are comfortable with our computing environment, we are going to be moving into more of the fundamentals of Python, but first, run the cell below to ensure all the libraries needed for this notebook are installed.<jupyter_code>!pip install numpy
!pip install pandas
!pip install sklearn
!pip install seaborn
!pip install matplotlib
!pip install -U okpy
# imports
import numpy as np
import pandas as pd
import seaborn as sns
import ipywidgets as widgets
from ipywidgets import interact
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Here is how to make an interactive model:<jupyter_code># make a function that takes in parameter[s] and graphs
# stick that into interact<jupyter_output><empty_output><jupyter_text>Introduction to programming conceptsWelcome to 101B! This introductory notebook will familiarize you with some of the basic strategies for data analysis that will be useful to you throughout the course. Once you have completed setting up Python on your computer using `pip install`, move on to the next cells to begin.  Part 1: Python basicsBefore getting into the more advanced analysis techniques that will be required in this course, we need to brush up on a few of the foundational elements of programming in Python. A. ExpressionsThe departure point for all programming is the concept of the __expression__. An expression is a combination of variables, operators, and other Python elements that the language interprets and acts upon. Expressions act as a set of instructions to be fed through the interpreter, with the goal of generating specific outcomes. See below for some examples of basic expressions.<jupyter_code>### Examples of expressions:
a = 4
b = 10/5
### The two expressions above do not return anything – they simply store values to the computer.

### An expression that returns an output:
print(a + b)<jupyter_output>6.0<jupyter_text>B. VariablesIn the examples above, `a` and `b` are specific Python objects known as __variables__. The first two lines set the variables equal to numerical (one `integer` and one `float`) values, while the final line asks the interpreter to `print` their sum. Variables are stored within the notebook's environment, meaning stored variable values carry over from cell to cell.<jupyter_code>### Notice that 'a' retains its value.
print(a)<jupyter_output>4<jupyter_text>Question 1: VariablesSee if you can write a series of expressions that creates two new variables called __x__ and __y__, assigns them values of __10.5__ and __7.2__, then prints their product.<jupyter_code>### Fill in the missing lines to complete the expressions.
x = ...
...

print()<jupyter_output><jupyter_text>C. ListsThe next topic is particularly useful in the kind of data manipulation that you will see throughout 101B. The following few cells will introduce the concept of __lists__ (and their counterpart, `numpy arrays`). Read through the following cell to understand the basic structure of a list.<jupyter_code>### A list is initialized like this:
lst = [1, 3, 6, 'lists', 'are' 'fun', 4]

### And elements are selected like this:
example = lst[2]

### The above line selects the 3rd element of lst (list indices are 0-offset) and sets it to a variable named example.
print(example)<jupyter_output>6<jupyter_text>Slicing listsAs you can see from above, lists do not have to be made up of elements of the same kind. Indices do not have to be taken one at a time, either. Instead, we can take a slice of indices and return the elements at those indices as a separate list.<jupyter_code>### This line will store the first (inclusive) through fourth (exclusive) elements of lst as a new list called lst_2:
lst_2 = lst[1:4]

lst_2<jupyter_output><empty_output><jupyter_text>Question 2: ListsBuild a list of length 10 containing whatever elements you'd like. Then, slice it into a new list of length five using a index slicing. Finally, print the last element in your sliced list.<jupyter_code>### Fill in the ellipses to complete the question.
my_list = ...

my_list_sliced = my_list[...]

print(...)<jupyter_output><empty_output><jupyter_text>Lists can also be operated on with a few built-in analysis functions. These include `min` and `max`, among others. Lists can also be concatenated together. Find some examples below.<jupyter_code>### A list containing six integers.
a_list = [1, 6, 4, 8, 13, 2]

### Another list containing six integers.
b_list = [4, 5, 2, 14, 9, 11]

print('Max of a_list:', max(a_list))
print('Min of b_list:', min(a_list))

### Concatenate a_list and b_list:
c_list = a_list + b_list
print('Concatenated:', c_list)<jupyter_output>Max of a_list: 13
Min of b_list: 1
Concatenated: [1, 6, 4, 8, 13, 2, 4, 5, 2, 14, 9, 11]<jupyter_text>D. Numpy ArraysClosely related to the concept of a list is the array, a nested sequence of elements that is structurally identical to a list. Arrays, however, can be operated on arithmetically with much more versatility than regular lists. For the purpose of later data manipulation, we'll access arrays through Numpy, which will require an installation and an import statement.To install numpy, open your terminal and use the command:> `pip install numpy`Now run the next cell to import the numpy library into your notebook, and examine how numpy arrays can be used.<jupyter_code>import numpy as np
### Initialize an array of integers 0 through 9.
example_array = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

### This can also be accomplished using np.arange
example_array_2 = np.arange(10)

### Double the values in example_array and print the new array.
double_array = example_array*2
double_array<jupyter_output><empty_output><jupyter_text>E. LoopingLoops are often useful in manipulating, iterating over, or transforming large lists and arrays. The first type we will discuss is the __for loop__. For loops are helpful in traversing a list and performing an action at each element. For example, the following code moves through every element in example_array, adds it to the previous element in example_array, and copies this sum to a new array.<jupyter_code>new_list = []

for element in example_array:
    new_element = element + 5
    new_list.append(new_element)

new_list<jupyter_output><empty_output><jupyter_text>The most important line in the above cell is the "`for element in...`" line. This statement sets the structure of our  loop, instructing the machine to stop at every number in `example_array`, perform the indicated operations, and then move on. Once Python has stopped at every element in `example_array`, the loop is completed and the final line, which outputs `new_list`, is executed. It's important to note that "element" is an arbitrary variable name used to represent whichever index value the loop is currently operating on. We can change the variable name to whatever we want and achieve the same result, as long as we stay consistent. For example:<jupyter_code>newer_list = []

for completely_arbitrary_name in example_array:
    newer_element = completely_arbitrary_name + 5
    newer_list.append(newer_element)
    
newer_list<jupyter_output><empty_output><jupyter_text>For loops can also iterate over ranges of numerical values. If I wanted to alter `example_array` without copying it over to a new list, I would use a numerical iterator to access list indices rather than the elements themselves. This iterator, called `i`, would range from 0, the value of the first index, to 9, the value of the last. I can make sure of this by using the built-in `range` and `len` functions.<jupyter_code>for i in range(len(example_array)):
    example_array[i] = example_array[i] + 5

example_array<jupyter_output><empty_output><jupyter_text>Other types of loopsThe __while loop__ repeatedly performs operations until its conditional is no longer satisfied. In the below example, an array of integers 0 to 9 is generated. When the program enters the while loop on the subsequent line, it notices that the maximum value of the array is less than 50. Because of this, it adds 1 to the fifth element, as instructed. Once the instructions embedded in the loop are complete, the program refers back to the conditional. Again, the maximum value is less than 50. This process repeats until the the fifth element, now the maximum value of the array, is equal to 50, at which point the conditional is no longer true and the loop breaks.<jupyter_code>while_array = np.arange(10)        # Generate our array of values

print('Before:', while_array)

while(max(while_array) < 50):      # Set our conditional
    while_array[4] += 1            # Add 1 to the fifth element if the conditional is satisfied 
    
print('After:', while_array)<jupyter_output>Before: [0 1 2 3 4 5 6 7 8 9]
After: [ 0  1  2  3 50  5  6  7  8  9]<jupyter_text>Question 3: LoopsIn the following cell, partial steps to manipulate an array are included. You must fill in the blanks to accomplish the following: 1. Iterate over the entire array, checking if each element is a multiple of 52. If an element is not a multiple of 5, add 1 to it repeatedly until it is3. Iterate back over the list and print each element.> Hint: To check if an integer `x` is a multiple of `y`, use the modulus operator `%`. Typing `x % y` will return the remainder when `x` is divided by `y`. Therefore, (`x % y != 0`) will return `True` when `y` __does not divide__ `x`, and `False` when it does.<jupyter_code>### Make use of iterators, range, length, while loops, and indices to complete this question.
question_3 = np.array([12, 31, 50, 0, 22, 28, 19, 105, 44, 12, 77])

for i in range(len(...)):
    while(...):
        question_3[i] = ...
        
for element in question_3:
    print(...)<jupyter_output><empty_output><jupyter_text>F. Functions!Functions are useful when you want to repeat a series of steps on multiple different objects, but don't want to type out the steps over and over again. Many functions are built into Python already; for example, you've already made use of `len()` to retrieve the number of elements in a list. You can also write your own functions, though, and at this point you already have the skills to do so. Functions generally take a set of __parameters__, which define the objects they will use when they are run. For example, the `len()` function takes a list or array as its parameter, and returns the length of that list. The following cell gives an example of an extremely simple function, called `add_two`, which takes as its parameter an integer and returns that integer with, you guessed it, 2 added to it.<jupyter_code># An adder function that adds 2 to the given n.
def add_two(n):
    return n + 2
add_two(5)<jupyter_output><empty_output><jupyter_text>Easy enough, right? Let's look at a function that takes two parameters, compares them somehow, and then returns a boolean value (`True` or `False`) depending on the comparison. The `is_multiple` function below takes as parameters an integer `m` and an integer `n`, checks if `m` is a multiple of `n`, and returns `True` if it is. Otherwise, it returns `False`.<jupyter_code>def is_multiple(m, n):
    if (m % n == 0):
        return True
    else:
        return False
is_multiple(12, 4)
is_multiple(12, 7)<jupyter_output><empty_output><jupyter_text>Since functions are so easily replicable, we can include them in loops if we want. For instance, our `is_multiple` function can be used to check if a number is prime! See for yourself by testing some possible prime numbers in the cell below.<jupyter_code># Change possible_prime to any integer to test its primality
# NOTE: If you happen to stumble across a large (> 8 digits) prime number, the cell could take a very, very long time
# to run and will likely crash your kernel. Just click kernel>interrupt if it looks like it's caught.

possible_prime = 9999991

for i in range(2, possible_prime):
    if (is_multiple(possible_prime, i)):
        print(possible_prime, 'is not prime')   
        break
    if (i >= possible_prime/2):
        print(possible_prime, 'is prime')
        break<jupyter_output>9999991 is prime<jupyter_text>Question 4: Writing functionsIn the following cell, complete a function that will take as its parameters a list and two integers x and y, iterate through the list, and replace any number in the list that is a multiple of x with y.> Hint: use the is_multiple() function to streamline your code.<jupyter_code>def replace_with_y(lst, x, y):
    for i in range(...):
        if(...):
            ...
    return lst<jupyter_output><empty_output><jupyter_text>Pandas DataframesWe will be using Pandas dataframes for much of this class to organize and sort through economic data. Pandas is one of the most widely used Python libraries in data science. It is mainly used for data cleaning, and with good reason: it’s very powerful and flexible, among many other things.  Creating dataframesThe rows and columns of a pandas dataframe are essentially a collection of lists stacked on top/next to each other. For example, if I wanted to store the top 10 movies and their ratings in a datatable, I could create 10 lists that each contain a rating and a corresponding title, and these lists would be the rows of the table:<jupyter_code>top_10_movies = pd.DataFrame(data=np.array(
            [[9.2, 'The Shawshank Redemption (1994)'],
            [9.2, 'The Godfather (1972)'],
            [9., 'The Godfather: Part II (1974)'],
            [8.9, 'Pulp Fiction (1994)'],
            [8.9, "Schindler's List (1993)"],
            [8.9, 'The Lord of the Rings: The Return of the King (2003)'],
            [8.9, '12 Angry Men (1957)'],
            [8.9, 'The Dark Knight (2008)'],
            [8.9, 'Il buono, il brutto, il cattivo (1966)'],
            [8.8, 'The Lord of the Rings: The Fellowship of the Ring (2001)']]), columns=["Rating", "Movie"])
top_10_movies<jupyter_output><empty_output><jupyter_text>Alternatively, we can store data in a dictionary instead of in lists. A dictionary keeps a mapping of keys to a set of values, and each key is unique. Using our top 10 movies example, we could create a dictionary that contains ratings a key, and movie titles as another key.<jupyter_code>top_10_movies_dict = {"Rating" : [9.2, 9.2, 9., 8.9, 8.9, 8.9, 8.9, 8.9, 8.9, 8.8], 
                      "Movie" : ['The Shawshank Redemption (1994)',
                                'The Godfather (1972)',
                                'The Godfather: Part II (1974)',
                                'Pulp Fiction (1994)',
                                "Schindler's List (1993)",
                                'The Lord of the Rings: The Return of the King (2003)',
                                '12 Angry Men (1957)',
                                'The Dark Knight (2008)',
                                'Il buono, il brutto, il cattivo (1966)',
                                'The Lord of the Rings: The Fellowship of the Ring (2001)']}<jupyter_output><empty_output><jupyter_text>Now, we can use this dictionary to create a table with columns `Rating` and `Movie`<jupyter_code>top_10_movies_2 = pd.DataFrame(data=top_10_movies_dict, columns=["Rating", "Movie"])
top_10_movies_2<jupyter_output><empty_output><jupyter_text>Notice how both ways return the same table! However, the list method created the table by essentially taking the lists and making up the rows of the table, while the dictionary method took the keys from the dictionary to make up the columns of the table. In this way, dataframes can be viewed as a collection of basic data structures, either through collecting rows or columns.   Reading in DataframesLuckily for you, most datatables in this course will be premade and given to you in a form that is easily read into a pandas method, which creates the table for you. A common file type that is used for economic data is a Comma-Separated Values(.csv) file, which stores tabular data. It is not necessary for you to know exactly how .csv files store data, but you should know how to read a file in as a pandas dataframe.  We will read in a .csv file that contains quarterly real GDI, real GDP, and nominal GDP data in the U.S. from 1947 to the present.<jupyter_code>### Run this cell to read in the table
accounts = pd.read_csv("data/Quarterly_Accounts.csv")<jupyter_output><empty_output><jupyter_text>The `pd.read_csv` function expects a path to a .csv file as its input, and will return a datatable created from the data contained in the csv.We have provided `Quarterly_Accouunts.csv` in the data directory, which is all contained in the current working directory (aka the folder this assignment is contained in). For this reason, we must specify to the `read_csv` function that it should look for the csv in the data directory, and the `/` indicates that `Quarterly_Accounts.csv` can be found there. Here is a sample of some of the rows in this datatable:<jupyter_code>accounts.head()<jupyter_output><empty_output><jupyter_text>Indexing DataframesOftentimes, tables will contain a lot of extraneous data that muddles our datatables, making it more difficult to quickly and accurately obtain the data we need. To correct for this, we can select out columns or rows that we need by indexing our dataframes.  The easiest way to index into a table is with square bracket notation. Suppose you wanted to obtain all of the Real GDP data from the data. Using a single pair of square brackets, you could index the table for `"Real GDP"`<jupyter_code>## Run this cell and see what it outputs
accounts["Real GDP"]<jupyter_output><empty_output><jupyter_text>Notice how the above cell returns an array of all the real GDP values in their original order.Now, if you wanted to get the first real GDP value from this array, you could index it with another pair of square brackets:<jupyter_code>accounts["Real GDP"][0]<jupyter_output><empty_output><jupyter_text>Keep in mind that pandas dataframes, as well as many other data structures, are zero-indexed, meaning indexes start at 0 and end at the number of elements minus one.  If you wanted to create a new datatable with select columns from the original table, you can index with double brackets.<jupyter_code>## Note: .head() returns the first five rows of the table
accounts[["Year", "Quarter", "Real GDP", "Real GDI"]].head()<jupyter_output><empty_output><jupyter_text>You can also use column indices instead of names.<jupyter_code>accounts[[0, 1, 2, 3]].head()<jupyter_output><empty_output><jupyter_text>Alternatively, you can also get rid of columns you dont need using `.drop()`<jupyter_code>accounts.drop("Nominal GDP", axis=1).head()<jupyter_output><empty_output><jupyter_text>Finally, you can use square bracket notation to index rows by their indices with a single set of brackets. You must specify a range of values for which you want to index. For example, if I wanted the 20th to 30th rows of `accounts`:<jupyter_code>accounts[20:31]<jupyter_output><empty_output><jupyter_text>Filtering DataAs you can tell from the previous, indexing rows based on indices is only useful when you know the specific set of rows that you need, and you can only really get a range of entries. Working with data often involves huge datasets, making it inefficient and sometimes impossible to know exactly what indices to be looking at. On top of that, most data analysis concerns itself with looking for patterns or specific conditions in the data, which is impossible to look for with simple index based sorting.    Thankfully, you can also use square bracket notation to filter out data based on a condition. Suppose we only wanted real GDP and nominal GDP data from the 21st century:<jupyter_code>accounts[accounts["Year"] >= 2000][["Real GDP", "Nominal GDP"]]<jupyter_output><empty_output><jupyter_text>The `accounts` table is being indexed by the condition `accounts["Year"] >= 2000`, which returns a table where only rows that have a "Year" greater than $2000$ is returned. We then index this table with the double bracket notation from the previous section to only get the real GDP and nominal GDP columns. Suppose now we wanted a table with data from the first quarter, and where the real GDP was less than 5000 or nominal GDP is greater than 15,000.<jupyter_code>accounts[(accounts["Quarter"] == "Q1") & ((accounts["Real GDP"] < 5000) | (accounts["Nominal GDP"] > 15000))]<jupyter_output><empty_output><jupyter_text>Many different conditions can be included to filter, and you can use `&` and `|` operators to connect them together. Make sure to include parantheses for each condition! Another way to reorganize data to make it more convenient is to sort the data by the values in a specific column. For example, if we wanted to find the highest real GDP since 1947, we could sort the table for real GDP:<jupyter_code>accounts.sort_values("Real GDP")<jupyter_output><empty_output><jupyter_text>But wait! The table looks like it's sorted in increasing order. This is because `sort_values` defaults to ordering the column in ascending order. To correct this, add in the extra optional parameter<jupyter_code>accounts.sort_values("Real GDP", ascending=False)<jupyter_output><empty_output><jupyter_text>Now we can clearly see that the highest real GDP was attained in the first quarter of this year, and had a value of 16903.2  Useful Functions for Numeric DataHere are a few useful functions when dealing with numeric data columns.To find the minimum value in a column, call `min()` on a column of the table.<jupyter_code>accounts["Real GDP"].min()<jupyter_output><empty_output><jupyter_text>To find the maximum value, call `max()`.<jupyter_code>accounts["Nominal GDP"].max()<jupyter_output><empty_output><jupyter_text>And to find the average value of a column, use `mean()`.<jupyter_code>accounts["Real GDI"].mean()<jupyter_output><empty_output><jupyter_text>Part 2: Visualization and Regression Now that you have completed the Python tutorial, you are now ready to learn about how to visualize data and how to analyze data with regression. To begin, run the cells below to import the required packages we will be using for this tutorial.<jupyter_code>%matplotlib inline
import numpy as np 
import pandas as pd
import sklearn as sk 
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>We will be using the US unemployment data from https://fred.stlouisfed.org/ show what we can do with data. Let's start by importing the .csv file data with pandas. The statement below will put the csv file into a pandas DataFrame, a data structure for holding tabular (2D) data.<jupyter_code>unemployment_data = pd.read_csv("data/detailed_unemployment.csv")
unemployment_data<jupyter_output><empty_output><jupyter_text>We can start visualizing the data that we have in the table. First, we convert the table into a numpy array. Let's extract the columns that we are interested in and plot them with pyplot.<jupyter_code>#Once this cell is run, the "data" variable will store the table and can be accessed from any cell 
data = np.array(unemployment_data[:len(unemployment_data)-1])

#data[:, col_num] means take select all row values in that column number in numpy
total_unemployed = data[:, 1]
not_labor = data[:, 3]

#Plot the data by inputting the x and y axis
plt.scatter(total_unemployed, not_labor)
plt.xlabel("Percent Unemployed")
plt.ylabel("Total Not In Labor, Searched for Work")
plt.show()<jupyter_output><empty_output><jupyter_text>Question 5: PlottingTry plotting the total percent of people unemployed vs those unemployed for more than 15 weeks.<jupyter_code>total_unemployed = ...
unemp_15_weeks = ...

plt.scatter(total_unemployed, unemp_15_weeks)
plt.xlabel("Percent Unemployed")
plt.ylabel("Total Unemployed for > 15 Weeks")
plt.show()
ok.grade('q05')<jupyter_output><empty_output><jupyter_text>Now that we know how to select and plot our data, we are ready to dive into regression. For our current task, let's use the total unemployed and housing price index columns.<jupyter_code>total_unemployed = data[:,1]
hpi = data[:,7]

plt.scatter(total_unemployed, hpi)
plt.xlabel("Percent Unemployed")
plt.ylabel("Housing Price Index")
plt.show()<jupyter_output><empty_output><jupyter_text>The Scikit Learn library has lots of helpful tools for regression tasks. We will perform linear regression on our data with the imported LinearRegression class. The .fit(x, y) method fits the model to the input data and y values and saves it to that instance of the model. We can then use the .predict(x) method to predict the values of the input data from the model.<jupyter_code>from sklearn.linear_model import LinearRegression

model = LinearRegression()
#We set x and y to our column values, and use np.reshape so that
#the data is formatted correctly to be input into the model
x = total_unemployed
x = np.reshape(x, (73,1))
y = hpi

model.fit(x, y)
y_ = model.predict(x)

plt.scatter(x, y)
plt.plot(x, y_)
plt.xlabel("Percent Unemployed")
plt.ylabel("Housing Price Index")
plt.show()<jupyter_output><empty_output><jupyter_text>You can also use your linear regression model to predict values based on your current data. For example, if we wanted to predict the housing price index at an 18% unemployment rate:<jupyter_code>#The predict method returns an array of length 1, so let's take the first element since it's our predicted value
prediction = model.predict(18)[0]
prediction<jupyter_output><empty_output><jupyter_text>Question 6: RegressionLet's make a regression model to predict the total number of people unemployed for more than 15 weeks based on the total percent of people unemployed. Then, let's make a prediction on the number of people unemployed for more than 15 weeks if the unemployment rate was 20%.<jupyter_code>#Initialize the model
model = ...

#Set up our x and y variables using columns from earlier 
x = ...
x = np.reshape(x, (73, 1))
y = ...

#Fit our model to the data and store y_ values for our regression line
#INSERT CODE HERE
y_ = ...

plt.scatter(x, y)
plt.plot(x, y_)
plt.xlabel("Percent Unemployed")
plt.ylabel("Total Unemployed for > 15 Weeks")
plt.show()
#Make your prediction here
prediction = model.predict(20)[0]
prediction
ok.grade('q06')<jupyter_output><empty_output><jupyter_text>Congratulations! You have completed the regression tutorial. Try importing your own datasets and using regression to analyze your data.  Chapter 1: Introduction to Macroeconomics  Suppose a quantity grows at a steady proportional rate of 3% per year. How long will it take to double?<jupyter_code># ANSWER
TIME_TO_DOUBLE = ___<jupyter_output><empty_output><jupyter_text>Quadruple?<jupyter_code># ANSWER
TIME_TO_QUADRUPLE = ___<jupyter_output><empty_output><jupyter_text>Grow 1024-fold?<jupyter_code># ANSWER
TIME_TO_1024 = ___<jupyter_output><empty_output><jupyter_text>Suppose we have a quantity x(t) that varies over time following the equation: $\frac{dx(t)}{dt} = -(0.06)t + 0.36$ Without integrating the equation:$1.$ Tell me what the long-run steady-state value of $x$--that is, the limit of $x$ as $t$ approaches in infinity--is going to be.<jupyter_code>steady_state_val = ___<jupyter_output><empty_output><jupyter_text>$2.$ Suppose that the value of $x$ at time $t=0$, $x(0)$ equals 12. Once again, without integrating the equation, tell me how long it will take x to close half the distance between its initial value of 12 and its steady-state value.<jupyter_code>half_dist_time = ___<jupyter_output><empty_output><jupyter_text>$3.$ How long will it take to close 3/4 of the distance?<jupyter_code>three_fourth_time = ___<jupyter_output><empty_output><jupyter_text>$4.$ $7/8$ of the distance?<jupyter_code>seven_eighth_time = ___<jupyter_output><empty_output><jupyter_text>$5.$ $15/16$ of the distance?<jupyter_code>fifteen_sixteenth = ___<jupyter_output><empty_output><jupyter_text>Now you are allowed to integrate $\frac{dx(t)}{dt} = -(0.06)t + 0.36$.$1.$ Write down and solve the indefinite integral.  ANSWER: here is an integral $2.$ Write down and solve the definite integral for the initial condition $x(0) = 12$.  ANSWER: $3.$ Write down and solve the definite integral for the initial condition $x(0) = 6$.  ANSWER:  Suppose we have a quantity $z = (\frac{x}{y})^\beta$Suppose $x$ is growing at 4% per year and that $\beta=1/4$:$1.$ How fast is $z$ growing if $y$ is growing at 0% per year?<jupyter_code>zero_per_growth = ___<jupyter_output><empty_output><jupyter_text>$2.$ If $y$ is growing at 2% per year?<jupyter_code>two_per_growth = ___<jupyter_output><empty_output><jupyter_text>$3.$ If $y$ is growing at 4% per year?<jupyter_code>four_per_growth = ___<jupyter_output><empty_output><jupyter_text>Rule of 721. If a quantity grows at about 3% per year, how long will it take to double?<jupyter_code>time_to_double = ___<jupyter_output><empty_output><jupyter_text>$2.$ If a quantity shrinks at about 4% per year, how long will it take it to halve itself?<jupyter_code>time_to_half = ___<jupyter_output><empty_output><jupyter_text>$3.$ If a quantity doubles five times, how large is it relative to its original value?<jupyter_code>doubled_five_times_ratio = ___<jupyter_output><empty_output><jupyter_text>$4.$ If a quantity halves itself three times, how large is it relative to its original value?<jupyter_code>halved_three_times_ratio = ___<jupyter_output><empty_output><jupyter_text>Show the relationship between the interest rate and the amount of time it takes to double graphically<jupyter_code>def graph(interest_rate):
    x = np.linspace(1,10,30)
    y = 72 / x
    
    print('Time to double:', 72 / interest_rate, 'years')
    
    plt.plot(x,y)
    plt.scatter(interest_rate, 72 / interest_rate, c='r')
    
    plt.xlabel('interest rate (%)')
    plt.ylabel('time (years)')
interact(graph, interest_rate=widgets.IntSlider(min=1,max=10,step=1))<jupyter_output>Time to double: 72.0 years<jupyter_text>How close is this to the actual formula? (EXPAND)  Why do DeLong and Olney think that the interest rate and the level of the stock market are important macroeconomic variables?  ANSWER:  What are the principal flaws in using national product per worker as a measure of material welfare? Given these flaws, why do we use it anyway?  ANSWER:  What is the difference between the nominal interest rate and the real interest rate? Why do DeLong and Olney think that the real interest rate is more important?  ANSWER:  Chapter 2: Measuring the Macroeconomy  National Income and Product AccountingExplain whether or not, why, and how the following items are included in the calculations of national product:$1.$ Increases in business inventories.   ANSWER: $2.$ Fees earned by real estate agents on selling existing homes.  ANSWER: $3.$ Social Security checks written by the government.   ANSWER: $4.$ Building of a new dam by the Army Corps of Engineers.  ANSWER: $5.$ Interest that your parents pay on the mortgage they have on their house.  ANSWER: $6.$ Purchases of foreign-made trucks by American residents  ANSWER:  In or Out of National Product? And WhyExplain whether or not, why, and how the following items are included in the calculation of national product:$1.$ The sale for \$25,000 of an automobile that cost \$20,000 to manufacture that had been produced here at home last year and carried over in inventory.  ANSWER: $2.$ The sale for \$35,000 of an automobile that cost \$25,000 to manufacture newly- made at home this year.  ANSWER: $3.$ The sale for \$45,000 of an automobile that cost \$30,000 to manufacture that was newly-made abroad this year and imported.  ANSWER: $4.$ The sale for \$25,000 of an automobile that cost \$20,000 to manufacture that was made abroad and imported last year.  ANSWER:  In or Out of National Product? And Why IIExplain whether or not, why, and how the following items are included in the calculation of GDP:$1.$ The purchase for \$500 of a dishwasher produced here at home this year.  ANSWER: $2.$ The purchase for $500 of a dishwasher made abroad this year.  ANSWER: $3.$ The purchase for $500 of a used dishwasher.  ANSWER: $4.$ The manufacture of a new dishwasher here at home for $500 of a dishwasher thatthen nobody wants to buy.  ANSWER:  Components of National Income and ProductSuppose that the appliance store buys a refrigerator from the manufacturer on December 15, 2018 for \$600, and that you then buy that refrigerator on January 15, 2019 for \$1000:$1.$ What is the contribution to GDP in 2018?<jupyter_code>contribution_2018 = ___<jupyter_output><empty_output><jupyter_text>$2.$ How is the refrigerator accounted for in the NIPA in 2019?  ANSWER: nka;sldkf;ohwalk;ldfh;la lna;sldjfn;landf;llajsndf;lankjsd;fljknasd;fljljsnd;fl $3.$ What is the contribution to GDP in 2018?<jupyter_code>contribution_2019 = ___<jupyter_output><empty_output><jupyter_text>$4.$ How is the refrigerator accounted for in the NIPA in 2019?  ANSWER:<jupyter_code>## These lines are reading in CSV files and creating datatables from then, you don't have to worry about them! ##
unemployment = pd.read_csv("data/Unemployment.csv")
quarterly_acc = pd.read_csv("data/Quarterly_Accounts.csv")
from_2007 = quarterly_acc.loc[(quarterly_acc["Year"].isin(np.arange(2007, 2018)))]<jupyter_output><empty_output><jupyter_text>Estimating National ProductThe Bureau of Economic Analysis measures national product in two different ways: as total expenditure on the economy’s output of goods and services and as the total income of everyone in the economy. Since – as you learned in earlier courses – these two things are the same, the two approaches should give the same answer. But in practice they do not.We have provided a data table `quarterly_gdp` that contains quarterly data on real GDP measured on the expenditure side (referred to in the National Income and Product Accounts as “Real Gross Domestic Product, chained dollars”) and real GDP measured on the income side (referred to as “Real Gross Domestic Income, chained dollars”). The table refers to Real Gross Dometic Product as "Real GDP" and to Real Gross Dometic Income as "Real GDI", and they are measured in billions of dollars. (Note: You will not have to use Nominal GDP) Another table, `from_2007`, has been created from `quarterly_gdp`, and includes information from 2007 to 2017. Below is a snippet from `from_2007`:<jupyter_code>from_2007.head(10)<jupyter_output><empty_output><jupyter_text>$1.$ Compute the growth rate at an annual rate of each of the two series by quarter for2007:Q1–2012:Q4.<jupyter_code>gdi_rate = ___
gdp_rate = ___<jupyter_output><empty_output><jupyter_text>$2.$ Describe any two things you see when you compare the two series that you findinteresting, and explain why you find them interesting.  ANSWER:  Calculating Real Magnitudes:$1.$ When you calculate real national product, do you do so by dividing nominal national product by the price level or by subtracting the price level from nominal national product?   ANSWER: $2.$ When you calculate the real interest rate, do you do so by dividing the nominal interest rate by the price level or by subtracting the inflation rate from the nominal interest rate?   ANSWER: $3.$ Are your answers to (a) and (b) the same? Why or why not?  ANSWER:  Unemployment RateUse the `unemployment` table provided to answer the following questions. ***All numbers (other than percents) are in the thousands.*** Here are the first five entries of the table.<jupyter_code>unemployment.head()<jupyter_output><empty_output><jupyter_text>What, roughly, was the highest level the U.S. unemployment rate (measured as Percent Unemployed of Labor Force in the table) reached in:$1.$ The 20th century?<jupyter_code>unemployment_20th = ___<jupyter_output><empty_output><jupyter_text>$2.$ The past fifty years?<jupyter_code>unemployment_past_50 = ___<jupyter_output><empty_output><jupyter_text>$3.$ The twenty years before 2006?<jupyter_code>unemployment_before_2006 = ___<jupyter_output><empty_output><jupyter_text>$4.$ Given your answers to (1) through (3), Do you think there is a connection between your answer to the question above and the fact that Federal Reserve Chair <NAME> received a five-minute standing ovation at the end of the first of many events marking his retirement in 2005?  ANSWER:  The State of the Labor Market$1.$ About how many people lose or quit their jobs in an average year?<jupyter_code>average_quitters = ___<jupyter_output><empty_output><jupyter_text>$2.$ About how many people get jobs in an average year?<jupyter_code>average_getters = ___<jupyter_output><empty_output><jupyter_text>$3.$ About how many people are unemployed in an average year?<jupyter_code>average_unemployed = ___<jupyter_output><empty_output><jupyter_text>$4.$ About how many people are at work in an average year?<jupyter_code>average_workers = ___<jupyter_output><empty_output><jupyter_text>$5.$ About how many people are unemployed now?<jupyter_code>unemployed_now = ___<jupyter_output><empty_output><jupyter_text>National Income Accounting:$1.$ What was the level of real GDP in 2005 dollars in 1970?<jupyter_code>real_gdp_2005 = ___<jupyter_output><empty_output><jupyter_text>$2.$ What was the rate of inflation in the United States in 2000?<jupyter_code>inflation_rate_2000 = ___<jupyter_output><empty_output><jupyter_text>$3.$ Explain whether or not, how, and why the following items are included in the calculation of GDP: (i) rent you pay on an apartment, (ii) purchase of a used textbook, (iii) purchase of a new tank by the Department of Defense, (iv) watching an advertisement on youtube.  ANSWER: thisjo is my answeral;sdknf;lsalsjdndksdlkfakd;slfn Congratulations, you have finished your first assignment for Econ 101B! Run the cell below to submit all of your work. Make sure to check on OK to make sure that it has uploaded.<jupyter_code>_ = ok.submit()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup