You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.
import pandas as pd
import numpy as np
from scipy.stats import ttest_ind
This assignment requires more individual learning than previous assignments - you are encouraged to check out the pandas documentation to find functions or methods you might not have used yet, or ask questions on Stack Overflow and tag them as pandas and python related. And of course, the discussion forums are open for interaction with your peers and the course staff.
Definitions:
Hypothesis: University towns have their mean housing prices less effected by recessions. Run a t-test to compare the ratio of the mean price of houses in university towns the quarter before the recession starts compared to the recession bottom. (price_ratio=quarter_before_recession/recession_bottom
)
The following data files are available for this assignment:
City_Zhvi_AllHomes.csv
, has median home sale prices at a fine grained level.university_towns.txt
.gdplev.xls
. For this assignment, only look at GDP data from the first quarter of 2000 onward.Each function in this assignment below is worth 10%, with the exception of run_ttest()
, which is worth 50%.
# Use this dictionary to map state names to two letter acronyms
states = {'OH': 'Ohio', 'KY': 'Kentucky', 'AS': 'American Samoa', 'NV': 'Nevada', 'WY': 'Wyoming', 'NA': 'National', 'AL': 'Alabama', 'MD': 'Maryland', 'AK': 'Alaska', 'UT': 'Utah', 'OR': 'Oregon', 'MT': 'Montana', 'IL': 'Illinois', 'TN': 'Tennessee', 'DC': 'District of Columbia', 'VT': 'Vermont', 'ID': 'Idaho', 'AR': 'Arkansas', 'ME': 'Maine', 'WA': 'Washington', 'HI': 'Hawaii', 'WI': 'Wisconsin', 'MI': 'Michigan', 'IN': 'Indiana', 'NJ': 'New Jersey', 'AZ': 'Arizona', 'GU': 'Guam', 'MS': 'Mississippi', 'PR': 'Puerto Rico', 'NC': 'North Carolina', 'TX': 'Texas', 'SD': 'South Dakota', 'MP': 'Northern Mariana Islands', 'IA': 'Iowa', 'MO': 'Missouri', 'CT': 'Connecticut', 'WV': 'West Virginia', 'SC': 'South Carolina', 'LA': 'Louisiana', 'KS': 'Kansas', 'NY': 'New York', 'NE': 'Nebraska', 'OK': 'Oklahoma', 'FL': 'Florida', 'CA': 'California', 'CO': 'Colorado', 'PA': 'Pennsylvania', 'DE': 'Delaware', 'NM': 'New Mexico', 'RI': 'Rhode Island', 'MN': 'Minnesota', 'VI': 'Virgin Islands', 'NH': 'New Hampshire', 'MA': 'Massachusetts', 'GA': 'Georgia', 'ND': 'North Dakota', 'VA': 'Virginia'}
def get_list_of_university_towns():
'''Returns a DataFrame of towns and the states they are in from the
university_towns.txt list. The format of the DataFrame should be:
DataFrame( [ ["Michigan", "Ann Arbor"], ["Michigan", "Yipsilanti"] ],
columns=["State", "RegionName"] )
The following cleaning needs to be done:
1. For "State", removing characters from "[" to the end.
2. For "RegionName", when applicable, removing every character from " (" to the end.
3. Depending on how you read the data, you may need to remove newline character '\n'. '''
university_data = open('university_towns.txt').read().splitlines()
university_list = []
for element in university_data :
if '[edit]' in element:
x = element.find('[')
state = element[0:x]
elif ' (' in element:
x = element.find(' (')
region = element[0:x]
university_list.append([state, region])
else :
region = element
university_list.append([state, region])
university_towns = pd.DataFrame(university_list, columns = ['State', 'RegionName'])
return university_towns
print(get_list_of_university_towns()[:5])
print()
print(get_list_of_university_towns()[-5:])
def GDP_cleanup() :
GDP = (pd.read_excel('gdplev.xls')[219:])
GDP.reset_index(inplace = True)
GDP = (GDP.drop(GDP.columns[[0,1,2,3,4,6,8]], axis=1)
.rename(columns = {'Unnamed: 4': 'Quarter',
'Unnamed: 6': 'GDP'}))
GDP['GDP'] *= 100000000
GDP['GDP Change'] = GDP['GDP'].diff()
return GDP
GDP = GDP_cleanup()
def get_complete_recession() :
'''Helper function for next three answers.'''
recession_data = {}
quarter = 1
'''Recession start info.'''
while quarter < len(GDP)-1 :
if ((GDP.loc[quarter, 'GDP Change'] < 0) and (GDP.loc[quarter+1, 'GDP Change'] < 0)) :
recession_data['start'] = [quarter, GDP.loc[quarter][0],GDP.loc[quarter][1]]
break
else :
quarter += 1
'''Recession end info.'''
while quarter < len(GDP)-1 :
if ((GDP.loc[quarter, 'GDP Change'] > 0) and (GDP.loc[quarter+1, 'GDP Change'] > 0)) :
recession_data['end'] = [quarter+1, GDP.loc[quarter+1][0],GDP.loc[quarter+1][1]]
break
else :
quarter += 1
'''Recession bottom info.'''
quarter = recession_data['start'][0]
min_GDP = float('inf')
while quarter <= recession_data['end'][0]:
temp_GDP = GDP.loc[quarter][1]
if temp_GDP < min_GDP :
min_GDP = temp_GDP
min_quarter = quarter
quarter += 1
recession_data['bottom'] = [min_quarter, GDP.loc[min_quarter][0],GDP.loc[min_quarter][1]]
return recession_data
recession_data = get_complete_recession()
recession_data
def get_recession_start():
'''Returns the year and quarter of the recession start time as a
string value in a format such as 2005q3'''
return recession_data['start'][1]
get_recession_start()
def get_recession_end():
'''Returns the year and quarter of the recession end time as a
string value in a format such as 2005q3'''
return recession_data['end'][1]
get_recession_end()
def get_recession_bottom():
'''Returns the year and quarter of the recession bottom time as a
string value in a format such as 2005q3'''
return recession_data['bottom'][1]
get_recession_bottom()
def convert_housing_data_to_quarters():
'''Converts the housing data to quarters and returns it as mean
values in a dataframe. This dataframe should be a dataframe with
columns for 2000q1 through 2016q3, and should have a multi-index
in the shape of ["State","RegionName"].
Note: Quarters are defined in the assignment description, they are
not arbitrary three month periods.
The resulting dataframe should have 67 columns, and 10,730 rows.
'''
Housing_data = (pd.read_csv('City_Zhvi_AllHomes.csv')
.drop(['RegionID'], axis = 1))
Housing_data['State'] = Housing_data['State'].apply(lambda x: states[x])
Housing_data.set_index(['State', 'RegionName'], inplace=True)
Housing_data.drop(Housing_data.columns[0:48], axis = 1, inplace=True)
for x in range(66) :
quarter = (x % 4) + 1
year = 2000 + (x // 4)
if quarter < 4 :
temp = Housing_data.loc[: , (str(year) + '-0' + str(quarter * 3 - 2)): (str(year) + '-0' + str(quarter * 3))]
else :
temp = Housing_data.loc[: , (str(year) + '-' + str(quarter * 3 - 2)): (str(year) + '-' + str(quarter * 3))]
Housing_data[(str(year) + 'q' + str(quarter))] = temp.mean(axis=1)
Housing_data.drop(Housing_data.columns[0:3], axis = 1, inplace=True)
x += 1
Housing_data['2016q3'] = Housing_data.loc[: , '2016-07': '2016-08'].mean(axis=1)
Housing_data.drop(Housing_data.columns[0:2], axis = 1, inplace=True)
#return(Housing_data.shape)
return(Housing_data)
convert_housing_data_to_quarters()
def run_ttest():
'''First creates new data showing the decline or growth of housing prices
between the recession start and the recession bottom. Then runs a ttest
comparing the university town values to the non-university towns values,
return whether the alternative hypothesis (that the two groups are the same)
is true or not as well as the p-value of the confidence.
Return the tuple (different, p, better) where different=True if the t-test is
True at a p<0.01 (we reject the null hypothesis), or different=False if
otherwise (we cannot reject the null hypothesis). The variable p should
be equal to the exact p value returned from scipy.stats.ttest_ind(). The
value for better should be either "university town" or "non-university town"
depending on which has a lower mean price ratio (which is equivilent to a
reduced market loss).'''
'''Cleanup and differentiation'''
new_df = pd.DataFrame(index = convert_housing_data_to_quarters().index)
new_df['PriceRatio'] = convert_housing_data_to_quarters()[get_recession_start()] / convert_housing_data_to_quarters()[get_recession_bottom()]
university_states_list = get_list_of_university_towns()['State'].tolist()
university_towns_list = get_list_of_university_towns()['RegionName'].tolist()
University_Towns = new_df[((new_df.index.get_level_values(0)).isin(university_states_list) &
(new_df.index.get_level_values(1)).isin(university_towns_list)) == True]
Non_University_Towns = new_df[((new_df.index.get_level_values(0)).isin(university_states_list) &
(new_df.index.get_level_values(1)).isin(university_towns_list)) == False]
'''different and p'''
p = (ttest_ind(University_Towns['PriceRatio'], Non_University_Towns['PriceRatio'], nan_policy='omit'))[1]
if p > 0.01 :
different = False
else :
different = True
'''better'''
if University_Towns['PriceRatio'].mean() > Non_University_Towns['PriceRatio'].mean() :
better = "non-university town"
else :
better = "university town"
return (different, p, better)
run_ttest()