!pip install pandas numpy matplotlib openpyxl statsmodels linearmodels seaborn
PythonDependent Variable: Inflation Independent Variables: Money Supply (M3) Growth (annual %), Unemployment Rate (% of total labour force), GDP Growth per annum (%), GNI Per Capita (%), Real Interest Rates (%), and Classification (1=Middle-to-High Income, 0 if Lower-Middle-to-Middle Income)
#PACKAGES AREA
import pandas as pd
from functools import reduce
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
#---------FILES AND DATA RANGE----------------
file_path = r"employmentinflation.xlsx"
start_year = 1991
end_year = 2021
endrange = end_year + 1
#CATEGORISATION, PICKING WHICH COUNTRIES HAVE VALUES
class_df = pd.read_excel(file_path, sheet_name="classifications").drop_duplicates()
year_columns = [col for col in class_df.columns if str(col).isdigit() and start_year <= int(col) <= end_year]
low_class = class_df[year_columns].apply(lambda row: any(x in ['L', 'LM'] for x in row if x != '..') and all(x in ['L', 'LM', '..'] for x in row),axis=1)
high_class = class_df[year_columns].apply(lambda row: any(x in ['UM', 'H'] for x in row if x != '..') and all(x in ['UM', 'H', '..'] for x in row),axis=1)
low_income_countries = class_df.loc[low_class, ['Country Code', 'Country']]
high_income_countries = class_df.loc[high_class, ['Country Code', 'Country']]
filtered_countries = (low_income_countries.values.tolist() + high_income_countries.values.tolist())
economic_data = {'inflation': pd.read_excel(file_path, sheet_name="inflation"),'unemployment': pd.read_excel(file_path, sheet_name="unemployment"),'interest': pd.read_excel(file_path, sheet_name="interest"),'growth': pd.read_excel(file_path, sheet_name="growth"),'m3': pd.read_excel(file_path, sheet_name="m3"),'income': pd.read_excel(file_path, sheet_name="income")}
#----WHAT COUNTRIES HAVE COMPLETE DATA FROM 1991-2021?------
years = [str(y) for y in range(start_year, endrange)]
def has_complete_data(country_code):
for sheet in economic_data:
df = economic_data[sheet]
country_data = df[df['Country Code'] == country_code]
if country_data.empty:
return False
year_data = country_data[[col for col in df.columns if str(col).strip() in years]]
if year_data.isna().any().any():
return False
return True
filtered_countries = [(code, name) for code, name in filtered_countries if has_complete_data(code)]
low_income_set = set([tuple(x) for x in low_income_countries.values.tolist()])
income_binary = {(code, name): 0 if (code, name) in low_income_set else 1 for code, name in filtered_countries}
def reshape_to_panel(country_code, country_name):
dfs = []
for sheet_name, indicator in zip(economic_data.keys(), ['inflation', 'unemployment', 'interest', 'growth', 'm3', 'income']):
df = economic_data[sheet_name]
country_df = df[df['Country Code'] == country_code]
melted = pd.melt(country_df,id_vars=['Country Name'],value_vars=[col for col in df.columns if str(col).strip() in years],var_name='year',value_name=indicator)
melted['year'] = melted['year'].astype(int)
melted = melted.dropna()
dfs.append(melted)
panel = reduce(lambda left, right: pd.merge(left, right, on=['Country Name', 'year']), dfs)
panel['classification'] = income_binary[(country_code, country_name)]
return panel
low_income_count = sum(1 for code, name in filtered_countries if (code, name) in low_income_set)
high_income_count = len(filtered_countries) - low_income_count
final_panel = pd.concat([reshape_to_panel(code, name)for code, name in filtered_countries if reshape_to_panel(code, name) is not None])
final_panel = final_panel.sort_values(['Country Name', 'year']).reset_index(drop=True)
print("Low-income countries with complete data:")
for code, name in filtered_countries:
if income_binary[(code, name)] == 0:
print(f"- {name}")
print("\nHigh-income countries with complete data:")
for code, name in filtered_countries:
if income_binary[(code, name)] == 1:
print(f"- {name}")
print(final_panel)
print("\nNumber of low income countries: ",low_income_count)
print("Number of High income countries: ",high_income_count)
print("\n-------------")
print("\nMax Recorded Inflation: ",final_panel['inflation'].max(),"%")
print("\nMin Recorded Inflation: ",final_panel['inflation'].min(),"%")
print("\nMax Recorded Unemployment: ",final_panel['unemployment'].max(),"%")
print("\nMin Recorded Unemployment: ",final_panel['unemployment'].min(),"%")
print("\n-------------")
#-----DATA CLEANING, REMOVING EXTREMITIES---------
def remove_outliers_iqr(df, column):
q1 = df[column].quantile(0.25)
q3 = df[column].quantile(0.75)
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
return df[(df[column] >= lower) & (df[column] <= upper)]
cleaned_panel = remove_outliers_iqr(final_panel, 'inflation')
#-----REGRESSION OLS------
X = cleaned_panel[['unemployment', 'interest', 'growth', 'classification','m3','income']]
X = sm.add_constant(X)
y = cleaned_panel['inflation']
model = sm.OLS(y, X).fit()
print(model.summary())
#----PHILLIPS CURVE------
sns.lmplot(data=cleaned_panel,x='unemployment',y='inflation',hue='classification',palette='Set1',markers=['o', 's'],aspect=1.5,height=6,ci=None)
plt.title("Phillips Curve by Income Group (Cleaned Data)")
plt.xlabel("Unemployment Rate (%)")
plt.ylabel("Inflation Rate (%)")
plt.legend(title="Income Group", labels=["Low Income", "High Income"])
plt.tight_layout()
plt.show()
low_income_data = cleaned_panel[cleaned_panel['classification'] == 0]
high_income_data = cleaned_panel[cleaned_panel['classification'] == 1]
X_low = sm.add_constant(low_income_data['unemployment'])
y_low = low_income_data['inflation']
model_low = sm.OLS(y_low, X_low).fit()
print("Low-Income Slope:", model_low.params['unemployment'])
X_high = sm.add_constant(high_income_data['unemployment'])
y_high = high_income_data['inflation']
model_high = sm.OLS(y_high, X_high).fit()
print("High-Income Slope:", model_high.params['unemployment'])
PythonLow-income countries with complete data:
- Bhutan
- Bolivia
- Egypt, Arab Rep.
- India
- Kenya
- Madagascar
- Solomon Islands
High-income countries with complete data:
- Bahamas, The
- United States
- Uruguay
Country Name year inflation unemployment interest growth \
0 Bahamas, The 1991 7.114681 12.170 6.282837 -4.181785
1 Bahamas, The 1992 5.738199 14.810 4.020735 -3.825582
2 Bahamas, The 1993 2.722898 12.720 8.381728 0.307807
3 Bahamas, The 1994 1.399334 13.830 4.591387 3.148916
4 Bahamas, The 1995 2.066995 10.830 5.900219 4.378752
.. ... ... ... ... ... ...
305 Uruguay 2017 6.218094 7.890 7.715058 1.740376
306 Uruguay 2018 7.606534 8.336 4.348384 0.164778
307 Uruguay 2019 7.881989 8.836 3.049107 0.928351
308 Uruguay 2020 9.756406 10.413 0.229432 -7.380142
309 Uruguay 2021 7.747914 9.328 -3.354878 5.561893
m3 income classification
0 6.633526 -5.915253 1
1 5.487199 -3.149718 1
2 16.126929 -2.744304 1
3 8.727931 1.314998 1
4 8.549461 17.280664 1
.. ... ... ...
305 1.910619 0.544476 1
306 11.840189 -0.163672 1
307 15.932945 1.610391 1
308 24.326485 -7.886605 1
309 16.817338 0.025879 1
[310 rows x 9 columns]
Number of low income countries: 7
Number of High income countries: 3
-------------
Max Recorded Inflation: 101.971683202507 %
Min Recorded Inflation: -1.70400479616298 %
Max Recorded Unemployment: 16.661 %
Min Recorded Unemployment: 0.599 %
-------------
OLS Regression Results
==============================================================================
Dep. Variable: inflation R-squared: 0.241
Model: OLS Adj. R-squared: 0.225
Method: Least Squares F-statistic: 15.11
Date: Sat, 31 May 2025 Prob (F-statistic): 5.13e-15
Time: 19:10:58 Log-Likelihood: -780.68
No. Observations: 292 AIC: 1575.
Df Residuals: 285 BIC: 1601.
Df Model: 6
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
const 4.4687 0.631 7.077 0.000 3.226 5.712
unemployment 0.1858 0.066 2.805 0.005 0.055 0.316
interest 0.0093 0.017 0.557 0.578 -0.024 0.042
growth 0.0757 0.101 0.749 0.454 -0.123 0.275
classification -3.2882 0.575 -5.719 0.000 -4.420 -2.156
m3 0.1224 0.024 5.037 0.000 0.075 0.170
income -0.1168 0.085 -1.369 0.172 -0.285 0.051
==============================================================================
Omnibus: 23.904 Durbin-Watson: 1.192
Prob(Omnibus): 0.000 Jarque-Bera (JB): 29.428
Skew: 0.633 Prob(JB): 4.07e-07
Kurtosis: 3.904 Cond. No. 66.2
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Low-Income Slope: 0.1767404838961858 High-Income Slope: 0.20372404977037464
#PACKAGES AREA
import pandas as pd
from functools import reduce
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
#---------FILES AND DATA RANGE----------------
file_path = r"employmentinflation.xlsx"
start_year = 1991
end_year = 2021
endrange = end_year + 1
#CATEGORISATION, PICKING WHICH COUNTRIES HAVE VALUES
class_df = pd.read_excel(file_path, sheet_name="classifications").drop_duplicates()
year_columns = [col for col in class_df.columns if str(col).isdigit() and start_year <= int(col) <= end_year]
low_class = class_df[year_columns].apply(lambda row: any(x in ['L', 'LM'] for x in row if x != '..') and all(x in ['L', 'LM', '..'] for x in row),axis=1)
high_class = class_df[year_columns].apply(lambda row: any(x in ['UM', 'H'] for x in row if x != '..') and all(x in ['UM', 'H', '..'] for x in row),axis=1)
low_income_countries = class_df.loc[low_class, ['Country Code', 'Country']]
high_income_countries = class_df.loc[high_class, ['Country Code', 'Country']]
filtered_countries = (low_income_countries.values.tolist() + high_income_countries.values.tolist())
economic_data = {'inflation': pd.read_excel(file_path, sheet_name="inflation"),'unemployment': pd.read_excel(file_path, sheet_name="unemployment"),'m3': pd.read_excel(file_path, sheet_name="m3")}
#----WHAT COUNTRIES HAVE COMPLETE DATA FROM 1991-2021?------
years = [str(y) for y in range(start_year, endrange)]
def has_complete_data(country_code):
for sheet in economic_data:
df = economic_data[sheet]
country_data = df[df['Country Code'] == country_code]
if country_data.empty:
return False
year_data = country_data[[col for col in df.columns if str(col).strip() in years]]
if year_data.isna().any().any():
return False
return True
filtered_countries = [(code, name) for code, name in filtered_countries if has_complete_data(code)]
low_income_set = set([tuple(x) for x in low_income_countries.values.tolist()])
income_binary = {(code, name): 0 if (code, name) in low_income_set else 1 for code, name in filtered_countries}
def reshape_to_panel(country_code, country_name):
dfs = []
for sheet_name, indicator in zip(economic_data.keys(), ['inflation', 'unemployment', 'm3']):
df = economic_data[sheet_name]
country_df = df[df['Country Code'] == country_code]
melted = pd.melt(country_df,id_vars=['Country Name'],value_vars=[col for col in df.columns if str(col).strip() in years],var_name='year',value_name=indicator)
melted['year'] = melted['year'].astype(int)
melted = melted.dropna()
dfs.append(melted)
panel = reduce(lambda left, right: pd.merge(left, right, on=['Country Name', 'year']), dfs)
panel['classification'] = income_binary[(country_code, country_name)]
return panel
low_income_count = sum(1 for code, name in filtered_countries if (code, name) in low_income_set)
high_income_count = len(filtered_countries) - low_income_count
final_panel = pd.concat([reshape_to_panel(code, name)for code, name in filtered_countries if reshape_to_panel(code, name) is not None])
final_panel = final_panel.sort_values(['Country Name', 'year']).reset_index(drop=True)
print("Low-income countries with complete data:")
print("\nNumber of low income countries: ",low_income_count)
print("Number of High income countries: ",high_income_count)
for code, name in filtered_countries:
if income_binary[(code, name)] == 0:
print(f"- {name}")
print("\nHigh-income countries with complete data:")
for code, name in filtered_countries:
if income_binary[(code, name)] == 1:
print(f"- {name}")
print(final_panel)
print("\n-------------")
print("\nMax Recorded Inflation: ",final_panel['inflation'].max(),"%")
print("\nMin Recorded Inflation: ",final_panel['inflation'].min(),"%")
print("\nMax Recorded Unemployment: ",final_panel['unemployment'].max(),"%")
print("\nMin Recorded Unemployment: ",final_panel['unemployment'].min(),"%")
print("\n-------------")
#-----DATA CLEANING, REMOVING EXTREMITIES---------
def remove_outliers_iqr(df, column):
q1 = df[column].quantile(0.25)
q3 = df[column].quantile(0.75)
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
return df[(df[column] >= lower) & (df[column] <= upper)]
cleaned_panel = remove_outliers_iqr(final_panel, 'inflation')
#-----REGRESSION OLS------
X = cleaned_panel[['unemployment', 'm3', 'classification']]
X = sm.add_constant(X)
y = cleaned_panel['inflation']
model = sm.OLS(y, X).fit()
print(model.summary())
#--------PHILLIPS CURVE-------
sns.lmplot(data=cleaned_panel,x='unemployment',y='inflation',hue='classification',palette='Set1',markers=['o', 's'],aspect=1.5,height=6,ci=None)
plt.title("Phillips Curve by Income Group (Cleaned Data)")
plt.xlabel("Unemployment Rate (%)")
plt.ylabel("Inflation Rate (%)")
plt.legend(title="Income Group", labels=["Low Income", "High Income"])
plt.tight_layout()
plt.show()
#----SLOPE OF TREND LINE (USING REGRESSION OF UNEMPLOYMENT VS INFLATION)-------
low_income_data = cleaned_panel[cleaned_panel['classification'] == 0]
high_income_data = cleaned_panel[cleaned_panel['classification'] == 1]
X_low = sm.add_constant(low_income_data['unemployment'])
y_low = low_income_data['inflation']
model_low = sm.OLS(y_low, X_low).fit()
print("Low-Income Slope for line of best fit:", model_low.params['unemployment'])
X_high = sm.add_constant(high_income_data['unemployment'])
y_high = high_income_data['inflation']
model_high = sm.OLS(y_high, X_high).fit()
print("High-Income Slope for line of best fit:", model_high.params['unemployment'])
#PART 2
country_names = cleaned_panel['Country Name'].unique()
positive_slope_countries = {}
negative_slope_countries = {}
for country in country_names:
country_data = cleaned_panel[cleaned_panel['Country Name'] == country]
X = country_data[['unemployment', 'm3', 'classification']]
X = sm.add_constant(X)
y = country_data['inflation']
model = sm.OLS(y, X).fit()
slope = model.params['unemployment']
p_value = model.pvalues['unemployment']
if p_value < 0.05:
if slope > 0:
positive_slope_countries[country] = {'slope': slope, 'p_value': p_value, 'r_squared': model.rsquared}
elif slope < 0:
negative_slope_countries[country] = {'slope': slope, 'p_value': p_value, 'r_squared': model.rsquared}
print("Countries with positive unemployment-inflation relationship (slope > 0) and p-value < 0.05:")
for country, stats in positive_slope_countries.items():
print(f"{country}: Slope = {stats['slope']:.4f}, p-value = {stats['p_value']:.4f}, R² = {stats['r_squared']:.2f}")
print("\nCountries with negative unemployment-inflation relationship (slope < 0) and p-value < 0.05:")
for country, stats in negative_slope_countries.items():
print(f"{country}: Slope = {stats['slope']:.4f}, p-value = {stats['p_value']:.4f}, R² = {stats['r_squared']:.2f}")
macao_data = final_panel[final_panel['Country Name'] == 'Macao SAR, China']
sns.lmplot(data=macao_data, x='unemployment', y='inflation', aspect=1.5, height=6, ci=None)
plt.title("Phillips Curve for Macao")
plt.xlabel("Unemployment Rate (%)")
plt.ylabel("Inflation Rate (%)")
plt.tight_layout()
plt.show()
min_unemployment = macao_data['unemployment'].min()
print(f"Minimum unemployment rate in Macao: {min_unemployment}%")
ph_data = final_panel[final_panel['Country Name'] == 'Philippines']
sns.lmplot(data=ph_data, x='unemployment', y='inflation', aspect=1.5, height=6, ci=None)
plt.title("Phillips Curve for Philippines")
plt.xlabel("Unemployment Rate (%)")
plt.ylabel("Inflation Rate (%)")
plt.tight_layout()
plt.show()
min_unemployment1 = ph_data['unemployment'].min()
print(f"Minimum unemployment rate in Philippines: {min_unemployment1}%")
PythonLow-income countries with complete data:
Number of low income countries: 31
Number of High income countries: 18
- Bangladesh
- Bhutan
- Bolivia
- Burkina Faso
- Burundi
- Cabo Verde
- Central African Republic
- Chad
- Côte d'Ivoire
- Egypt, Arab Rep.
- El Salvador
- Ghana
- Guinea-Bissau
- Haiti
- Honduras
- India
- Kenya
- Madagascar
- Malawi
- Mali
- Morocco
- Nepal
- Niger
- Nigeria
- Pakistan
- Philippines
- Senegal
- Solomon Islands
- Tanzania
- Togo
- Vanuatu
High-income countries with complete data:
- Australia
- Bahamas, The
- Denmark
- Hungary
- Iceland
- Israel
- Japan
- Korea, Rep.
- Libya
- Macao SAR, China
- Mexico
- Norway
- Qatar
- Sweden
- Trinidad and Tobago
- United Kingdom
- United States
- Uruguay
Country Name year inflation unemployment m3 classification
0 Australia 1991 3.176675 9.586 1.182172 1
1 Australia 1992 1.012231 10.733 7.379036 1
2 Australia 1993 1.753653 10.879 5.726582 1
3 Australia 1994 1.969635 9.724 9.959256 1
4 Australia 1995 4.627767 8.473 8.518372 1
... ... ... ... ... ... ...
1514 Vanuatu 2017 3.084526 5.287 9.297854 0
1515 Vanuatu 2018 2.330964 5.326 13.087647 0
1516 Vanuatu 2019 2.762520 5.444 6.910111 0
1517 Vanuatu 2020 5.329351 4.046 -0.559056 0
1518 Vanuatu 2021 2.343284 4.766 8.871941 0
[1519 rows x 6 columns]
-------------
Max Recorded Inflation: 101.971683202507 %
Min Recorded Inflation: -9.79764705882357 %
Max Recorded Unemployment: 19.81 %
Min Recorded Unemployment: 0.1 %
-------------
OLS Regression Results
==============================================================================
Dep. Variable: inflation R-squared: 0.179
Model: OLS Adj. R-squared: 0.177
Method: Least Squares F-statistic: 101.9
Date: Wed, 14 May 2025 Prob (F-statistic): 1.13e-59
Time: 15:00:04 Log-Likelihood: -3873.3
No. Observations: 1407 AIC: 7755.
Df Residuals: 1403 BIC: 7776.
Df Model: 3
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
const 3.2395 0.223 14.539 0.000 2.802 3.677
unemployment 0.0919 0.026 3.540 0.000 0.041 0.143
m3 0.1270 0.009 13.844 0.000 0.109 0.145
classification -1.6748 0.217 -7.710 0.000 -2.101 -1.249
==============================================================================
Omnibus: 65.595 Durbin-Watson: 1.052
Prob(Omnibus): 0.000 Jarque-Bera (JB): 77.756
Skew: 0.497 Prob(JB): 1.30e-17
Kurtosis: 3.583 Cond. No. 42.6
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Low-Income Slope for line of best fit: 0.06339158884750414 High-Income Slope for line of best fit: 0.0981943736858223 Countries with positive unemployment-inflation relationship (slope > 0) and p-value < 0.05: El Salvador: Slope = 1.2347, p-value = 0.0054, R² = 0.46 Hungary: Slope = 0.7213, p-value = 0.0271, R² = 0.34 Israel: Slope = 0.4478, p-value = 0.0087, R² = 0.60 Morocco: Slope = 0.4878, p-value = 0.0049, R² = 0.30 Philippines: Slope = 2.2682, p-value = 0.0104, R² = 0.33 Solomon Islands: Slope = 4.7180, p-value = 0.0000, R² = 0.52 Tanzania: Slope = 5.0625, p-value = 0.0140, R² = 0.25 United Kingdom: Slope = 0.3279, p-value = 0.0081, R² = 0.28 Countries with negative unemployment-inflation relationship (slope < 0) and p-value < 0.05: Honduras: Slope = -0.9093, p-value = 0.0015, R² = 0.43 Japan: Slope = -0.6530, p-value = 0.0005, R² = 0.43 Macao SAR, China: Slope = -1.2296, p-value = 0.0002, R² = 0.55 Mexico: Slope = -2.3957, p-value = 0.0031, R² = 0.47 Sweden: Slope = -0.5935, p-value = 0.0052, R² = 0.25

Minimum unemployment rate in Macao: 1.67%

Minimum unemployment rate in Philippines: 2.237%