ECON 4370/6370 — Homework 2

Author

Your Name (SMU ID)

Published

October 12, 2026

  • This homework is a coding assignment. Please follow the instructions to complete the tasks.
  • Use Quarto/Knitr chunks for all work.
  • Turn in the rendered HTML and your .qmd source via Canvas.

0. Setup

set.seed(123)  # Please don't change this seed.

# You may load packages you plan to use (optional):
library(tidyverse)
library(readxl)
library(zoo)
library(lubridate)
library(forecast)

# Read in the CPS data we used in the lecture
cps <- read_csv("./data/cps09mar.csv")

# Read in the Welch Goyal Data we used in the lecture
data_raw <- read_excel("./data/PredictorData2018.xlsx",
                       sheet = "Monthly",
                       col_names = TRUE,
                       na = "NaN")

# Transform the Welch-Goyal data
data_wg <- data_raw %>% 
    transmute(
        date = zoo::as.yearmon(lubridate::ymd(yyyymm, truncated = 2)),
        ExReturn = log(Index) - log(c(1,Index[-length(Index)])),
        dp = log(D12) - log(Index),
        dy = log(D12) - log( c(1, Index[-length(Index)]) ),
        ep = log(E12) - log(Index),
        tms = lty - tbl,
        dfy = BAA - AAA,
        dfr = corpr - ltr,
        bm = `b/m`,
        tbl = tbl,
        ltr = ltr,
        ntis = ntis,
        svar = svar,
        infl = infl
    ) %>% 
    filter(row_number() > 1)

1. Return to Education for Subgroups

In this exercise, we will estimate the Mincer equation for different subgroups based on gender and education level. The Mincer equation relates log wages to education and experience:

\[\log(w_i) = \alpha + \beta_1 \cdot \text{education}_i + \beta_2 \cdot \text{experience}_i + \beta_3 \cdot \text{experience}_i^2 + \varepsilon_i\]

Step 1: Prepare the data

First, prepare the CPS data for the Mincer regression analysis:

# TODO: Filter and prepare the CPS data for Mincer regression
# - Keep only workers with positive earnings, hours, and weeks
# - Calculate hourly wage and log wage
# - Calculate potential experience as age - education - 6
# - Create education groups: "High School or Less" (≤12 years) vs "College+" (>12 years)
# - Create gender labels

# Step-by-step instructions for data preparation:

# 1. Filter the data to keep only valid workers:
#    - earnings > 0 (positive earnings)
#    - hours > 0 (positive hours worked)
#    - week > 0 (positive weeks worked)
#    - hours <= 80 (reasonable maximum hours per week)
#    - week <= 52 (reasonable maximum weeks per year)

# 2. Calculate derived variables:
#    - wage_hourly = earnings / (hours * week)
#    - log_wage = log(wage_hourly)
#    - experience = pmax(age - education - 6, 0)  # potential experience, non-negative
#    - exp2 = experience^2  # squared experience for Mincer equation

# 3. Create subgroup indicators:
#    - gender_group: "Male" if female == 0, "Female" if female == 1
#    - edu_group: "High School or Less" if education <= 12, "College+" if education > 12
#    - subgroup: combination of gender and education (4 groups total)

# 4. Remove any observations with missing values in key variables

cps_mincer <- cps %>%
  # 1. Filter to keep only valid workers
  filter(
    earnings > 0,
    hours > 0,
    week > 0,
    hours <= 80,
    week <= 52
  ) %>%
  # 2. Calculate derived variables
  mutate(
    wage_hourly = earnings / (hours * week),
    log_wage = log(wage_hourly),
    experience = pmax(age - education - 6, 0),
    exp2 = experience^2
  ) %>%
  # 3. Create subgroup indicators
  mutate(
    gender_group = ifelse(female == 0, "Male", "Female"),
    edu_group = ifelse(education <= 12, "High School or Less", "College+"),
    subgroup = paste(gender_group, edu_group, sep = ", ")
  ) %>%
  # 4. Remove any observations with missing values
  filter(!is.na(log_wage), !is.na(education), !is.na(experience))

Step 2: Estimate the Mincer equation for different subgroups

Estimate the Mincer equation separately for each subgroup:

# Create a function to estimate Mincer equation for a given subset of data
mincer_est <- function(data, subgroup_name) {
  # Estimate the Mincer regression
  model <- lm(log_wage ~ education + experience + exp2, data = data)
  
  # Extract coefficients and statistics
  coefs <- coef(model)
  
  # Return results as a data frame row
  data.frame(
    subgroup = subgroup_name,
    alpha = coefs[1],
    beta_edu = coefs[2],
    beta_exp = coefs[3],
    beta_exp2 = coefs[4],
    r_squared = summary(model)$r.squared,
    n_obs = nrow(data)
  )
}

# Get unique subgroups
subgroups <- unique(cps_mincer$subgroup)

# Estimate for each subgroup and combine results
results <- do.call(rbind, lapply(subgroups, function(sg) {
  data_subset <- cps_mincer %>% filter(subgroup == sg)
  mincer_est(data_subset, sg)
}))

# Display the results
print(results)
                                subgroup     alpha   beta_edu   beta_exp
(Intercept)    Male, High School or Less 1.3264472 0.07757939 0.04007600
(Intercept)1              Male, College+ 0.8997329 0.11706893 0.04894109
(Intercept)2            Female, College+ 0.8472421 0.11574105 0.03010816
(Intercept)3 Female, High School or Less 1.2470036 0.07305856 0.02836952
                 beta_exp2  r_squared n_obs
(Intercept)  -0.0005766226 0.12148645 10856
(Intercept)1 -0.0008799959 0.18600173 18131
(Intercept)2 -0.0005052117 0.18536040 14806
(Intercept)3 -0.0003842440 0.09211704  6752

Step 3: Visualize the results

Create visualizations to compare the returns to education across subgroups:

# TODO: Create visualizations to compare results across subgroups
# Suggestions:
# 1. Bar plot comparing returns to education (β₁) across subgroups
# 2. Scatter plot of log wages vs education by subgroup
# 3. Experience-wage profiles by subgroup

# 1. Bar plot of returns to education (beta_edu) by subgroup
# Use your results data frame with columns: subgroup, beta_edu
# ggplot(results, aes(x = subgroup, y = beta_edu)) + geom_col()

# 2. Scatter plot of log wages vs education by subgroup
# Use the original cps_mincer data with subgroup information
# ggplot(cps_mincer, aes(x = education, y = log_wage, color = subgroup)) + 
#   geom_point(alpha = 0.3) + 
#   geom_smooth(method = "lm", se = FALSE)

# 3. Experience-wage profiles by subgroup
# Create predicted wage profiles using the estimated coefficients
# For each subgroup, create a sequence of experience values (0 to 40 years)
# Calculate predicted log wages: alpha + beta_edu * education + beta_exp * exp + beta_exp2 * exp^2
# Plot the predicted profiles for each subgroup

# 1. Bar plot of returns to education (beta_edu) by subgroup
ggplot(results, aes(x = subgroup, y = beta_edu, fill = subgroup)) +
  geom_col() +
  labs(
    title = "Returns to Education by Subgroup",
    x = "Subgroup",
    y = "Return to Education (β₁)"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  guides(fill = "none")

# 2. Scatter plot of log wages vs education by subgroup
ggplot(cps_mincer, aes(x = education, y = log_wage, color = subgroup)) +
  geom_point(alpha = 0.3, size = 0.5) +
  geom_smooth(method = "lm", se = TRUE) +
  labs(
    title = "Log Wages vs Education by Subgroup",
    x = "Years of Education",
    y = "Log Hourly Wage",
    color = "Subgroup"
  ) +
  theme_minimal()
`geom_smooth()` using formula = 'y ~ x'

# 3. Experience-wage profiles by subgroup
# Create predicted wage profiles using the estimated coefficients
# For each subgroup, create a sequence of experience values (0 to 40 years)
exp_seq <- seq(0, 40, by = 1)

# Create predicted profiles for each subgroup
pred_profiles <- do.call(rbind, lapply(1:nrow(results), function(i) {
  row <- results[i, ]
  # Assume median education level for each subgroup
  data_subset <- cps_mincer %>% filter(subgroup == row$subgroup)
  median_edu <- median(data_subset$education)
  
  # Calculate predicted log wages
  data.frame(
    subgroup = row$subgroup,
    experience = exp_seq,
    log_wage_pred = row$alpha + row$beta_edu * median_edu + 
                    row$beta_exp * exp_seq + row$beta_exp2 * exp_seq^2
  )
}))

# Plot the predicted profiles
ggplot(pred_profiles, aes(x = experience, y = log_wage_pred, color = subgroup)) +
  geom_line(linewidth = 1) +
  labs(
    title = "Experience-Wage Profiles by Subgroup",
    subtitle = "Based on median education level within each subgroup",
    x = "Years of Experience",
    y = "Predicted Log Hourly Wage",
    color = "Subgroup"
  ) +
  theme_minimal()

2. Rolling Window Estimation of the AR(1) Model

The AR(1) Model

The AR(1) model for inflation is: \[\text{infl}_t = \alpha + \rho \cdot \text{infl}_{t-1} + \varepsilon_t\]

Where: - \(\alpha\) is the intercept (constant term) - \(\rho\) is the persistence parameter (how much current inflation depends on past inflation) - \(\varepsilon_t\) is the error term

In this exercise, we will implement rolling window estimation to examine how the persistence of inflation changes over time.

What is Rolling Window Estimation?

Rolling window estimation is a technique used in time series analysis to examine how model parameters change over time. Instead of estimating a model once using all available data, we estimate the model repeatedly using only a fixed-size “window” of recent observations.

Key concepts:

  • Window size: The number of observations used in each estimation (we’ll use 120 months = 10 years)
  • Rolling: The window moves forward one observation at a time
  • Time-varying parameters: This allows us to see how relationships change over time

Example with our data:

  • Start with observations 1-120, estimate AR(1) model
  • Move to observations 2-121, estimate AR(1) model
  • Move to observations 3-122, estimate AR(1) model
  • Continue until we reach the end of the data

Visual representation (window size = 120):

Time:     1  2  3  4  ........................... 120 121 ... T
Window 1: [████████████████████████████████████████]
Window 2:    [████████████████████████████████████████]
Window 3:       [████████████████████████████████████████]
...

Each window gives us one estimate of ρ, creating a time series of ρ estimates.

Why use rolling windows? 1. Structural breaks: Economic relationships may change over time 2. Parameter stability: Test if model parameters are constant 3. Forecasting: More recent data may be more relevant for predictions 4. Policy analysis: Understand how economic relationships evolve

Step 1: Prepare the inflation data

# TODO: Prepare the inflation time series
# - Extract the inflation series from data_wg
# - Remove any missing values
# - Create lagged inflation variable

infl_data <- data_wg %>%
  # Extract the inflation series and date
  select(date, infl) %>%
  # Remove any missing values
  filter(!is.na(infl)) %>%
  # Create lagged inflation variable
  mutate(infl_lag = lag(infl, 1)) %>%
  # Remove first observation (due to lag creating NA)
  filter(!is.na(infl_lag))

# Display first few rows
head(infl_data)
# A tibble: 6 × 3
  date          infl infl_lag
  <yearmon>    <dbl>    <dbl>
1 Feb 1927  -0.00571 -0.0113 
2 Mar 1927  -0.00575 -0.00571
3 Apr 1927   0       -0.00575
4 May 1927   0.00578  0      
5 Jun 1927   0.0115   0.00578
6 Jul 1927  -0.0170   0.0115 

Step 2: Implement rolling window estimation

# TODO: Implement rolling window estimation
# - Fix window size to 120 months (10 years)
# - For each window, estimate AR(1) model: infl_t = α + ρ * infl_{t-1} + ε_t
# - Store the estimated coefficients and their standard errors
# - Store the R-squared for each window

# Function to estimate AR(1) for a given window
ar1_est <- function(data_window) {
  # Estimate AR(1) model: infl ~ infl_lag
  model <- lm(infl ~ infl_lag, data = data_window)
  
  # Extract coefficients and statistics
  coefs <- coef(model)
  se <- summary(model)$coefficients[, "Std. Error"]
  
  # Return results
  data.frame(
    alpha = coefs[1],
    rho = coefs[2],
    se_alpha = se[1],
    se_rho = se[2],
    r_squared = summary(model)$r.squared
  )
}

# Implement rolling window loop
window_size <- 120

# Calculate total number of windows
n_windows <- nrow(infl_data) - window_size + 1

# Initialize results list
rolling_results <- list()

# Loop through each window
for (i in 1:n_windows) {
  # Get window data
  window_data <- infl_data[i:(i + window_size - 1), ]
  
  # Estimate AR(1) model
  est <- ar1_est(window_data)
  
  # Store results with the end date of the window
  rolling_results[[i]] <- cbind(
    date = infl_data$date[i + window_size - 1],
    est
  )
}

# Combine results into a single data frame
rolling_estimates <- do.call(rbind, rolling_results)

# Display first few rows
head(rolling_estimates)
                 date         alpha       rho     se_alpha     se_rho r_squared
(Intercept)  Jan 1937 -0.0009763332 0.4125134 0.0006567832 0.08379754 0.1703775
(Intercept)1 Feb 1937 -0.0009967902 0.4098698 0.0006539789 0.08387700 0.1683022
(Intercept)2 Mar 1937 -0.0009082370 0.4104949 0.0006564426 0.08438204 0.1670519
(Intercept)3 Apr 1937 -0.0008801690 0.4187312 0.0006551819 0.08412003 0.1735440
(Intercept)4 May 1937 -0.0008875656 0.4232743 0.0006529007 0.08354306 0.1786724
(Intercept)5 Jun 1937 -0.0010074553 0.4104530 0.0006472270 0.08272969 0.1725989
tail(rolling_estimates)
                   date        alpha       rho     se_alpha     se_rho
(Intercept)978 Jul 2018 0.0005254056 0.5198881 0.0003121873 0.07815844
(Intercept)979 Aug 2018 0.0005661141 0.5371005 0.0003046338 0.07682248
(Intercept)980 Sep 2018 0.0005664025 0.5375824 0.0003056966 0.07741166
(Intercept)981 Oct 2018 0.0006720395 0.5224704 0.0002933375 0.07429312
(Intercept)982 Nov 2018 0.0008912673 0.4153174 0.0002678655 0.06970983
(Intercept)983 Dec 2018 0.0009629055 0.3686565 0.0002763537 0.08044303
               r_squared
(Intercept)978 0.2727066
(Intercept)979 0.2929066
(Intercept)980 0.2901212
(Intercept)981 0.2953407
(Intercept)982 0.2312474
(Intercept)983 0.1510932

Step 3: Visualize the results

# TODO: Create visualizations of the rolling estimates
# 1. Time series plot of the estimated ρ (persistence parameter)

# Plot rolling estimates of ρ (persistence parameter) over time
ggplot(rolling_estimates, aes(x = date, y = rho)) +
  geom_line(color = "blue", linewidth = 0.8) +
  geom_ribbon(aes(ymin = rho - 1.96 * se_rho, ymax = rho + 1.96 * se_rho), 
              alpha = 0.2, fill = "blue") +
  geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
  geom_hline(yintercept = 1, linetype = "dashed", color = "darkgreen") +
  labs(
    title = "Rolling Window Estimates of AR(1) Persistence Parameter (ρ)",
    subtitle = "Window size: 120 months (10 years), with 95% confidence bands",
    x = "Date (End of Window)",
    y = "ρ (Persistence Parameter)",
    caption = "Dashed lines: ρ = 0 (no persistence) and ρ = 1 (unit root)"
  ) +
  theme_minimal() +
  theme(plot.caption = element_text(hjust = 0))