Worked examples in Python, R and Stata

Basic Econometrics
Applications for Empirical Research

Textbook by Assoc. Prof. Vo Tat Thang

Worked examples and LaTeX figures: Truong Thi Kieu Nhung

Introduction

Basic Econometrics, Applications for Empirical Research (2025, ISBN 978-604-346-471-9) is a textbook by Assoc. Prof. Vo Tat Thang. I did not write the book. My part was to produce all the numerical examples and the LaTeX-formatted figures, in two versions at first (Python and Stata), and I have since added a third (R).

Textbook content is copyrighted, so only the worked examples are shared here: code, data and outputs. For explanations and theory, read the book. Buy the textbook at the UEH Bookstore.

Each chapter has the same example in three languages. Pick a tab, copy the code, and download the data. Comments inside the notebooks and do-files are in Vietnamese.

Check status

Running the code

Code is under CC BY 4.0 (as in the repository). Source: github.com/Kieunhungtruong/Econometrics.

Chapter 1 Descriptive statistics

Summary statistics, histogram, box plot, bar chart, outliers, correlation and covariance.

# Bảng màu mẫu
palette = ["#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d","#B3B3B3"]
labels = ["cyan", "Red", "Dark Blue", "Orange", "Green", "Gray","Light Gray"]
def sumdetail(df, column):
    """ Hiển thị thống kê chi tiết của một biến số giống Stata 'sum, detail' """

    # Tính các percentiles
    percentiles = [1, 5, 10, 25, 50, 75, 90, 95, 99]
    x = df[column].dropna()
    percentile_values = np.percentile(x, percentiles)

    # Các thống kê khác
    obs = x.count()
    total = x.sum()
    mean = x.mean()
    std_dev = x.std()
    variance = x.var()
    skewness = x.skew()
    kurt = kurtosis(x, fisher=False)  # Nếu không dùng tuỳ chọn fisher=False kết quả của bạn phải trừ đi 3 để giống kết quả Stata
    smallest = x.nsmallest(3).values
    largest = x.nlargest(3).values

    # Hiển thị kết quả
    print(f"{column.upper()}\n" + "-"*60)
    print(f"{'Percentiles':<15}{'Smallest':<15}")
    for i in range(len(percentiles)):
        if i < 3:
            print(f"{percentiles[i]:<5}{percentile_values[i]:<15,.2f}{smallest[i]:<15,.2f}")
        else:
            print(f"{percentiles[i]:<5}{percentile_values[i]:<15,.2f}")

    print(f"\n{'Obs':<20}{obs:,}")
    print(f"{'Sum':<20}{total:,.2f}")
    print(f"{'Mean':<20}{mean:,.2f}")
    print(f"{'Std. Dev.':<20}{std_dev:,.2f}")
    print(f"{'Variance':<20}{variance:,.2f}")
    print(f"{'Skewness':<20}{skewness:.6f}")
    print(f"{'Kurtosis':<20}{kurt:.6f}")
    print(f"\n{'Largest':<15}")
    for i in range(3):
        print(f"{largest[i]:,.2f}")
#!pip install pyreadstat
import pyreadstat
df, meta = pyreadstat.read_dta ("rawdata/migration_remittances_16_full.dta",encoding ='latin1')
#data_table.DataTable(df)
df.loc[0:19, ['per_expenditure', 'remittances']].map(lambda x: f"{x:.1f}")
Output
per_expenditure remittances
0 57732.0 60000.0
1 119605.6 65000.0
2 59211.5 5000.0
3 54523.7 7000.0
4 66294.8 10000.0
5 147202.5 8000.0
6 46908.5 10000.0
7 65866.0 7000.0
8 38047.7 6000.0
9 37322.0 10000.0
10 50906.4 5000.0
11 54765.2 60000.0
12 44007.2 29500.0
13 37130.4 7000.0
14 19506.8 2000.0
15 65775.8 12000.0
16 58190.7 6000.0
17 263917.2 15000.0
18 51537.0 24000.0
19 35963.0 4000.0
sumdetail(df, 'per_expenditure')
Output
PER_EXPENDITURE
------------------------------------------------------------
Percentiles    Smallest       
1    4,963.69       1,439.00       
5    7,885.75       1,759.50       
10   10,057.20      2,054.80       
25   14,447.17      
50   21,311.50      
75   32,136.83      
90   46,488.60      
95   58,830.10      
99   105,417.56     

Obs                 9,399
Sum                 250,343,980.31
Mean                26,635.17
Std. Dev.           22,829.51
Variance            521,186,668.94
Skewness            5.771963
Kurtosis            64.152248

Largest        
457,283.25
363,633.00
362,254.50
plt.hist(df["per_expenditure"], bins=27, edgecolor=palette[6], color=palette[5])
plt.show()
OutputOutput of chapter 1, cell 12
min_val = df["per_expenditure"].min()
max_val = df["per_expenditure"].max()
bin_size = (max_val - min_val) / 27  # Chia thành 27 khoảng

# Tạo biểu đồ
fig = go.Figure(go.Histogram(
    x=df["per_expenditure"],
    histnorm="percent",
    xbins=dict(start=min_val, end=max_val, size=bin_size)  # Chia bin theo kích thước cố định
))
# Cập nhật viền màu cho các cột
fig.update_traces(marker=dict(color= palette[5], line=dict(width=1,color= palette[6])))
fig.show()
mean_value = df['per_expenditure'].mean() #Trung bình
print(f"mean: {mean_value}")
Output
mean: 26635.171859492824
median_value = np.percentile(df['per_expenditure'], 50) #Trung vị
print(f"median: {median_value}")
Output
median: 21311.5
percentile_25 = np.percentile(df['per_expenditure'], 25)  # Tính bách phân vị 25
#or percentile_25 = df['per_expenditure'].quantile(0.25) with pandas
print("25th percentile:", percentile_25)
Output
25th percentile: 14447.16650390625
percentile_75 = np.percentile(df['per_expenditure'], 75)  # Tính bách phân vị 75
print("75th percentile:", percentile_75)
Output
75th percentile: 32136.8330078125
std_dev = df['per_expenditure'].std()       # Độ lệch chuẩn
print(f"Standard Deviation: {std_dev}")
Output
Standard Deviation: 22829.513112253913
variance = df['per_expenditure'].var()      # Phương sai
print(f"Variance: {variance}")
Output
Variance: 521186668.94257337
df1 , meta = pyreadstat.read_dta ("rawdata/GDP_population.dta")
data_table.disable_dataframe_formatter()
# Hoặc chỉ hiển thị DataFrame cụ thể
data_table.DataTable(df1)
Output
province population GDP region PCI
0 Hà Nội 8.4357 1190.27727 1 66.735939
1 Vĩnh Phúc 1.1976 153.41256 1 68.906227
2 Bắc Ninh 1.4882 248.08294 1 69.083672
3 Quảng Ninh 1.3629 266.17437 1 72.949509
4 Hải Dương 1.9468 170.73436 1 65.218483
... ... ... ... ... ...
58 Cần Thơ 1.2523 108.57441 5 66.944916
59 Hậu Giang 0.7295 49.38715 5 68.121300
60 Sóc Trăng 1.1978 66.23834 5 65.165794
61 Bạc Liêu 0.9218 54.66274 5 60.360783
62 Cà Mau 1.2076 71.73144 5 61.601028

63 rows × 5 columns

sns.boxplot(x='PCI', data=df1, orient='h',color= palette[6])
plt.show()
OutputOutput of chapter 1, cell 21
fig = go.Figure(go.Box(
    x=df1['PCI'],
    boxpoints='outliers',  # Hiển thị các outliers
    orientation='h',# Horizontal boxplot
    name='',
    marker=dict(
        color=palette[5],
        line=dict(color=palette[6])
    ),
))
fig.show()
df2, meta = pyreadstat.read_dta ("rawdata/wage2020.dta", encoding='latin1')
#data_table.DataTable(df2)
plt.hist(df2["wage"], bins=40, edgecolor=palette[6], color=palette[5])
plt.show()
OutputOutput of chapter 1, cell 24
df3=pd.read_excel("rawdata/grade.xlsx")
data_table.DataTable(df3)
Output
grade frequency
0 0.0 14
1 0.2 0
2 0.4 1
3 0.6 6
4 0.8 12
5 1.0 43
6 1.2 126
7 1.4 278
8 1.6 619
9 1.8 1156
10 2.0 1975
11 2.2 2935
12 2.4 4279
13 2.6 5682
14 2.8 7304
15 3.0 8593
16 3.2 10076
17 3.4 11770
18 3.6 13026
19 3.8 14851
20 4.0 16457
21 4.2 17680
22 4.4 19896
23 4.6 21858
24 4.8 24293
25 5.0 26556
26 5.2 28625
27 5.4 31312
28 5.6 34541
29 5.8 37440
30 6.0 40256
31 6.2 43554
32 6.4 46501
33 6.6 49310
34 6.8 51590
35 7.0 53000
36 7.2 54349
37 7.4 55274
38 7.6 56019
39 7.8 55990
40 8.0 54184
41 8.2 48784
42 8.4 39798
43 8.6 27884
44 8.8 16048
45 9.0 7573
46 9.2 2899
47 9.4 962
48 9.6 221
49 9.8 43
50 10.0 0
# Vẽ biểu đồ cột
plt.bar(df3["grade"].astype(str), df3["frequency"], width=0.6, color=palette[1], edgecolor=palette[1])
plt.xticks(fontsize=3.5)
plt.show()
OutputOutput of chapter 1, cell 26
df4, meta = pyreadstat.read_dta ("rawdata/remittances_adolescents1.dta", encoding ='latin1')
data_table.DataTable(df4)
Output
tinh huyen xa diaban hoso m1ama1 num_edu_adolescents adolescent_gender m1ac5 HHsize adolescent6_18_ratio adolescent0_15_ratio
0 1 1 4 8 15 3 2 1 8 5.0 0.400000 0.400000
1 1 1 7 6 13 3 7 0 13 3.0 0.333333 0.333333
2 1 1 7 6 20 3 8 1 14 4.0 0.500000 0.500000
3 1 1 7 6 20 4 4 0 10 4.0 0.500000 0.500000
4 1 1 16 13 15 4 5 0 11 4.0 0.250000 0.250000
... ... ... ... ... ... ... ... ... ... ... ... ...
6369 96 973 32248 9 13 3 5 0 17 5.0 0.600000 0.400000
6370 96 973 32248 9 13 4 5 0 15 5.0 0.600000 0.400000
6371 96 973 32248 9 13 5 5 1 12 5.0 0.600000 0.400000
6372 96 973 32248 9 14 3 3 0 9 4.0 0.500000 0.500000
6373 96 973 32248 9 14 4 1 0 7 4.0 0.500000 0.500000

6374 rows × 12 columns

# Dùng bins rời rạc theo số nguyên duy nhất
bins = sorted(df4["num_edu_adolescents"].unique())
plt.hist(df4["num_edu_adolescents"], bins=bins, color=palette[5], edgecolor=palette[6])
plt.show()
OutputOutput of chapter 1, cell 29
sumdetail(df4,'num_edu_adolescents')
Output
NUM_EDU_ADOLESCENTS
------------------------------------------------------------
Percentiles    Smallest       
1    0.00           0.00           
5    1.00           0.00           
10   2.00           0.00           
25   3.00           
50   6.00           
75   8.00           
90   10.00          
95   11.00          
99   11.00          

Obs                 6,374
Sum                 36,233.00
Mean                5.68
Std. Dev.           3.05
Variance            9.29
Skewness            0.061907
Kurtosis            1.964521

Largest        
12.00
12.00
12.00
a=sns.boxplot(x='per_expenditure', data=df, orient='h',color= palette[6])
plt.show()
OutputOutput of chapter 1, cell 31
fig = go.Figure(go.Box(
    x=df['per_expenditure'],
    boxpoints='outliers',  # Hiển thị các outliers
    orientation='h',       # Horizontal boxplot
    name='',
    marker=dict(
        color=palette[5],
        line=dict(color=palette[6])
    ),
))
fig.show()
Q1 = df["per_expenditure"].quantile(0.25)
Q3 = df["per_expenditure"].quantile(0.75)
IQR = Q3 - Q1
lower_fence = Q1 - 1.5 * IQR
upper_fence = Q3 + 1.5 * IQR
print("Q1:", Q1)
print("Q3:", Q3)
print("IQR:", IQR)
Output
Q1: 14447.16650390625
Q3: 32136.8330078125
IQR: 17689.66650390625
df["outlier_per_expenditure"] = (
    (df["per_expenditure"] < lower_fence) | (df["per_expenditure"] > upper_fence)
).astype(int)
df["outlier_per_expenditure"].value_counts()
Output
count
outlier_per_expenditure
0 8927
1 472

plt.scatter(df["remittances"], df["per_expenditure"], color=palette[1], alpha=0.4)
plt.xlabel("Remittances")
plt.ylabel("Per Expenditure")
plt.title("Scatter plot: Remittances vs Per Expenditure")
plt.show()
OutputOutput of chapter 1, cell 36
correlation = df[["per_expenditure", "remittances"]].corr()
correlation
Output
per_expenditure remittances
per_expenditure 1.000000 0.136289
remittances 0.136289 1.000000
covariance = df[["per_expenditure", "remittances"]].cov()
covariance
Output
per_expenditure remittances
per_expenditure 5.211867e+08 7.560522e+07
remittances 7.560522e+07 5.904581e+08
# Chapter 1 - Descriptive statistics (R port of chapter1.ipynb)
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER'); if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(readxl); library(ggplot2)

data_dir <- Sys.getenv('DATA_DIR', 'rawdata')  # point this at the repo's data folder

dir.create('figures', showWarnings = FALSE)

palette <- c("#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d", "#B3B3B3")

# --- 1.1 Helper: sumdetail (like Stata 'sum, detail', matching the Python helper) ---
sumdetail <- function(df, column) {
  x <- df[[column]]; x <- x[!is.na(x)]
  n <- length(x); m <- mean(x); s <- sd(x)
  pct <- c(1, 5, 10, 25, 50, 75, 90, 95, 99)
  pv <- quantile(x, pct / 100, type = 7, names = FALSE)
  skew <- (n / ((n - 1) * (n - 2))) * sum(((x - m) / s)^3)  # pandas .skew() (adjusted)
  kurt <- mean((x - m)^4) / mean((x - m)^2)^2                 # scipy kurtosis(fisher=FALSE)
  cat(toupper(column), "\n", strrep("-", 60), "\n", sep = "")
  sm <- sort(x)[1:3]; lg <- sort(x, decreasing = TRUE)[1:3]
  for (i in seq_along(pct)) cat(sprintf("%-5d%-15s%s\n", pct[i], formatC(pv[i], format = "f", digits = 2, big.mark = ","),
                                       if (i <= 3) formatC(sm[i], format = "f", digits = 2, big.mark = ",") else ""))
  cat(sprintf("\nObs  %s\nSum  %s\nMean %s\nSD   %s\nVar  %s\nSkewness %.6f\nKurtosis %.6f\n",
              format(n, big.mark = ","), formatC(sum(x), format = "f", digits = 2, big.mark = ","),
              formatC(m, format = "f", digits = 2, big.mark = ","), formatC(s, format = "f", digits = 2, big.mark = ","),
              formatC(var(x), format = "f", digits = 2, big.mark = ","), skew, kurt))
  cat("\nLargest\n"); for (v in lg) cat(formatC(v, format = "f", digits = 2, big.mark = ","), "\n")
}

# --- 1.2 Load data and view first rows ---
df <- read_dta(file.path(data_dir, "migration_remittances_16_full.dta"), encoding = "latin1")

print(head(df[, c("per_expenditure", "remittances")], 20))
Output
# A tibble: 20 × 2
   per_expenditure remittances
             <dbl>       <dbl>
 1          57732        60000
 2         119606.       65000
 3          59212.        5000
 4          54524.        7000
 5          66295.       10000
 6         147202.        8000
 7          46908.       10000
 8          65866         7000
 9          38048.        6000
10          37322        10000
11          50906.        5000
12          54765.       60000
13          44007.       29500
14          37130.        7000
15          19507.        2000
16          65776.       12000
17          58191.        6000
18         263917.       15000
19          51537        24000
20          35963         4000
# --- 1.3 Detailed descriptive statistics ---
sumdetail(df, "per_expenditure")
Output
PER_EXPENDITURE
------------------------------------------------------------
1    4,963.69       1,439.00
5    7,885.75       1,759.50
10   10,057.20      2,054.80
25   14,447.17      
50   21,311.50      
75   32,136.83      
90   46,488.60      
95   58,830.10      
99   105,417.56     

Obs  9,399
Sum  250,343,980.31
Mean 26,635.17
SD   22,829.51
Var  521,186,668.94
Skewness 5.771963
Kurtosis 64.152248

Largest
457,283.25 
363,633.00 
362,254.50 
# --- 1.4 Histogram ---
p <- ggplot(df, aes(per_expenditure)) + geom_histogram(bins = 27, fill = palette[6], colour = palette[7])

ggsave("figures/ch1_hist_per_expenditure.png", p, width = 6, height = 4)
OutputR output: ch1_hist_per_expenditure.png
rng <- range(df$per_expenditure)

p <- ggplot(df, aes(per_expenditure)) +
  geom_histogram(aes(y = after_stat(count / sum(count) * 100)), bins = 27, fill = palette[6], colour = palette[7]) +
  ylab("percent")

ggsave("figures/ch1_hist_percent.png", p, width = 6, height = 4)
OutputR output: ch1_hist_percent.png
# --- 1.5 Mean, median, quartiles, SD, variance ---
cat("mean:", format(mean(df$per_expenditure), digits = 15), "\n")
Output
mean: 26635.1718594928 
cat("median:", quantile(df$per_expenditure, 0.50, names = FALSE), "\n")
Output
median: 21311.5 
cat("25th percentile:", quantile(df$per_expenditure, 0.25, names = FALSE), "\n")
Output
25th percentile: 14447.17 
cat("75th percentile:", quantile(df$per_expenditure, 0.75, names = FALSE), "\n")
Output
75th percentile: 32136.83 
cat("Standard Deviation:", format(sd(df$per_expenditure), digits = 15), "\n")
Output
Standard Deviation: 22829.5131122539 
cat("Variance:", format(var(df$per_expenditure), digits = 15), "\n")
Output
Variance: 521186668.942573 
# --- 1.6 Boxplot of PCI (GDP_population) ---
df1 <- read_dta(file.path(data_dir, "GDP_population.dta"))

p <- ggplot(df1, aes(x = PCI)) + geom_boxplot(fill = palette[7])

ggsave("figures/ch1_box_PCI.png", p, width = 6, height = 3)
OutputR output: ch1_box_PCI.png
# --- 1.7 Wage histogram ---
df2 <- read_dta(file.path(data_dir, "wage2020.dta"), encoding = "latin1")

p <- ggplot(df2, aes(wage)) + geom_histogram(bins = 40, fill = palette[6], colour = palette[7])

ggsave("figures/ch1_hist_wage.png", p, width = 6, height = 4)
OutputR output: ch1_hist_wage.png
# --- 1.8 Bar chart of grade frequencies ---
df3 <- read_excel(file.path(data_dir, "grade.xlsx"))

p <- ggplot(df3, aes(x = factor(grade), y = frequency)) + geom_col(width = 0.6, fill = palette[2]) +
  theme(axis.text.x = element_text(size = 4))

ggsave("figures/ch1_bar_grade.png", p, width = 6, height = 4)
OutputR output: ch1_bar_grade.png
# --- 1.9 Discrete variable: num_edu_adolescents ---
df4 <- read_dta(file.path(data_dir, "remittances_adolescents1.dta"), encoding = "latin1")

p <- ggplot(df4, aes(num_edu_adolescents)) + geom_histogram(binwidth = 1, fill = palette[6], colour = palette[7])

ggsave("figures/ch1_hist_num_edu.png", p, width = 6, height = 4)
OutputR output: ch1_hist_num_edu.png
sumdetail(df4, "num_edu_adolescents")
Output
NUM_EDU_ADOLESCENTS
------------------------------------------------------------
1    0.00           0.00
5    1.00           0.00
10   2.00           0.00
25   3.00           
50   6.00           
75   8.00           
90   10.00          
95   11.00          
99   11.00          

Obs  6,374
Sum  36,233.00
Mean 5.68
SD   3.05
Var  9.29
Skewness 0.061907
Kurtosis 1.964521

Largest
12.00 
12.00 
12.00 
# --- 1.10 Outliers: boxplot and IQR fences ---
p <- ggplot(df, aes(x = per_expenditure)) + geom_boxplot(fill = palette[7])

ggsave("figures/ch1_box_per_expenditure.png", p, width = 6, height = 3)
OutputR output: ch1_box_per_expenditure.png
Q1 <- quantile(df$per_expenditure, 0.25, names = FALSE); Q3 <- quantile(df$per_expenditure, 0.75, names = FALSE)

IQR_ <- Q3 - Q1

lower_fence <- Q1 - 1.5 * IQR_; upper_fence <- Q3 + 1.5 * IQR_

cat("Q1:", Q1, "\nQ3:", Q3, "\nIQR:", IQR_, "\n")
Output
Q1: 14447.17 
Q3: 32136.83 
IQR: 17689.67 
df$outlier_per_expenditure <- as.integer(df$per_expenditure < lower_fence | df$per_expenditure > upper_fence)

print(table(df$outlier_per_expenditure))
Output
   0    1 
8927  472 
# --- 1.11 Scatter plot ---
p <- ggplot(df, aes(remittances, per_expenditure)) + geom_point(colour = palette[2], alpha = 0.4) +
  labs(x = "Remittances", y = "Per Expenditure", title = "Scatter plot: Remittances vs Per Expenditure")

ggsave("figures/ch1_scatter.png", p, width = 6, height = 4)
OutputR output: ch1_scatter.png
# --- 1.12 Correlation and covariance matrices ---
print(cor(df[, c("per_expenditure", "remittances")], use = "pairwise.complete.obs"))
Output
                per_expenditure remittances
per_expenditure       1.0000000   0.1362889
remittances           0.1362889   1.0000000
print(cov(df[, c("per_expenditure", "remittances")], use = "pairwise.complete.obs"))
Output
                per_expenditure remittances
per_expenditure       521186669    75605222
remittances            75605222   590458148
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chapter1":
global link "C:\Downloads\data_dofile\1.data\chapter1" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow

*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 1                                                 */
/*      File Name:  chapter1.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    An Introduction to Econometrics               */  
/*      Input File:     migration_remittances_16_full             */
/*                      GDP_population.dta                        */
/*                      wage2020.dta                              */
/*                      grade.dta                                 */
/*                      remittances_adolescents1.dta              */
/*      Output File:    chapter1.log                              */  
/******************************************************************/ 
log using chapter1.log, text replace

use "$link\migration_remittances_16_full.dta",clear

list per_expenditure remittances in 1/20

sum per_expenditure, detail

histogram per_expenditure,bin (27)

graph export Chapter1.1.png, as(png) name("Graph") replace

mean per_expenditure

sort per_expenditure

centile per_expenditure, centile(50)

tabstat per_expenditure , statistics(sd variance) 

centile per_expenditure , centile(25)

centile per_expenditure , centile(75)

use "$link\GDP_population.dta",clear

graph hbox PCI

graph export Chapter1.3.png, as(png) name("Graph") replace

use "$link\wage2020.dta",clear

histogram wage, frequency 

graph export Chapter1.4a.png, as(png) name("Graph") replace

use "$link\grade.dta",clear

graph bar Sốlượng, over(Điểm)

graph export Chapter1.4b.png, as(png) name("Graph") replace

use "$link\remittances_adolescents1.dta",clear

histogram num_edu_adolescents , discrete frequency 

graph export Chapter1.4c.png, as(png) name("Graph") replace

sum num_edu_adolescents,detail

use "$link\migration_remittances_16_full.dta",clear

summarize per_expenditure, detail

local q1 = r(p25)

display `q1' 

local q3 = r(p75)

display `q3' 

local iqr = `q3' - `q1'

display `iqr'

graph hbox per_expenditure

graph export Chapter1.5.png, as(png) name("Graph") replace

gen outlier_per_expenditure = 0

replace outlier_per_expenditure = 1 if per_expenditure >= 58673 

scatter per_expenditure remittances

graph export Chapter1.6.png, as(png) name("Graph") replace

correlate per_expenditure remittances, covariance 

matrix list r(C), format(%14.2f)

correlate per_expenditure remittances 

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: GDP_population.dta · grade.dta · migration_remittances_16_full.dta · remittances_adolescents1.dta · wage2020.dta

Chapter 2 Time series, panel data and OLS

Time-series and panel layouts, scatter plots with a fitted line, simple and multiple OLS.

# Bảng màu mẫu
palette = ["#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d","#B3B3B3"]
labels = ["cyan", "Red", "Dark Blue", "Orange", "Green", "Gray","Light Gray"]
df, meta = pyreadstat.read_dta("rawdata/migration_remittances_16_full.dta", encoding='latin1')
df
Output
tinh huyen xa diaban hoso num_migration marital_status HHsize agehead num_children0_5 ... durables_share housing_share others_share healthcare_share education_share RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta
0 1 1 4 8 14 NaN 0 2.0 63.0 0.0 ... 0.000000 0.030590 0.021175 0.004854 0.044689 1.0 0.0 0.0 0.0 0.0
1 1 1 4 8 15 NaN 1 5.0 37.0 0.0 ... 0.026955 0.011273 0.006304 0.000797 0.006511 1.0 0.0 0.0 0.0 0.0
2 1 1 4 8 19 NaN 1 2.0 61.0 0.0 ... 0.000000 0.027630 0.013743 0.014355 0.000000 1.0 0.0 0.0 0.0 0.0
3 1 1 7 6 13 NaN 1 3.0 62.0 0.0 ... 0.018952 0.022694 0.014611 0.002366 0.056978 1.0 0.0 0.0 0.0 0.0
4 1 1 7 6 14 NaN 1 5.0 62.0 0.0 ... 0.000000 0.067794 0.004254 0.011658 0.002564 1.0 0.0 0.0 0.0 0.0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
9394 96 973 32242 18 14 NaN 1 4.0 57.0 0.0 ... 0.006153 0.003076 0.004692 0.004922 0.000000 0.0 0.0 0.0 0.0 1.0
9395 96 973 32242 18 15 NaN 1 3.0 53.0 0.0 ... 0.000000 0.007322 0.001611 0.115197 0.000000 0.0 0.0 0.0 0.0 1.0
9396 96 973 32248 9 13 NaN 1 5.0 45.0 0.0 ... 0.000000 0.006577 0.005098 0.030914 0.004440 0.0 0.0 0.0 0.0 1.0
9397 96 973 32248 9 14 NaN 1 4.0 36.0 0.0 ... 0.000000 0.005244 0.007342 0.013635 0.005874 0.0 0.0 0.0 0.0 1.0
9398 96 973 32248 9 19 NaN 1 4.0 57.0 0.0 ... 0.011156 0.049087 0.007099 0.005477 0.000000 0.0 0.0 0.0 0.0 1.0

9399 rows × 65 columns

# Tính các thống kê mô tả
summary = df[['per_expenditure', 'remittances']].agg(['mean', 'median', 'std', 'var', 'min', 'max', 'count'])
summary
Output
per_expenditure remittances
mean 2.663517e+04 8.363139e+03
median 2.131150e+04 2.000000e+03
std 2.282951e+04 2.429934e+04
var 5.211867e+08 5.904581e+08
min 1.439000e+03 0.000000e+00
max 4.572832e+05 6.220000e+05
count 9.399000e+03 9.399000e+03
# Đọc và xử lý file năm 2016
df_2016, meta = pyreadstat.read_dta ("rawdata/migration_remittances_16_full.dta", encoding='latin1')
df_2014, meta = pyreadstat.read_dta ("rawdata/migration_remittances_14_full.dta", encoding='latin1')
df_2012, meta = pyreadstat.read_dta ("rawdata/migration_remittances_12_full.dta", encoding='latin1')

df_2016_mean = df_2016[['per_expenditure', 'remittances']].mean().to_frame().T
df_2014_mean = df_2014[['per_expenditure', 'remittances']].mean().to_frame().T
df_2012_mean = df_2012[['per_expenditure', 'remittances']].mean().to_frame().T

df_2016_mean['year'] = 2016
df_2014_mean['year'] = 2014
df_2012_mean['year'] = 2012
# Gộp cả 3 DataFrame lại
df_merged = pd.concat([df_2012_mean, df_2014_mean, df_2016_mean], ignore_index=True)

# Hiển thị kết quả
print(df_merged.to_string(index=False))
Output
 per_expenditure  remittances  year
    19989.313637  5943.913182  2012
    23533.501102  6664.606447  2014
    26635.171859  8363.138845  2016
panel= pd.read_stata("rawdata/panel121416.dta")
panel
Output
year hhid HHsize agehead genderhead female_ratio migration remittances num_eduhead per_expenditure children_ratio elderly_ratio ln_per_expenditure agehead2
0 2012.0 3.200000e+01 5.0 59.0 1.0 0.400000 0.0 10000.0 12 66575.000000 0.400000 0.0 11.106085 3481.0
1 2014.0 3.200000e+01 2.0 61.0 1.0 0.500000 1.0 19000.0 12 51281.000000 0.000000 0.5 10.845076 3721.0
2 2016.0 3.200000e+01 2.0 63.0 1.0 0.500000 0.0 60000.0 12 57732.000000 0.000000 0.5 10.963567 3969.0
3 2012.0 3.300000e+01 5.0 33.0 0.0 0.800000 0.0 130000.0 12 59666.199219 0.400000 0.0 10.996521 1089.0
4 2014.0 3.300000e+01 5.0 35.0 0.0 0.600000 0.0 253000.0 12 85886.601562 0.400000 0.0 11.360784 1225.0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
5731 2014.0 1.680093e+12 4.0 41.0 0.0 0.500000 0.0 3000.0 9 33600.250000 0.250000 0.0 10.422289 1681.0
5732 2016.0 1.680093e+12 4.0 43.0 0.0 0.500000 0.0 0.0 9 36424.500000 0.250000 0.0 10.502996 1849.0
5733 2012.0 1.680093e+12 5.0 45.0 0.0 0.600000 0.0 410.0 6 7207.000000 0.000000 0.0 8.882808 2025.0
5734 2014.0 1.680093e+12 2.0 47.0 0.0 0.500000 1.0 18000.0 7 26588.000000 0.000000 0.0 10.188215 2209.0
5735 2016.0 1.680093e+12 3.0 49.0 0.0 0.333333 0.0 0.0 4 17934.000000 0.333333 0.0 9.794454 2401.0

5736 rows × 14 columns

# Vẽ scatter plot
sns.scatterplot(x='remittances', y='per_expenditure', data=df, color=palette[6], alpha=0.6)
# Vẽ đường hồi quy kèm CI
sns.regplot(x='remittances', y='per_expenditure', data=df, scatter=False, ci=95, color=palette[1])
plt.title('Relationship between Remittances and Per Capita Expenditures')
plt.xlabel('Remittances')
plt.ylabel('Per Capita Expenditures')
plt.show()
OutputOutput of chapter 2, cell 14
X = sm.add_constant(df['remittances']) # Thêm cột intercept (hằng số) vào biến độc lập
model = sm.OLS(df['per_expenditure'], X)
results = model.fit()
print(results.summary())
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                  0.018
Method:                 Least Squares   F-statistic:                     177.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.31e-40
Time:                        10:32:44   Log-Likelihood:            -1.0757e+05
No. Observations:                9399   AIC:                         2.152e+05
Df Residuals:                    9397   BIC:                         2.152e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.556e+04    246.728    103.613      0.000    2.51e+04     2.6e+04
remittances     0.1280      0.010     13.336      0.000       0.109       0.147
==============================================================================
Omnibus:                    10743.945   Durbin-Watson:                   1.564
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          1587596.544
Skew:                           5.822   Prob(JB):                         0.00
Kurtosis:                      65.596   Cond. No.                     2.72e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.72e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Lấy hệ số hồi quy của 'remittances'
coeff_remittances = results.params['remittances']

# Tính hiệu ứng biên tại remittances == 60000
remittances_value = 60000
# Tính giá trị dự đoán tại remittances = 60000
predicted_value = results.params['const'] + coeff_remittances * remittances_value

print(f"Dự đoán giá trị của per_expenditure khi remittances = 60000: {predicted_value}")
Output
Dự đoán giá trị của per_expenditure khi remittances = 60000: 33247.014484230516
# Đọc dữ liệu .dta từ Stata
df, meta = pyreadstat.read_dta(
    "rawdata/migration_remittances_16_full.dta",
    encoding='latin1')

# Tạo các biến bình phương
df['agehead2'] = df['agehead'] ** 2
df['HHsize2'] = df['HHsize'] ** 2

# Danh sách các biến độc lập đúng như trong Stata
independent_vars = [
    'ln_expenditure', 'agehead', 'agehead2', 'primary', 'secondary',
    'high_school', 'higher_education', 'HHsize', 'HHsize2', 'dependency_ratio',
    'domestic_remittances', 'overseas_remittances', 'urban', 'RedRiverDelta',
    'Northmidlandareas', 'MekongRiverDelta', 'Centralhighlands', 'CentralCoast'
]

# Bỏ các dòng có missing như Stata
all_vars = ['food_share'] + independent_vars
df_model = df[all_vars].dropna()

# Tách X và y
X = df_model[independent_vars]
X = sm.add_constant(X)  # thêm hằng số _cons
y = df_model['food_share']

# Hồi quy tuyến tính (OLS)
model = sm.OLS(y, X).fit()

# In kết quả chi tiết như Stata
print(model.summary())
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             food_share   R-squared:                       0.691
Model:                            OLS   Adj. R-squared:                  0.691
Method:                 Least Squares   F-statistic:                     1041.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:32:44   Log-Likelihood:                 13344.
No. Observations:                8381   AIC:                        -2.665e+04
Df Residuals:                    8362   BIC:                        -2.652e+04
Df Model:                          18                                         
Covariance Type:            nonrobust                                         
========================================================================================
                           coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------------
const                    0.8971      0.013     69.272      0.000       0.872       0.922
ln_expenditure          -0.0383      0.001    -34.788      0.000      -0.040      -0.036
agehead                 -0.0006      0.000     -2.167      0.030      -0.001   -5.47e-05
agehead2              6.104e-06    2.5e-06      2.442      0.015     1.2e-06     1.1e-05
primary                  0.0007      0.002      0.440      0.660      -0.002       0.004
secondary                0.0002      0.002      0.102      0.919      -0.003       0.003
high_school             -0.0005      0.002     -0.226      0.822      -0.004       0.003
higher_education         0.0015      0.003      0.581      0.561      -0.004       0.007
HHsize                  -0.1135      0.001    -78.683      0.000      -0.116      -0.111
HHsize2                  0.0086      0.000     58.678      0.000       0.008       0.009
dependency_ratio        -0.0017      0.001     -1.887      0.059      -0.003    6.47e-05
domestic_remittances    -0.0014      0.001     -0.990      0.322      -0.004       0.001
overseas_remittances    -0.0015      0.003     -0.512      0.608      -0.007       0.004
urban                    0.0124      0.001      9.450      0.000       0.010       0.015
RedRiverDelta           -0.0031      0.002     -1.557      0.120      -0.007       0.001
Northmidlandareas       -0.0043      0.002     -2.084      0.037      -0.008      -0.000
MekongRiverDelta        -0.0084      0.002     -4.222      0.000      -0.012      -0.005
Centralhighlands        -0.0112      0.003     -4.329      0.000      -0.016      -0.006
CentralCoast            -0.0010      0.002     -0.524      0.600      -0.005       0.003
==============================================================================
Omnibus:                     3937.239   Durbin-Watson:                   1.877
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            81037.717
Skew:                           1.765   Prob(JB):                         0.00
Kurtosis:                      17.819   Cond. No.                     7.09e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.09e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Chapter 2 - Data types and simple/multiple OLS (R port of chapter2.ipynb)
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER'); if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(ggplot2)

data_dir <- Sys.getenv('DATA_DIR', 'rawdata')  # point this at the repo's data folder

dir.create('figures', showWarnings = FALSE)

palette <- c("#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d", "#B3B3B3")

# --- 2.1 Load cross-section data ---
df <- read_dta(file.path(data_dir, "migration_remittances_16_full.dta"), encoding = "latin1")

cat("Rows:", nrow(df), "Cols:", ncol(df), "\n")
Output
Rows: 9399 Cols: 65 
# --- 2.2 Summary statistics ---
vars <- c("per_expenditure", "remittances")

summary_tab <- sapply(df[vars], function(x) c(mean = mean(x, na.rm = TRUE), median = median(x, na.rm = TRUE),
  std = sd(x, na.rm = TRUE), var = var(x, na.rm = TRUE), min = min(x, na.rm = TRUE),
  max = max(x, na.rm = TRUE), count = sum(!is.na(x))))

print(summary_tab)
Output
       per_expenditure  remittances
mean          26635.17 8.363139e+03
median        21311.50 2.000000e+03
std           22829.51 2.429934e+04
var       521186668.94 5.904581e+08
min            1439.00 0.000000e+00
max          457283.25 6.220000e+05
count          9399.00 9.399000e+03
# --- 2.3 Time series: means by survey year ---
means <- do.call(rbind, lapply(c(2012, 2014, 2016), function(y) {
  d <- read_dta(file.path(data_dir, sprintf("migration_remittances_%s_full.dta", substr(y, 3, 4))), encoding = "latin1")
  data.frame(per_expenditure = mean(d$per_expenditure, na.rm = TRUE), remittances = mean(d$remittances, na.rm = TRUE), year = y)
}))

print(means, row.names = FALSE)
Output
 per_expenditure remittances year
        19989.31    5943.913 2012
        23533.50    6664.606 2014
        26635.17    8363.139 2016
# --- 2.4 Panel data ---
panel <- read_dta(file.path(data_dir, "panel121416.dta"))

cat("Panel dims:", dim(panel), "\n")
Output
Panel dims: 5736 14 
# --- 2.5 Plot: relationship between variables ---
p <- ggplot(df, aes(remittances, per_expenditure)) + geom_point(colour = palette[7], alpha = 0.6) +
  geom_smooth(method = "lm", level = 0.95, colour = palette[2]) +
  labs(title = "Relationship between Remittances and Per Capita Expenditures",
       x = "Remittances", y = "Per Capita Expenditures")

ggsave("figures/ch2_scatter_reg.png", p, width = 6, height = 4)
OutputR output: ch2_scatter_reg.png
# --- 2.6 OLS regression ---
m1 <- lm(per_expenditure ~ remittances, data = df)

print(summary(m1))
Output
Call:
lm(formula = per_expenditure ~ remittances, data = df)

Residuals:
   Min     1Q Median     3Q    Max 
-67602 -11976  -5051   5543 431360 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 2.556e+04  2.467e+02  103.61   <2e-16 ***
remittances 1.280e-01  9.601e-03   13.34   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 22620 on 9397 degrees of freedom
Multiple R-squared:  0.01857,	Adjusted R-squared:  0.01847 
F-statistic: 177.8 on 1 and 9397 DF,  p-value: < 2.2e-16
cat("N =", nobs(m1), " R2 =", summary(m1)$r.squared, "\n")
Output
N = 9399  R2 = 0.01857467 
# Prediction at remittances = 60000
pred <- unname(coef(m1)[1] + coef(m1)["remittances"] * 60000)

cat("Predicted per_expenditure at remittances = 60000:", pred, "\n")
Output
Predicted per_expenditure at remittances = 60000: 33247.01 
# --- 2.7 Multiple regression of food_share ---
df$agehead2 <- df$agehead^2

df$HHsize2 <- df$HHsize^2

independent_vars <- c('ln_expenditure', 'agehead', 'agehead2', 'primary', 'secondary',
  'high_school', 'higher_education', 'HHsize', 'HHsize2', 'dependency_ratio',
  'domestic_remittances', 'overseas_remittances', 'urban', 'RedRiverDelta',
  'Northmidlandareas', 'MekongRiverDelta', 'Centralhighlands', 'CentralCoast')

df_model <- na.omit(as.data.frame(df)[, c("food_share", independent_vars)])

m2 <- lm(reformulate(independent_vars, "food_share"), data = df_model)

print(summary(m2))
Output
Call:
lm(formula = reformulate(independent_vars, "food_share"), data = df_model)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.31121 -0.02293  0.00076  0.02161  0.53028 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
(Intercept)           8.971e-01  1.295e-02  69.272  < 2e-16 ***
ln_expenditure       -3.831e-02  1.101e-03 -34.788  < 2e-16 ***
agehead              -5.739e-04  2.648e-04  -2.167   0.0303 *  
agehead2              6.104e-06  2.500e-06   2.442   0.0146 *  
primary               7.075e-04  1.607e-03   0.440   0.6598    
secondary             1.662e-04  1.637e-03   0.102   0.9191    
high_school          -4.539e-04  2.012e-03  -0.226   0.8215    
higher_education      1.488e-03  2.561e-03   0.581   0.5613    
HHsize               -1.135e-01  1.443e-03 -78.683  < 2e-16 ***
HHsize2               8.610e-03  1.467e-04  58.678  < 2e-16 ***
dependency_ratio     -1.659e-03  8.791e-04  -1.887   0.0592 .  
domestic_remittances -1.429e-03  1.444e-03  -0.990   0.3224    
overseas_remittances -1.482e-03  2.893e-03  -0.512   0.6084    
urban                 1.239e-02  1.311e-03   9.450  < 2e-16 ***
RedRiverDelta        -3.150e-03  2.023e-03  -1.557   0.1195    
Northmidlandareas    -4.311e-03  2.069e-03  -2.084   0.0372 *  
MekongRiverDelta     -8.437e-03  1.998e-03  -4.222 2.45e-05 ***
Centralhighlands     -1.116e-02  2.577e-03  -4.329 1.52e-05 ***
CentralCoast         -1.039e-03  1.981e-03  -0.524   0.6001    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.04929 on 8362 degrees of freedom
Multiple R-squared:  0.6914,	Adjusted R-squared:  0.6908 
F-statistic:  1041 on 18 and 8362 DF,  p-value: < 2.2e-16
cat("N =", nobs(m2), " R2 =", summary(m2)$r.squared, "\n")
Output
N = 8381  R2 = 0.6914281 
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chapter2" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chapter2" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 2                                                 */
/*      File Name:  chapter2.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    The linear regression model                   */   
/*      Input File:     migration_remittances_16_full             */ 
/*                      migration_remittances_14_full             */ 
/*                      migration_remittances_12_full             */
/*                      panel121416                               */  
/*      Output File:    chapter2.log                              */  
/******************************************************************/ 

log using chapter2.log, text replace

use "$link\migration_remittances_16_full.dta",clear

tabstat per_expenditure remittances , statistics(mean median sd var min max n)

collapse (mean) per_expenditure remittances

gen year =2016

save 2016,replace
use "$link\migration_remittances_14_full.dta",clear

collapse (mean) per_expenditure remittances

gen year =2014

save 2014,replace

use "$link\migration_remittances_12_full.dta",clear

collapse (mean) per_expenditure remittances

gen year = 2012

append using 2014 2016

use "$link\panel121416.dta",clear

use "$link\migration_remittances_16_full.dta",clear

graph twoway (lfitci per_expenditure remittances) (scatter per_expenditure remittances)

graph export Chapter2.6.png, as(png) name("Graph") replace

reg per_expenditure remittances

margins, at ( remittances==60000)

use "$link\migration_remittances_16_full.dta",clear

gen agehead2=agehead^2

gen HHsize2=HHsize^2

reg food_share ln_expenditure agehead agehead2 primary secondary high_school higher_education HHsize HHsize2 dependency_ratio domestic_remittances overseas_remittances urban RedRiverDelta Northmidlandareas MekongRiverDelta Centralhighlands CentralCoast

//or
global xvar "ln_expenditure agehead agehead2 primary secondary high_school higher_education HHsize HHsize2 dependency_ratio domestic_remittances overseas_remittances urban RedRiverDelta Northmidlandareas MekongRiverDelta Centralhighlands CentralCoast"

regress food_share $xvar 

ereturn list

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: migration_remittances_12_full.dta · migration_remittances_14_full.dta · migration_remittances_16_full.dta · panel121416.dta

Chapter 3 Heteroskedasticity

Residual plot, Breusch-Pagan and White tests, WLS, log model, robust standard errors.

df, meta = pyreadstat.read_dta(
    "rawdata/migration_remittances_16_full.dta",
    encoding="latin1",
)
df.head()
Output
tinh huyen xa diaban hoso num_migration marital_status HHsize agehead num_children0_5 ... durables_share housing_share others_share healthcare_share education_share RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta
0 1 1 4 8 14 NaN 0 2.0 63.0 0.0 ... 0.000000 0.030590 0.021175 0.004854 0.044689 1.0 0.0 0.0 0.0 0.0
1 1 1 4 8 15 NaN 1 5.0 37.0 0.0 ... 0.026955 0.011273 0.006304 0.000797 0.006511 1.0 0.0 0.0 0.0 0.0
2 1 1 4 8 19 NaN 1 2.0 61.0 0.0 ... 0.000000 0.027630 0.013743 0.014355 0.000000 1.0 0.0 0.0 0.0 0.0
3 1 1 7 6 13 NaN 1 3.0 62.0 0.0 ... 0.018952 0.022694 0.014611 0.002366 0.056978 1.0 0.0 0.0 0.0 0.0
4 1 1 7 6 14 NaN 1 5.0 62.0 0.0 ... 0.000000 0.067794 0.004254 0.011658 0.002564 1.0 0.0 0.0 0.0 0.0

5 rows × 65 columns

X = sm.add_constant(df["remittances"])
model = sm.OLS(df["per_expenditure"], X).fit()
print(model.summary())

df["residuals"]         = model.resid
df["squared_residuals"] = df["residuals"] ** 2
df["yhat"]              = model.fittedvalues
df["yhat2"]             = df["yhat"] ** 2
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                  0.018
Method:                 Least Squares   F-statistic:                     177.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.31e-40
Time:                        10:32:42   Log-Likelihood:            -1.0757e+05
No. Observations:                9399   AIC:                         2.152e+05
Df Residuals:                    9397   BIC:                         2.152e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.556e+04    246.728    103.613      0.000    2.51e+04     2.6e+04
remittances     0.1280      0.010     13.336      0.000       0.109       0.147
==============================================================================
Omnibus:                    10743.945   Durbin-Watson:                   1.564
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          1587596.544
Skew:                           5.822   Prob(JB):                         0.00
Kurtosis:                      65.596   Cond. No.                     2.72e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.72e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
lowess_result = lowess(df["residuals"], df["remittances"])

plt.figure(figsize=(10, 6))
plt.scatter(df["remittances"], df["residuals"],
            color=palette[5], alpha=0.5, label="Residuals")
plt.plot(lowess_result[:, 0], lowess_result[:, 1],
         color=palette[1], linewidth=2, label="LOWESS")
plt.axhline(y=0, color="black", linestyle="--")
plt.xlabel("Tiền gửi về (remittances)")
plt.ylabel("Phần dư")
plt.title("Hình 3.2 – Biểu đồ phần dư với LOWESS smoother")
plt.legend()
plt.tight_layout()
plt.show()
OutputOutput of chapter 3, cell 11
# Bước 3 – Hồi quy e² ~ remittances
X_rsq    = sm.add_constant(df["remittances"])
model_bp = sm.OLS(df["squared_residuals"], X_rsq).fit()
print(model_bp.summary())

# Thống kê LM = n * R²
n       = len(df)
LM_bp   = n * model_bp.rsquared
p_bp    = 1 - chi2.cdf(LM_bp, df=1)
print(f"LM statistic : {LM_bp:.4f}")
print(f"P-value      : {p_bp:.6f}")
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      squared_residuals   R-squared:                       0.001
Model:                            OLS   Adj. R-squared:                  0.001
Method:                 Least Squares   F-statistic:                     11.37
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           0.000748
Time:                        10:32:44   Log-Likelihood:            -2.2140e+05
No. Observations:                9399   AIC:                         4.428e+05
Df Residuals:                    9397   BIC:                         4.428e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        4.623e+08   4.48e+07     10.314      0.000    3.74e+08     5.5e+08
remittances  5882.1820   1744.131      3.373      0.001    2463.309    9301.055
==============================================================================
Omnibus:                    22169.834   Durbin-Watson:                   1.963
Prob(Omnibus):                  0.000   Jarque-Bera (JB):        214886940.514
Skew:                          23.723   Prob(JB):                         0.00
Kurtosis:                     742.226   Cond. No.                     2.72e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.72e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
LM statistic : 11.3628
P-value      : 0.000749
bp_test  = het_breuschpagan(df["residuals"], X)
bp_names = ["LM Statistic", "LM p-value", "F Statistic", "F p-value"]
for name, val in zip(bp_names, bp_test):
    print(f"  {name}: {val:.6f}")
# p-value ≈ 0.0007 < 0.05  →  mô hình có phương sai thay đổi
Output
  LM Statistic: 11.362817
  LM p-value: 0.000749
  F Statistic: 11.374150
  F p-value: 0.000748
# Thủ công
df["remittances_sq"] = df["remittances"] ** 2
X_white    = sm.add_constant(df[["remittances", "remittances_sq"]])
model_wt   = sm.OLS(df["squared_residuals"], X_white).fit()
print(model_wt.summary())
print(f"LM White = {n * model_wt.rsquared:.4f}")
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      squared_residuals   R-squared:                       0.002
Model:                            OLS   Adj. R-squared:                  0.001
Method:                 Least Squares   F-statistic:                     7.093
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           0.000835
Time:                        10:32:44   Log-Likelihood:            -2.2139e+05
No. Observations:                9399   AIC:                         4.428e+05
Df Residuals:                    9396   BIC:                         4.428e+05
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const           4.387e+08    4.7e+07      9.343      0.000    3.47e+08    5.31e+08
remittances     9778.8130   2906.196      3.365      0.001    4082.039    1.55e+04
remittances_sq    -0.0137      0.008     -1.676      0.094      -0.030       0.002
==============================================================================
Omnibus:                    22167.782   Durbin-Watson:                   1.963
Prob(Omnibus):                  0.000   Jarque-Bera (JB):        214893217.165
Skew:                          23.717   Prob(JB):                         0.00
Kurtosis:                     742.237   Cond. No.                     9.57e+09
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 9.57e+09. This might indicate that there are
strong multicollinearity or other numerical problems.
LM White = 14.1689
# Hàm có sẵn
white_test = het_white(model.resid, model.model.exog)
for name, val in zip(bp_names, white_test):
    print(f"  {name}: {val:.6f}")
# LM ≈ 14.17, chi2(2), p ≈ 0.0008  →  phương sai thay đổi
Output
  LM Statistic: 14.168901
  LM p-value: 0.000838
  F Statistic: 7.092882
  F p-value: 0.000835
X_wadj    = sm.add_constant(df[["yhat", "yhat2"]])
model_wadj = sm.OLS(df["squared_residuals"], X_wadj).fit()
print(model_wadj.summary())
print(f"LM White (adjusted) = {n * model_wadj.rsquared:.4f}")
# LM ≈ 14.17, chi2(2), p ≈ 0.0008  →  phương sai thay đổi
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      squared_residuals   R-squared:                       0.002
Model:                            OLS   Adj. R-squared:                  0.001
Method:                 Least Squares   F-statistic:                     7.093
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           0.000835
Time:                        10:32:44   Log-Likelihood:            -2.2139e+05
No. Observations:                9399   AIC:                         4.428e+05
Df Residuals:                    9396   BIC:                         4.428e+05
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const      -2.061e+09   8.84e+08     -2.332      0.020   -3.79e+09   -3.29e+08
yhat        1.192e+05   4.58e+04      2.604      0.009    2.95e+04    2.09e+05
yhat2         -0.8380      0.500     -1.676      0.094      -1.818       0.142
==============================================================================
Omnibus:                    22167.782   Durbin-Watson:                   1.963
Prob(Omnibus):                  0.000   Jarque-Bera (JB):        214893217.165
Skew:                          23.717   Prob(JB):                         0.00
Kurtosis:                     742.237   Cond. No.                     1.61e+10
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.61e+10. This might indicate that there are
strong multicollinearity or other numerical problems.
LM White (adjusted) = 14.1689
df2 = df[df["remittances"] > 0].copy()

# Step 1 OLS
X = sm.add_constant(df2["remittances"])
y = df2["per_expenditure"]
ols = sm.OLS(y, X).fit()

# Step 2 |res|
abs_res = np.abs(ols.resid)

# Step 3 weighting equation WITHOUT constant
Z = df2[["remittances"]]   # KHÔNG add_constant
var_model = sm.OLS(abs_res, Z).fit()

sigma_hat = var_model.fittedvalues

# Step 4 weights
w = 1 / (sigma_hat**2)

# Step 5 WLS
wls = sm.WLS(y, X, weights=w).fit()
print(wls.summary())

# Step 6 weighted residuals
wgt_res = wls.resid * np.sqrt(w)

# Step 7 BP test
aux = sm.OLS(wgt_res**2, sm.add_constant(df2["remittances"])).fit()

print(f"F = {aux.fvalue:.2f}, p = {aux.f_pvalue:.4f}")
Output
                            WLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.000
Model:                            WLS   Adj. R-squared:                  0.000
Method:                 Least Squares   F-statistic:                     3.129
Date:                Wed, 08 Apr 2026   Prob (F-statistic):             0.0770
Time:                        10:32:44   Log-Likelihood:            -1.1032e+05
No. Observations:                7953   AIC:                         2.206e+05
Df Residuals:                    7951   BIC:                         2.207e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.484e+04    260.110     95.497      0.000    2.43e+04    2.53e+04
remittances    -2.1016      1.188     -1.769      0.077      -4.431       0.228
==============================================================================
Omnibus:                    17336.833   Durbin-Watson:                   1.580
Prob(Omnibus):                  0.000   Jarque-Bera (JB):        164261972.299
Skew:                          19.387   Prob(JB):                         0.00
Kurtosis:                     705.990   Cond. No.                         236.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
F = 1.59, p = 0.2075
df4 = df[df["remittances"] > 0].copy()
X4  = sm.add_constant(df4["remittances"])
y4  = df4["per_expenditure"]

# WLS với trọng số 1/remittances
w = 1 / df4["remittances"]
model_wls2 = sm.WLS(y4, X4, weights=w).fit()
print(model_wls2.summary())

# weighted residual giống phần trên
wgt_res2 = model_wls2.resid * np.sqrt(w)

# BP test thủ công
aux2 = sm.OLS(wgt_res2**2, sm.add_constant(df4["remittances"])).fit()

print(f"F = {aux2.fvalue:.2f}, p = {aux2.f_pvalue:.4f}")
# p > 0.05 → đã xử lý xong phương sai thay đổi
Output
                            WLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.002
Model:                            WLS   Adj. R-squared:                  0.001
Method:                 Least Squares   F-statistic:                     12.73
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           0.000362
Time:                        10:32:44   Log-Likelihood:                -96022.
No. Observations:                7953   AIC:                         1.920e+05
Df Residuals:                    7951   BIC:                         1.921e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.341e+04    232.068    100.878      0.000     2.3e+04    2.39e+04
remittances     0.3445      0.097      3.568      0.000       0.155       0.534
==============================================================================
Omnibus:                    14341.390   Durbin-Watson:                   1.568
Prob(Omnibus):                  0.000   Jarque-Bera (JB):         43314176.006
Skew:                          12.751   Prob(JB):                         0.00
Kurtosis:                     363.638   Cond. No.                     2.48e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.48e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
F = 2.66, p = 0.1029
df5 = df[(df["remittances"] > 0) & (df["per_expenditure"] > 0)].copy()
df5["ln_remittances"]     = np.log(df5["remittances"])
df5["ln_per_expenditure"] = np.log(df5["per_expenditure"])

X5        = sm.add_constant(df5["ln_remittances"])
model_log = sm.OLS(df5["ln_per_expenditure"], X5).fit()
print(model_log.summary())

bp_log = het_breuschpagan(model_log.resid, model_log.model.exog)
print(f"BP F = {bp_log[2]:.4f}, p = {bp_log[3]:.6f}")
# F ≈ 15.89, p ≈ 0.0001  →  vẫn còn phương sai thay đổi
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.057
Model:                            OLS   Adj. R-squared:                  0.057
Method:                 Least Squares   F-statistic:                     478.7
Date:                Wed, 08 Apr 2026   Prob (F-statistic):          4.40e-103
Time:                        10:32:44   Log-Likelihood:                -7210.2
No. Observations:                7953   AIC:                         1.442e+04
Df Residuals:                    7951   BIC:                         1.444e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const              9.3161      0.032    294.533      0.000       9.254       9.378
ln_remittances     0.0860      0.004     21.878      0.000       0.078       0.094
==============================================================================
Omnibus:                      190.976   Durbin-Watson:                   1.291
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              295.926
Skew:                           0.242   Prob(JB):                     5.50e-65
Kurtosis:                       3.811   Cond. No.                         38.5
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
BP F = 15.8923, p = 0.000068
# yhat và yhat2 đã được tạo ở Phần 2
df_valid = df[df["yhat2"] > 0].copy()
X_v  = sm.add_constant(df_valid["remittances"])
y_v  = df_valid["per_expenditure"]

model_wls3 = sm.WLS(y_v, X_v, weights=1 / df_valid["yhat2"]).fit()
print(model_wls3.summary())
# _cons ≈ 25,114 ; remittances ≈ 0.187 (p=0.000)

bp3 = het_breuschpagan(model_wls3.resid, model_wls3.model.exog)
print(f"BP F = {bp3[2]:.2f}, p = {bp3[3]:.4f}")
# F ≈ 10.25, p = 0.0014  →  vẫn còn phương sai thay đổi
Output
                            WLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.014
Model:                            WLS   Adj. R-squared:                  0.014
Method:                 Least Squares   F-statistic:                     131.0
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.85e-30
Time:                        10:32:44   Log-Likelihood:            -1.0743e+05
No. Observations:                9399   AIC:                         2.149e+05
Df Residuals:                    9397   BIC:                         2.149e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.511e+04    248.091    101.229      0.000    2.46e+04    2.56e+04
remittances     0.1871      0.016     11.447      0.000       0.155       0.219
==============================================================================
Omnibus:                    10745.329   Durbin-Watson:                   1.559
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          1615048.784
Skew:                           5.816   Prob(JB):                         0.00
Kurtosis:                      66.156   Cond. No.                     1.65e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.65e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
BP F = 22.51, p = 0.0000
# Ví dụ 1: per_expenditure ~ remittances (Bảng 3.8)
X = sm.add_constant(df["remittances"])
model_r1 = sm.OLS(df["per_expenditure"], X).fit(cov_type="HC1")
print(model_r1.summary())
# remittances coef ≈ 0.128, Robust SE ≈ 0.0162  (Stata: 0.128, 0.0162)
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                  0.018
Method:                 Least Squares   F-statistic:                     62.33
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.24e-15
Time:                        10:32:44   Log-Likelihood:            -1.0757e+05
No. Observations:                9399   AIC:                         2.152e+05
Df Residuals:                    9397   BIC:                         2.152e+05
Df Model:                           1                                         
Covariance Type:                  HC1                                         
===============================================================================
                  coef    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.556e+04    249.712    102.375      0.000    2.51e+04    2.61e+04
remittances     0.1280      0.016      7.895      0.000       0.096       0.160
==============================================================================
Omnibus:                    10743.945   Durbin-Watson:                   1.564
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          1587596.544
Skew:                           5.822   Prob(JB):                         0.00
Kurtosis:                      65.596   Cond. No.                     2.72e+04
==============================================================================

Notes:
[1] Standard Errors are heteroscedasticity robust (HC1)
[2] The condition number is large, 2.72e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
xvars = [
    "ln_expenditure", "agehead", "agehead2", "primary", "secondary",
    "high_school", "higher_education", "HHsize", "HHsize2",
    "dependency_ratio", "domestic_remittances", "overseas_remittances",
    "urban", "RedRiverDelta", "Northmidlandareas", "MekongRiverDelta",
    "Centralhighlands", "CentralCoast",
]
df["agehead2"] = df["agehead"] ** 2
df["HHsize2"]  = df["HHsize"]  ** 2

df_fs = df.dropna(subset=["food_share"] + xvars).copy()
X_fs  = sm.add_constant(df_fs[xvars])
y_fs  = df_fs["food_share"]

model_ols_fs = sm.OLS(y_fs, X_fs).fit()
model_rob_fs = sm.OLS(y_fs, X_fs).fit(cov_type="HC1")

print("=== OLS ===")
print(model_ols_fs.summary())
print("\n=== Robust SE ===")
print(model_rob_fs.summary())

# Kiểm định BP & White
bp_fs    = het_breuschpagan(model_ols_fs.resid, model_ols_fs.model.exog)
white_fs = het_white(model_ols_fs.resid, model_ols_fs.model.exog)
print(f"BP  F = {bp_fs[2]:.2f},    p = {bp_fs[3]:.2e}")
print(f"White LM = {white_fs[0]:.2f}, p = {white_fs[1]:.2e}")
Output
=== OLS ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             food_share   R-squared:                       0.691
Model:                            OLS   Adj. R-squared:                  0.691
Method:                 Least Squares   F-statistic:                     1041.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:32:44   Log-Likelihood:                 13344.
No. Observations:                8381   AIC:                        -2.665e+04
Df Residuals:                    8362   BIC:                        -2.652e+04
Df Model:                          18                                         
Covariance Type:            nonrobust                                         
========================================================================================
                           coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------------
const                    0.8971      0.013     69.272      0.000       0.872       0.922
ln_expenditure          -0.0383      0.001    -34.788      0.000      -0.040      -0.036
agehead                 -0.0006      0.000     -2.167      0.030      -0.001   -5.47e-05
agehead2              6.104e-06    2.5e-06      2.442      0.015     1.2e-06     1.1e-05
primary                  0.0007      0.002      0.440      0.660      -0.002       0.004
secondary                0.0002      0.002      0.102      0.919      -0.003       0.003
high_school             -0.0005      0.002     -0.226      0.822      -0.004       0.003
higher_education         0.0015      0.003      0.581      0.561      -0.004       0.007
HHsize                  -0.1135      0.001    -78.683      0.000      -0.116      -0.111
HHsize2                  0.0086      0.000     58.678      0.000       0.008       0.009
dependency_ratio        -0.0017      0.001     -1.887      0.059      -0.003    6.47e-05
domestic_remittances    -0.0014      0.001     -0.990      0.322      -0.004       0.001
overseas_remittances    -0.0015      0.003     -0.512      0.608      -0.007       0.004
urban                    0.0124      0.001      9.450      0.000       0.010       0.015
RedRiverDelta           -0.0031      0.002     -1.557      0.120      -0.007       0.001
Northmidlandareas       -0.0043      0.002     -2.084      0.037      -0.008      -0.000
MekongRiverDelta        -0.0084      0.002     -4.222      0.000      -0.012      -0.005
Centralhighlands        -0.0112      0.003     -4.329      0.000      -0.016      -0.006
CentralCoast            -0.0010      0.002     -0.524      0.600      -0.005       0.003
==============================================================================
Omnibus:                     3937.239   Durbin-Watson:                   1.877
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            81037.717
Skew:                           1.765   Prob(JB):                         0.00
Kurtosis:                      17.819   Cond. No.                     7.09e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.09e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

=== Robust SE ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             food_share   R-squared:                       0.691
Model:                            OLS   Adj. R-squared:                  0.691
Method:                 Least Squares   F-statistic:                     279.9
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:32:44   Log-Likelihood:                 13344.
No. Observations:                8381   AIC:                        -2.665e+04
Df Residuals:                    8362   BIC:                        -2.652e+04
Df Model:                          18                                         
Covariance Type:                  HC1                                         
========================================================================================
                           coef    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------------
const                    0.8971      0.018     49.689      0.000       0.862       0.932
ln_expenditure          -0.0383      0.001    -26.135      0.000      -0.041      -0.035
agehead                 -0.0006      0.000     -1.758      0.079      -0.001    6.59e-05
agehead2              6.104e-06      3e-06      2.034      0.042    2.23e-07     1.2e-05
primary                  0.0007      0.002      0.434      0.665      -0.002       0.004
secondary                0.0002      0.002      0.102      0.919      -0.003       0.003
high_school             -0.0005      0.002     -0.226      0.821      -0.004       0.003
higher_education         0.0015      0.002      0.609      0.543      -0.003       0.006
HHsize                  -0.1135      0.004    -27.609      0.000      -0.122      -0.105
HHsize2                  0.0086      0.000     19.240      0.000       0.008       0.009
dependency_ratio        -0.0017      0.001     -2.347      0.019      -0.003      -0.000
domestic_remittances    -0.0014      0.002     -0.929      0.353      -0.004       0.002
overseas_remittances    -0.0015      0.003     -0.515      0.607      -0.007       0.004
urban                    0.0124      0.001      8.876      0.000       0.010       0.015
RedRiverDelta           -0.0031      0.002     -1.49
df_wage, _ = pyreadstat.read_dta(
    "rawdata/wage2020.dta",
    encoding="latin1",
)

wage_vars  = ["urban", "gender", "yearsofedu", "yearsofexperience"]
X_w = sm.add_constant(df_wage[wage_vars])
y_w = df_wage["wage"]

model_ols_w = sm.OLS(y_w, X_w).fit()
model_rob_w = sm.OLS(y_w, X_w).fit(cov_type="HC1")

print("=== OLS (Bảng 3.10) ===")
print(model_ols_w.summary())
print("\n=== Robust SE (Bảng 3.11) ===")
print(model_rob_w.summary())

bp_w    = het_breuschpagan(model_ols_w.resid, model_ols_w.model.exog)
white_w = het_white(model_ols_w.resid, model_ols_w.model.exog)
print(f"BP  F = {bp_w[2]:.2f},   p = {bp_w[3]:.2e}")
print(f"White LM = {white_w[0]:.2f}, p = {white_w[1]:.2e}")
Output
=== OLS (Bảng 3.10) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.200
Model:                            OLS   Adj. R-squared:                  0.200
Method:                 Least Squares   F-statistic:                     633.0
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:32:47   Log-Likelihood:            -1.2341e+05
No. Observations:               10118   AIC:                         2.468e+05
Df Residuals:                   10113   BIC:                         2.469e+05
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              1.096e+04   2148.704      5.101      0.000    6748.303    1.52e+04
urban              2.233e+04   1037.454     21.525      0.000    2.03e+04    2.44e+04
gender            -1.453e+04    966.347    -15.035      0.000   -1.64e+04   -1.26e+04
yearsofedu         5781.1773    161.878     35.713      0.000    5463.865    6098.490
yearsofexperience   422.6402     42.581      9.926      0.000     339.174     506.107
==============================================================================
Omnibus:                     6384.033   Durbin-Watson:                   1.440
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           180008.186
Skew:                           2.566   Prob(JB):                         0.00
Kurtosis:                      23.016   Cond. No.                         122.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

=== Robust SE (Bảng 3.11) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.200
Model:                            OLS   Adj. R-squared:                  0.200
Method:                 Least Squares   F-statistic:                     452.9
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:32:47   Log-Likelihood:            -1.2341e+05
No. Observations:               10118   AIC:                         2.468e+05
Df Residuals:                   10113   BIC:                         2.469e+05
Df Model:                           4                                         
Covariance Type:                  HC1                                         
=====================================================================================
                        coef    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              1.096e+04   2064.348      5.309      0.000    6914.142     1.5e+04
urban              2.233e+04   1104.230     20.223      0.000    2.02e+04    2.45e+04
gender            -1.453e+04    935.858    -15.525      0.000   -1.64e+04   -1.27e+04
yearsofedu         5781.1773    163.796     35.295      0.000    5460.143    6102.211
yearsofexperience   422.6402     42.741      9.888      0.000     338.868     506.412
==============================================================================
Omnibus:                     6384.033   Durbin-Watson:                   1.440
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           180008.186
Skew:                           2.566   Prob(JB):                         0.00
Kurtosis:                      23.016   Cond. No.                         122.
==============================================================================

Notes:
[1] Standard Errors are heteroscedasticity robust (HC1)
BP  F = 56.76,   p = 1.96e-47
White LM = 346.67, p = 7.06e-67
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(lmtest); library(sandwich); library(ggplot2)

# Point data_dir at the repo's data folder (or set env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

if (!dir.exists('figures')) dir.create('figures')

# Chapter 3 - Heteroskedasticity
# --- Read data
df <- read_dta(file.path(data_dir, 'migration_remittances_16_full.dta'))

df <- as.data.frame(zap_labels(df))

head(df)
Output
  tinh huyen xa diaban hoso num_migration marital_status HHsize agehead
1    1     1  4      8   14            NA              0      2      63
2    1     1  4      8   15            NA              1      5      37
3    1     1  4      8   19            NA              1      2      61
4    1     1  7      6   13            NA              1      3      62
5    1     1  7      6   14            NA              1      5      62
6    1     1  7      6   20            NA              1      4      45
  num_children0_5 num_children6_14 num_elderly_members children15 elderly60
1               0                0                   0          0         1
2               0                2                   0          2         1
3               0                0                   0          0         1
4               0                1                   0          1         1
5               0                1                   0          1         1
6               0                2                   0          2         0
  dependency_ratio genderhead female_ratio per_income urban ethnicity education
1        1.0000000          1    0.5000000      51000     1         1    5160.0
2        1.5000000          0    0.8000000     128520     1         1    3894.0
3        1.0000000          0    0.5000000     108096     1         1       0.0
4               NA          0    0.3333333     108000     1         1    9320.0
5        0.6666667          0    0.8000000      70680     1         1     850.0
6        1.0000000          0    0.5000000     118824     1         1    7907.5
  healthcare  others durables     food non_food housing expenditure
1      560.5 2445.00        0 32931.50 13103.00  3532.0      115464
2      476.8 3770.00    16120 39511.20 49092.00  6741.6      598028
3     1700.0 1627.50        0 36528.00 16084.00  3272.0      118423
4      387.0 2390.00     3100 25041.33 10573.33  3712.0      163571
5     3864.2 1410.00        0 26206.60 11492.00 22472.0      331474
6      467.5 3101.25    21500 55984.25 52470.00  5772.0      588810
  domestic_remittances overseas_remittances remittances num_eduhead primary
1                    1                    0       60000          12       0
2                    1                    1       65000          12       0
3                    1                    0        5000          12       0
4                    1                    0        7000          12       0
5                    1                    0       10000           9       0
6                    1                    0        8000          12       0
  secondary high_school higher_education num_least_highschool business
1         0           0                1                    1        0
2         0           0                1                    1        0
3         0           0                1                    1        0
4         0           0                1                    1        0
5         1           0                0                    0        0
6         0           0                1                    1        1
  migration per_expenditure children_ratio elderly_ratio ln_per_income
1         0        57732.00      0.0000000     0.5000000      10.83958
2         0       119605.60      0.4000000     0.2000000      11.76384
3         0        59211.50      0.0000000     0.5000000      11.59077
4         0        54523.67      0.3333333     0.3333333      11.58989
5         0        66294.80      0.2000000     0.2000000      11.16592
6         0       147202.50      0.5000000     0.0000000      11.68540
  ln_per_expenditure ln_expenditure  ln_food ln_non_food ln_durables ln_housing
1           10.96357       11.65671 10.40218    9.480597          NA   8.169620
2           11.69195       13.30139 10.58434   10.801452    9.687816   8.816052
3           10.98887       11.68202 10.50583    9.685580          NA   8.093157
4           10.90639       12.00500 10.12828    9.266090    8.039157   8.219326
5           11.10187       12.71130 10.17377    9.349406          NA  10.020025
6           11.89956       13.28586 10.93283   10.867997    9.975808   8.660774
  ln_others ln_healthcare ln_education ln_remittances food_share non_food_share
1  7.801800      6.328829     8.548692      11.002100 0.28521010     0.11348126
2  8.234830      6.167097     8.267192      11.082143 0.06606915     0.08208980
3  7.394800      7.438384           NA       8.517193 0.30845359     0.13581821
4  7.779048      5.958425     9.139918       8.853665 0.15309152     0.06464063
5  7.251345      8.259510     6.745236       9.210340 0.07906080     0.03466938
6  8.039560      6.147399     8.975567       8.987197 0.09508033     0.08911194
  durables_share housing_share others_share healthcare_share education_share
1     0.00000000   0.030589622  0.021175431     0.0048543271     0.044689253
2     0.02695526   0.011273051  0.006304053     0.0007972871     0.006511401
3     0.00000000   0.027629768  0.013743107     0.0143553196     0.000000000
4     0.01895201   0.022693509  0.014611392     0.0023659451     0.056978315
5     0.00000000   0.067794159  0.004253727     0.0116576264     0.002564304
6     0.03651433   0.009802823  0.005266979     0.0007939743     0.013429630
  RedRiverDelta Northmidlandareas CentralCoast Centralhighlands
1             1                 0            0                0
2             1                 0            0                0
3             1                 0            0                0
4             1                 0            0                0
5             1                 0            0                0
6             1                 0            0                0
  MekongRiverDelta
1                0
2                0
3                0
4                0
5                0
6                0
# --- 3.1 What is heteroskedasticity?
# OLS stays unbiased but is no longer BLUE; usual standard errors are wrong.

# --- 3.2 Detecting heteroskedasticity
# Step 1: original OLS and residuals
model <- lm(per_expenditure ~ remittances, data = df)

print(summary(model))
Output
Call:
lm(formula = per_expenditure ~ remittances, data = df)

Residuals:
   Min     1Q Median     3Q    Max 
-67602 -11976  -5051   5543 431360 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 2.556e+04  2.467e+02  103.61   <2e-16 ***
remittances 1.280e-01  9.601e-03   13.34   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 22620 on 9397 degrees of freedom
Multiple R-squared:  0.01857,	Adjusted R-squared:  0.01847 
F-statistic: 177.8 on 1 and 9397 DF,  p-value: < 2.2e-16
df$residuals <- resid(model)

df$squared_residuals <- df$residuals^2

df$yhat <- fitted(model)

df$yhat2 <- df$yhat^2

# Informal method: residual plot with LOWESS (Figure 3.2)
p <- ggplot(df, aes(remittances, residuals)) +
  geom_point(color = '#88837d', alpha = 0.5) +
  geom_smooth(method = 'loess', se = FALSE, color = '#a31414') +
  geom_hline(yintercept = 0, linetype = 'dashed') +
  labs(x = 'Remittances', y = 'Residuals',
       title = 'Figure 3.2 - Residual plot with smoother')

ggsave('figures/fig3_2.png', p, width = 8, height = 5)
OutputR output: fig3_2.png
# Breusch-Pagan test (Table 3.1), manual
model_bp <- lm(squared_residuals ~ remittances, data = df)

print(summary(model_bp))
Output
Call:
lm(formula = squared_residuals ~ remittances, data = df)

Residuals:
       Min         1Q     Median         3Q        Max 
-4.019e+09 -4.582e+08 -3.893e+08 -2.500e+08  1.856e+11 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 462257871   44818977  10.314  < 2e-16 ***
remittances      5882       1744   3.373 0.000748 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.109e+09 on 9397 degrees of freedom
Multiple R-squared:  0.001209,	Adjusted R-squared:  0.001103 
F-statistic: 11.37 on 1 and 9397 DF,  p-value: 0.0007477
n <- nrow(df)

LM_bp <- n * summary(model_bp)$r.squared

cat(sprintf('LM statistic : %.4f\nP-value      : %.6f\n', LM_bp, 1 - pchisq(LM_bp, 1)))
Output
LM statistic : 11.3628
P-value      : 0.000749
# Built-in BP test (studentized/Koenker = statsmodels het_breuschpagan)
print(bptest(model))
Output
	studentized Breusch-Pagan test

data:  model
BP = 11.363, df = 1, p-value = 0.0007493
print(summary(model_bp)$fstatistic)
Output
     value      numdf      dendf 
  11.37415    1.00000 9397.00000 
# White test (Table 3.2), manual
df$remittances_sq <- df$remittances^2

model_wt <- lm(squared_residuals ~ remittances + remittances_sq, data = df)

print(summary(model_wt))
Output
Call:
lm(formula = squared_residuals ~ remittances + remittances_sq, 
    data = df)

Residuals:
       Min         1Q     Median         3Q        Max 
-1.900e+09 -4.428e+08 -3.792e+08 -2.390e+08  1.856e+11 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)     4.387e+08  4.696e+07   9.343  < 2e-16 ***
remittances     9.779e+03  2.906e+03   3.365 0.000769 ***
remittances_sq -1.374e-02  8.197e-03  -1.676 0.093745 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.108e+09 on 9396 degrees of freedom
Multiple R-squared:  0.001507,	Adjusted R-squared:  0.001295 
F-statistic: 7.093 on 2 and 9396 DF,  p-value: 0.0008355
cat(sprintf('LM White = %.4f\n', n * summary(model_wt)$r.squared))
Output
LM White = 14.1689
# Built-in
print(bptest(model, ~ remittances + I(remittances^2), data = df))
Output
	studentized Breusch-Pagan test

data:  model
BP = 14.169, df = 2, p-value = 0.000838
# Adjusted White test (Table 3.3): e^2 on yhat and yhat^2
model_wadj <- lm(squared_residuals ~ yhat + yhat2, data = df)

print(summary(model_wadj))
Output
Call:
lm(formula = squared_residuals ~ yhat + yhat2, data = df)

Residuals:
       Min         1Q     Median         3Q        Max 
-1.900e+09 -4.428e+08 -3.792e+08 -2.390e+08  1.856e+11 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)   
(Intercept) -2.061e+09  8.839e+08  -2.332  0.01972 * 
yhat         1.192e+05  4.579e+04   2.604  0.00924 **
yhat2       -8.380e-01  4.999e-01  -1.676  0.09375 . 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.108e+09 on 9396 degrees of freedom
Multiple R-squared:  0.001507,	Adjusted R-squared:  0.001295 
F-statistic: 7.093 on 2 and 9396 DF,  p-value: 0.0008355
cat(sprintf('LM White (adjusted) = %.4f\n', n * summary(model_wadj)$r.squared))
Output
LM White (adjusted) = 14.1689
# --- 3.3 Remedies
# 1. WLS with Var(e) proportional to x^2 (Table 3.4)
df2 <- df[df$remittances > 0, ]

ols <- lm(per_expenditure ~ remittances, data = df2)

abs_res <- abs(resid(ols))

var_model <- lm(abs_res ~ 0 + remittances, data = df2)   # no constant

sigma_hat <- fitted(var_model)

w <- 1 / sigma_hat^2

wls <- lm(per_expenditure ~ remittances, data = df2, weights = w)

print(summary(wls))
Output
Call:
lm(formula = per_expenditure ~ remittances, data = df2, weights = w)

Weighted Residuals:
    Min      1Q  Median      3Q     Max 
-2032.7   -12.4     7.2    15.4 19619.9 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 24839.723    260.110  95.497   <2e-16 ***
remittances    -2.102      1.188  -1.769    0.077 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 428.6 on 7951 degrees of freedom
Multiple R-squared:  0.0003933,	Adjusted R-squared:  0.0002676 
F-statistic: 3.129 on 1 and 7951 DF,  p-value: 0.07697
wgt_res <- resid(wls) * sqrt(w)

aux <- lm(wgt_res^2 ~ remittances, data = df2)

fs <- summary(aux)$fstatistic

cat(sprintf('F = %.2f, p = %.4f\n', fs[1], pf(fs[1], fs[2], fs[3], lower.tail = FALSE)))
Output
F = 1.59, p = 0.2075
# Note: BP test after WLS may differ from Stata (residual/weight handling).

# 2. WLS with Var(e) proportional to x (Table 3.5)
df4 <- df[df$remittances > 0, ]

w <- 1 / df4$remittances

model_wls2 <- lm(per_expenditure ~ remittances, data = df4, weights = w)

print(summary(model_wls2))
Output
Call:
lm(formula = per_expenditure ~ remittances, data = df4, weights = w)

Weighted Residuals:
   Min     1Q Median     3Q    Max 
 -3110   -192    -67    104  31983 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 2.341e+04  2.321e+02 100.878  < 2e-16 ***
remittances 3.446e-01  9.658e-02   3.568 0.000362 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 830.5 on 7951 degrees of freedom
Multiple R-squared:  0.001598,	Adjusted R-squared:  0.001473 
F-statistic: 12.73 on 1 and 7951 DF,  p-value: 0.0003623
wgt_res2 <- resid(model_wls2) * sqrt(w)

aux2 <- lm(wgt_res2^2 ~ remittances, data = df4)

fs <- summary(aux2)$fstatistic

cat(sprintf('F = %.2f, p = %.4f\n', fs[1], pf(fs[1], fs[2], fs[3], lower.tail = FALSE)))
Output
F = 2.66, p = 0.1029
# 3. Log transformation
df5 <- df[df$remittances > 0 & df$per_expenditure > 0, ]

df5$ln_remittances <- log(df5$remittances)

df5$ln_per_expenditure <- log(df5$per_expenditure)

model_log <- lm(ln_per_expenditure ~ ln_remittances, data = df5)

print(summary(model_log))
Output
Call:
lm(formula = ln_per_expenditure ~ ln_remittances, data = df5)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.38075 -0.39634 -0.00383  0.37776  3.03454 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)    
(Intercept)     9.31613    0.03163  294.53   <2e-16 ***
ln_remittances  0.08597    0.00393   21.88   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5992 on 7951 degrees of freedom
Multiple R-squared:  0.05678,	Adjusted R-squared:  0.05666 
F-statistic: 478.7 on 1 and 7951 DF,  p-value: < 2.2e-16
bp_log <- bptest(model_log)

aux_log <- summary(lm(resid(model_log)^2 ~ ln_remittances, data = df5))$fstatistic

cat(sprintf('BP F = %.4f, p = %.6f\n', aux_log[1], pf(aux_log[1], aux_log[2], aux_log[3], lower.tail = FALSE)))
Output
BP F = 15.8923, p = 0.000068
print(bp_log)
Output
	studentized Breusch-Pagan test

data:  model_log
BP = 15.865, df = 1, p-value = 6.804e-05
# 4. WLS with weights 1/yhat^2 (Table 3.7)
df_valid <- df[df$yhat2 > 0, ]

model_wls3 <- lm(per_expenditure ~ remittances, data = df_valid, weights = 1 / df_valid$yhat2)

print(summary(model_wls3))
Output
Call:
lm(formula = per_expenditure ~ remittances, data = df_valid, 
    weights = 1/df_valid$yhat2)

Weighted Residuals:
    Min      1Q  Median      3Q     Max 
-1.0951 -0.4513 -0.1889  0.2118 16.6512 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 2.511e+04  2.481e+02  101.23   <2e-16 ***
remittances 1.871e-01  1.635e-02   11.45   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8402 on 9397 degrees of freedom
Multiple R-squared:  0.01375,	Adjusted R-squared:  0.01365 
F-statistic:   131 on 1 and 9397 DF,  p-value: < 2.2e-16
# statsmodels het_breuschpagan on raw wls.resid (unweighted residuals)
aux3 <- summary(lm(resid(model_wls3)^2 ~ remittances, data = df_valid))$fstatistic

cat(sprintf('BP F = %.2f, p = %.4f\n', aux3[1], pf(aux3[1], aux3[2], aux3[3], lower.tail = FALSE)))
Output
BP F = 22.51, p = 0.0000
# 5. Robust standard errors (Table 3.8), HC1 = Stata 'robust'
print(coeftest(model, vcov = vcovHC(model, type = 'HC1')))
Output
t test of coefficients:

              Estimate Std. Error  t value  Pr(>|t|)    
(Intercept) 2.5564e+04 2.4971e+02 102.3753 < 2.2e-16 ***
remittances 1.2804e-01 1.6219e-02   7.8947 3.236e-15 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Example 2: food_share with many regressors (Table 3.9)
df$agehead2 <- df$agehead^2

df$HHsize2 <- df$HHsize^2

xvars <- c('ln_expenditure','agehead','agehead2','primary','secondary','high_school',
           'higher_education','HHsize','HHsize2','dependency_ratio','domestic_remittances',
           'overseas_remittances','urban','RedRiverDelta','Northmidlandareas',
           'MekongRiverDelta','Centralhighlands','CentralCoast')

df_fs <- df[complete.cases(df[, c('food_share', xvars)]), ]

f_fs <- reformulate(xvars, response = 'food_share')

model_ols_fs <- lm(f_fs, data = df_fs)

cat('=== OLS ===\n'); print(summary(model_ols_fs))
Output
=== OLS ===

Call:
lm(formula = f_fs, data = df_fs)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.31121 -0.02293  0.00076  0.02161  0.53028 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
(Intercept)           8.971e-01  1.295e-02  69.272  < 2e-16 ***
ln_expenditure       -3.831e-02  1.101e-03 -34.788  < 2e-16 ***
agehead              -5.739e-04  2.648e-04  -2.167   0.0303 *  
agehead2              6.104e-06  2.500e-06   2.442   0.0146 *  
primary               7.075e-04  1.607e-03   0.440   0.6598    
secondary             1.662e-04  1.637e-03   0.102   0.9191    
high_school          -4.539e-04  2.012e-03  -0.226   0.8215    
higher_education      1.488e-03  2.561e-03   0.581   0.5613    
HHsize               -1.135e-01  1.443e-03 -78.683  < 2e-16 ***
HHsize2               8.610e-03  1.467e-04  58.678  < 2e-16 ***
dependency_ratio     -1.659e-03  8.791e-04  -1.887   0.0592 .  
domestic_remittances -1.429e-03  1.444e-03  -0.990   0.3224    
overseas_remittances -1.482e-03  2.893e-03  -0.512   0.6084    
urban                 1.239e-02  1.311e-03   9.450  < 2e-16 ***
RedRiverDelta        -3.150e-03  2.023e-03  -1.557   0.1195    
Northmidlandareas    -4.311e-03  2.069e-03  -2.084   0.0372 *  
MekongRiverDelta     -8.437e-03  1.998e-03  -4.222 2.45e-05 ***
Centralhighlands     -1.116e-02  2.577e-03  -4.329 1.52e-05 ***
CentralCoast         -1.039e-03  1.981e-03  -0.524   0.6001    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.04929 on 8362 degrees of freedom
Multiple R-squared:  0.6914,	Adjusted R-squared:  0.6908 
F-statistic:  1041 on 18 and 8362 DF,  p-value: < 2.2e-16
cat('=== Robust SE ===\n'); print(coeftest(model_ols_fs, vcov = vcovHC(model_ols_fs, type = 'HC1')))
Output
=== Robust SE ===

t test of coefficients:

                        Estimate  Std. Error  t value  Pr(>|t|)    
(Intercept)           8.9705e-01  1.8053e-02  49.6891 < 2.2e-16 ***
ln_expenditure       -3.8305e-02  1.4657e-03 -26.1349 < 2.2e-16 ***
agehead              -5.7389e-04  3.2641e-04  -1.7582   0.07875 .  
agehead2              6.1043e-06  3.0007e-06   2.0343   0.04196 *  
primary               7.0752e-04  1.6320e-03   0.4335   0.66464    
secondary             1.6624e-04  1.6290e-03   0.1021   0.91872    
high_school          -4.5388e-04  2.0058e-03  -0.2263   0.82098    
higher_education      1.4880e-03  2.4454e-03   0.6085   0.54287    
HHsize               -1.1353e-01  4.1122e-03 -27.6089 < 2.2e-16 ***
HHsize2               8.6100e-03  4.4750e-04  19.2401 < 2.2e-16 ***
dependency_ratio     -1.6586e-03  7.0656e-04  -2.3475   0.01893 *  
domestic_remittances -1.4291e-03  1.5383e-03  -0.9291   0.35288    
overseas_remittances -1.4822e-03  2.8785e-03  -0.5149   0.60661    
urban                 1.2391e-02  1.3960e-03   8.8756 < 2.2e-16 ***
RedRiverDelta        -3.1495e-03  2.1049e-03  -1.4963   0.13462    
Northmidlandareas    -4.3108e-03  2.1583e-03  -1.9973   0.04583 *  
MekongRiverDelta     -8.4370e-03  2.1657e-03  -3.8957 9.866e-05 ***
Centralhighlands     -1.1156e-02  2.4896e-03  -4.4812 7.521e-06 ***
CentralCoast         -1.0387e-03  2.0527e-03  -0.5060   0.61285    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
bp_fs <- bptest(model_ols_fs)

cat(sprintf('N = %d\n', nobs(model_ols_fs)))
Output
N = 8381
print(bp_fs)
Output
	studentized Breusch-Pagan test

data:  model_ols_fs
BP = 1844, df = 18, p-value < 2.2e-16
fsb <- summary(lm(resid(model_ols_fs)^2 ~ ., data = df_fs[, xvars]))$fstatistic

cat(sprintf('BP F = %.2f, p = %.2e\n', fsb[1], pf(fsb[1], fsb[2], fsb[3], lower.tail = FALSE)))
Output
BP F = 131.04, p = 0.00e+00
# White (full): regressors, squares and cross-products (as statsmodels het_white)
white_fs <- bptest(model_ols_fs, as.formula(paste('~ (', paste(xvars, collapse = '+'), ')^2 +',
                   paste0('I(', xvars, '^2)', collapse = '+'))), data = df_fs)

print(white_fs)
Output
	studentized Breusch-Pagan test

data:  model_ols_fs
BP = 3390.9, df = 159, p-value < 2.2e-16
# Example 3: wage regression (Tables 3.10-3.11)
df_wage <- as.data.frame(zap_labels(read_dta(file.path(data_dir, 'wage2020.dta'))))

model_ols_w <- lm(wage ~ urban + gender + yearsofedu + yearsofexperience, data = df_wage)

cat('=== OLS (Table 3.10) ===\n'); print(summary(model_ols_w))
Output
=== OLS (Table 3.10) ===

Call:
lm(formula = wage ~ urban + gender + yearsofedu + yearsofexperience, 
    data = df_wage)

Residuals:
    Min      1Q  Median      3Q     Max 
-119710  -29082   -4699   20680  755501 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)        10960.19    2148.70   5.101 3.44e-07 ***
urban              22330.79    1037.45  21.525  < 2e-16 ***
gender            -14529.32     966.35 -15.035  < 2e-16 ***
yearsofedu          5781.18     161.88  35.713  < 2e-16 ***
yearsofexperience    422.64      42.58   9.926  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47990 on 10113 degrees of freedom
Multiple R-squared:  0.2002,	Adjusted R-squared:  0.1999 
F-statistic:   633 on 4 and 10113 DF,  p-value: < 2.2e-16
cat('=== Robust SE (Table 3.11) ===\n'); print(coeftest(model_ols_w, vcov = vcovHC(model_ols_w, type = 'HC1')))
Output
=== Robust SE (Table 3.11) ===

t test of coefficients:

                    Estimate Std. Error  t value  Pr(>|t|)    
(Intercept)        10960.189   2064.348   5.3093 1.124e-07 ***
urban              22330.790   1104.230  20.2229 < 2.2e-16 ***
gender            -14529.318    935.858 -15.5251 < 2.2e-16 ***
yearsofedu          5781.177    163.796  35.2950 < 2.2e-16 ***
yearsofexperience    422.640     42.741   9.8883 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
print(bptest(model_ols_w))
Output
	studentized Breusch-Pagan test

data:  model_ols_w
BP = 222.17, df = 4, p-value < 2.2e-16
wv <- c('urban','gender','yearsofedu','yearsofexperience')

white_w <- bptest(model_ols_w, as.formula(paste('~ (', paste(wv, collapse = '+'), ')^2 +',
                  paste0('I(', wv, '^2)', collapse = '+'))), data = df_wage)

print(white_w)
Output
	studentized Breusch-Pagan test

data:  model_ols_w
BP = 346.67, df = 12, p-value < 2.2e-16
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chapter3" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chapter3" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 3                                                 */
/*      File Name:  chapter3.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Heteroskedasticity                            */  
/*      Input File:     migration_remittances_16_full.dta         */
/*                      wage2020.dta                              */  
/*      Output File:    chapter3.log                               */  
/******************************************************************/ 

log using chapter3.log, text replace

use "$link\migration_remittances_16_full.dta",clear

quietly regress per_expenditure remittances

predict r, residual 

twoway (scatter r remittances)(lowess r remittances),yline(0)

graph export Chapter3.2.png, as(png) name("Graph") replace

use "$link\migration_remittances_16_full.dta",clear

**# Kiểm định Breusch–Pagan
//Bước 1:Ước lượng mô hình hồi quy.

quietly reg per_expenditure remittances 

//Bước 2:Lấy phần dư e và bình phương phần dư e^2

predict r, residual 
gen rsq = r^2

//Bước 3: Hồi quy bình phương phần dư với tất cả các biến độc lập từ mô hình OLS gốc

reg rsq remittances 

// Kiểm định Breusch–Pagan bằng lệnh stata
quietly reg per_expenditure remittances 
hettest,rhs fstat

**# Kiểm định White thông thường

quietly reg rsq remittances c.remittances#c.remittances
display "LMwhite: " e(N)*e(r2)

// Kiểm định White test bằng lệnh stata
quietly reg per_expenditure remittances
imtest,white

**# Kiểm định White có điều chỉnh
//Bước 1: Hồi quy mô hình OLS

quietly reg per_expenditure remittances

//Bước 2: Tạo biến mới đặt tên là yhat và yhat2, với yhat là biến chứa giá trị dự báo của biến phụ thuộc.

predict yhat,xb
gen yhat2=yhat^2

//Bước 3: Hồi quy phần dư của mô hình với hai biến yhat và yhat2

reg rsq yhat yhat2

**# Sử dụng bình phương nhỏ nhất có trọng số (Weighted Least Squares: WLS)

//Tìm findit wls chọn cài đặt wls0

wls0  per_expenditure remittances , wvar( remittances ) type(abse) noconst

hettest,rhs fstat

gen remittances_sqrt = sqrt(remittances)

wls0 per_expenditure remittances  , wvar(remittances_sqrt) type(abse) noconst

hettest,rhs fstat

**# Lấy log cho các biến

reg ln_per_expenditure ln_remittances

hettest,rhs fstat

**# Chọn trọng số là giá trị dự báo yhat

wls0 per_expenditure remittances  , wvar(yhat) type(abse) noconst

hettest,rhs fstat

reg per_expenditure remittances ,robust

**# Mô hình chi tiêu thực phẩm

gen agehead2=agehead^2

gen HHsize2=HHsize^2

global xvar "ln_expenditure agehead agehead2 primary secondary high_school higher_education HHsize HHsize2 dependency_ratio domestic_remittances overseas_remittances urban RedRiverDelta Northmidlandareas MekongRiverDelta Centralhighlands CentralCoast"

quietly regress food_share $xvar 

hettest,rhs fstat

imtest,white

regress food_share $xvar,robust

**# Mô hình tiền lương

use "$link\wage2020.dta", clear

quietly regress wage urban gender yearsofedu yearsofexperience

hettest,rhs fstat

imtest,white

regress wage urban gender yearsofedu yearsofexperience,robust

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: migration_remittances_16_full.dta · wage2020.dta

Chapter 4 Specification and endogeneity

Omitted variables, RESET, irrelevant variables, multicollinearity, outliers, normality, IV/2SLS.

df, meta = pyreadstat.read_dta(
    "rawdata/migration_remittances_16_full.dta",
    encoding="latin1",
)
df.head()
Output
tinh huyen xa diaban hoso num_migration marital_status HHsize agehead num_children0_5 ... durables_share housing_share others_share healthcare_share education_share RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta
0 1 1 4 8 14 NaN 0 2.0 63.0 0.0 ... 0.000000 0.030590 0.021175 0.004854 0.044689 1.0 0.0 0.0 0.0 0.0
1 1 1 4 8 15 NaN 1 5.0 37.0 0.0 ... 0.026955 0.011273 0.006304 0.000797 0.006511 1.0 0.0 0.0 0.0 0.0
2 1 1 4 8 19 NaN 1 2.0 61.0 0.0 ... 0.000000 0.027630 0.013743 0.014355 0.000000 1.0 0.0 0.0 0.0 0.0
3 1 1 7 6 13 NaN 1 3.0 62.0 0.0 ... 0.018952 0.022694 0.014611 0.002366 0.056978 1.0 0.0 0.0 0.0 0.0
4 1 1 7 6 14 NaN 1 5.0 62.0 0.0 ... 0.000000 0.067794 0.004254 0.011658 0.002564 1.0 0.0 0.0 0.0 0.0

5 rows × 65 columns

df["agehead2"] = df["agehead"] ** 2

xvars_full1 = ["remittances", "HHsize", "children15", "elderly60",
               "female_ratio", "genderhead", "agehead", "agehead2", "num_eduhead"]
X1_r = sm.add_constant(df["remittances"])
m1_r = sm.OLS(df["per_expenditure"], X1_r).fit()
print(m1_r.summary())
# N=9,399 | F(1,9397)=177.85 | R²=0.0186
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                  0.018
Method:                 Least Squares   F-statistic:                     177.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.31e-40
Time:                        10:41:08   Log-Likelihood:            -1.0757e+05
No. Observations:                9399   AIC:                         2.152e+05
Df Residuals:                    9397   BIC:                         2.152e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        2.556e+04    246.728    103.613      0.000    2.51e+04     2.6e+04
remittances     0.1280      0.010     13.336      0.000       0.109       0.147
==============================================================================
Omnibus:                    10743.945   Durbin-Watson:                   1.564
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          1587596.544
Skew:                           5.822   Prob(JB):                         0.00
Kurtosis:                      65.596   Cond. No.                     2.72e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.72e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
X1_ur = sm.add_constant(df[xvars_full1])
m1_ur = sm.OLS(df["per_expenditure"], X1_ur).fit()
print(m1_ur.summary())
# N=9,399 | F(9,9389)=179.64 | R²=0.1469
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:        per_expenditure   R-squared:                       0.147
Model:                            OLS   Adj. R-squared:                  0.146
Method:                 Least Squares   F-statistic:                     179.6
Date:                Wed, 08 Apr 2026   Prob (F-statistic):          8.76e-316
Time:                        10:41:08   Log-Likelihood:            -1.0692e+05
No. Observations:                9399   AIC:                         2.139e+05
Df Residuals:                    9389   BIC:                         2.139e+05
Df Model:                           9                                         
Covariance Type:            nonrobust                                         
================================================================================
                   coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------
const         1.256e+04   2843.516      4.419      0.000    6990.697    1.81e+04
remittances      0.1158      0.009     12.771      0.000       0.098       0.134
HHsize        -881.3838    201.957     -4.364      0.000   -1277.264    -485.504
children15   -2526.4778    336.887     -7.499      0.000   -3186.850   -1866.106
elderly60    -2881.1219    417.264     -6.905      0.000   -3699.050   -2063.194
female_ratio -2812.5566   1145.414     -2.455      0.014   -5057.816    -567.297
genderhead    3959.6574    570.497      6.941      0.000    2841.359    5077.956
agehead        227.8777    105.016      2.170      0.030      22.024     433.731
agehead2        -1.5284      0.963     -1.587      0.112      -3.416       0.359
num_eduhead   1793.1973     61.441     29.185      0.000    1672.759    1913.636
==============================================================================
Omnibus:                    11419.022   Durbin-Watson:                   1.678
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          2231997.985
Skew:                           6.403   Prob(JB):                         0.00
Kurtosis:                      77.400   Cond. No.                     3.38e+05
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.38e+05. This might indicate that there are
strong multicollinearity or other numerical problems.
R2_r  = m1_r.rsquared   # 0.0186
R2_ur = m1_ur.rsquared  # 0.1469
m_add = 8               # số biến bổ sung
n1    = int(m1_ur.nobs)
k1    = len(xvars_full1) + 1   # 10 tham số

F1 = ((R2_ur - R2_r) / m_add) / ((1 - R2_ur) / (n1 - k1))
p1 = 1 - f_dist.cdf(F1, dfn=m_add, dfd=n1 - k1)

print(f"R² hạn chế       = {R2_r:.4f}")
print(f"R² không hạn chế = {R2_ur:.4f}")
print(f"F statistic      = {F1:.2f}")
print(f"p-value          = {p1:.4f}")
# F ≈ 176.55, p ≈ 0.000 → bác bỏ H₀: mô hình ban đầu bỏ sót biến
Output
R² hạn chế       = 0.0186
R² không hạn chế = 0.1469
F statistic      = 176.55
p-value          = 0.0000
df_wage, _ = pyreadstat.read_dta(
    "rawdata/wage2020.dta",
    encoding="latin1",
)

df_wage["yearsofexperience2"] = df_wage["yearsofexperience"] ** 2
df_wage["experienceXgender"]  = df_wage["yearsofexperience"] * df_wage["gender"]

xvars_r3  = ["urban", "gender", "yearsofedu", "yearsofexperience"]
xvars_ur3 = ["urban", "gender", "yearsofedu", "yearsofexperience",
             "yearsofexperience2", "experienceXgender",
             "RedRiverDelta", "Northmidlandareas", "CentralCoast",
             "Centralhighlands", "MekongRiverDelta"]
X3_r = sm.add_constant(df_wage[xvars_r3])
m3_r = sm.OLS(df_wage["wage"], X3_r).fit()
print(m3_r.summary())
# N=10,118 | F(4,10113)=633.02 | R²=0.2002
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.200
Model:                            OLS   Adj. R-squared:                  0.200
Method:                 Least Squares   F-statistic:                     633.0
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:08   Log-Likelihood:            -1.2341e+05
No. Observations:               10118   AIC:                         2.468e+05
Df Residuals:                   10113   BIC:                         2.469e+05
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              1.096e+04   2148.704      5.101      0.000    6748.303    1.52e+04
urban              2.233e+04   1037.454     21.525      0.000    2.03e+04    2.44e+04
gender            -1.453e+04    966.347    -15.035      0.000   -1.64e+04   -1.26e+04
yearsofedu         5781.1773    161.878     35.713      0.000    5463.865    6098.490
yearsofexperience   422.6402     42.581      9.926      0.000     339.174     506.107
==============================================================================
Omnibus:                     6384.033   Durbin-Watson:                   1.440
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           180008.186
Skew:                           2.566   Prob(JB):                         0.00
Kurtosis:                      23.016   Cond. No.                         122.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
X3_ur = sm.add_constant(df_wage[xvars_ur3])
m3_ur = sm.OLS(df_wage["wage"], X3_ur).fit()
print(m3_ur.summary())
# N=10,118 | F(11,10106)=384.32 | R²=0.2949
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.295
Model:                            OLS   Adj. R-squared:                  0.294
Method:                 Least Squares   F-statistic:                     384.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:08   Log-Likelihood:            -1.2278e+05
No. Observations:               10118   AIC:                         2.456e+05
Df Residuals:                   10106   BIC:                         2.457e+05
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const               1.908e+04   2662.710      7.165      0.000    1.39e+04    2.43e+04
urban               1.896e+04    992.050     19.113      0.000     1.7e+04    2.09e+04
gender              -1.52e+04   1833.266     -8.289      0.000   -1.88e+04   -1.16e+04
yearsofedu          5180.2944    159.162     32.547      0.000    4868.305    5492.284
yearsofexperience   2959.6949    125.930     23.503      0.000    2712.847    3206.543
yearsofexperience2   -52.1863      2.311    -22.578      0.000     -56.717     -47.655
experienceXgender     13.2129     71.699      0.184      0.854    -127.332     153.758
RedRiverDelta      -1.121e+04   1633.459     -6.863      0.000   -1.44e+04   -8008.658
Northmidlandareas   -3.62e+04   1737.218    -20.836      0.000   -3.96e+04   -3.28e+04
CentralCoast       -3.196e+04   1612.507    -19.819      0.000   -3.51e+04   -2.88e+04
Centralhighlands   -4.552e+04   2162.284    -21.052      0.000   -4.98e+04   -4.13e+04
MekongRiverDelta    -2.42e+04   1683.790    -14.371      0.000   -2.75e+04   -2.09e+04
==============================================================================
Omnibus:                     6950.236   Durbin-Watson:                   1.558
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           246308.657
Skew:                           2.831   Prob(JB):                         0.00
Kurtosis:                      26.499   Cond. No.                     7.58e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.58e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
R2_r3  = m3_r.rsquared
R2_ur3 = m3_ur.rsquared
m_add3 = 7
n3     = int(m3_ur.nobs)
k3     = len(xvars_ur3) + 1

F3 = ((R2_ur3 - R2_r3) / m_add3) / ((1 - R2_ur3) / (n3 - k3))
p3 = 1 - f_dist.cdf(F3, dfn=m_add3, dfd=n3 - k3)
print(f"F = {F3:.2f}, p = {p3:.4f}")
# F ≈ 193.91 → bác bỏ H₀
Output
F = 193.91, p = 0.0000
df_wage["wage_million"] = df_wage["wage"] / 1000

X_reset = sm.add_constant(df_wage[xvars_r3])
m_reset = sm.OLS(df_wage["wage_million"], X_reset).fit()
print(m_reset.summary())
# Hệ số giống wage nhưng scale nhỏ hơn 1000 lần
# N=10,118 | F(4,10113)=633.02 | R²=0.2002
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:           wage_million   R-squared:                       0.200
Model:                            OLS   Adj. R-squared:                  0.200
Method:                 Least Squares   F-statistic:                     633.0
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:09   Log-Likelihood:                -53521.
No. Observations:               10118   AIC:                         1.071e+05
Df Residuals:                   10113   BIC:                         1.071e+05
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                10.9602      2.149      5.101      0.000       6.748      15.172
urban                22.3308      1.037     21.525      0.000      20.297      24.364
gender              -14.5293      0.966    -15.035      0.000     -16.424     -12.635
yearsofedu            5.7812      0.162     35.713      0.000       5.464       6.098
yearsofexperience     0.4226      0.043      9.926      0.000       0.339       0.506
==============================================================================
Omnibus:                     6384.033   Durbin-Watson:                   1.440
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           180008.186
Skew:                           2.566   Prob(JB):                         0.00
Kurtosis:                      23.016   Cond. No.                         122.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
df_wage["yhat_million"]  = m_reset.fittedvalues
df_wage["yhat2_million"] = df_wage["yhat_million"] ** 2
df_wage["yhat3_million"] = df_wage["yhat_million"] ** 3
df_wage["yhat4_million"] = df_wage["yhat_million"] ** 4
X_ext23 = sm.add_constant(df_wage[xvars_r3 + ["yhat2_million", "yhat3_million"]])
m_ext23 = sm.OLS(df_wage["wage_million"], X_ext23).fit()
print(m_ext23.summary())
# F(6,10111)=505.48 | R²=0.2307
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:           wage_million   R-squared:                       0.231
Model:                            OLS   Adj. R-squared:                  0.230
Method:                 Least Squares   F-statistic:                     505.5
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:09   Log-Likelihood:                -53325.
No. Observations:               10118   AIC:                         1.067e+05
Df Residuals:                   10111   BIC:                         1.067e+05
Df Model:                           6                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                28.6288      3.208      8.925      0.000      22.341      34.916
urban                30.8746      6.075      5.082      0.000      18.966      42.783
gender              -22.5039      3.836     -5.866      0.000     -30.024     -14.984
yearsofedu            9.9339      1.479      6.716      0.000       7.034      12.833
yearsofexperience     0.5996      0.116      5.175      0.000       0.372       0.827
yhat2_million        -0.0247      0.004     -6.428      0.000      -0.032      -0.017
yhat3_million         0.0002   1.78e-05      9.627      0.000       0.000       0.000
==============================================================================
Omnibus:                     6085.138   Durbin-Watson:                   1.439
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           164583.344
Skew:                           2.405   Prob(JB):                         0.00
Kurtosis:                      22.164   Cond. No.                     1.14e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.14e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
RSS_base = m_reset.ssr
RSS_23   = m_ext23.ssr
q23      = 2
dfd23    = m_ext23.df_resid

F_23 = ((RSS_base - RSS_23) / q23) / (RSS_23 / dfd23)
p_23 = 1 - f_dist.cdf(F_23, dfn=q23, dfd=dfd23)
print(f"F({q23}, {int(dfd23)}) = {F_23:.2f},  Prob > F = {p_23:.4f}")
# F ≈ 200.46, p = 0.000 → bác bỏ H₀
Output
F(2, 10111) = 200.46,  Prob > F = 0.0000
X_ext234 = sm.add_constant(df_wage[xvars_r3 + ["yhat2_million", "yhat3_million", "yhat4_million"]])
m_ext234 = sm.OLS(df_wage["wage_million"], X_ext234).fit()
print(m_ext234.summary())
# F(7,10110)=433.32 | R²=0.2308
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:           wage_million   R-squared:                       0.231
Model:                            OLS   Adj. R-squared:                  0.230
Method:                 Least Squares   F-statistic:                     433.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:09   Log-Likelihood:                -53324.
No. Observations:               10118   AIC:                         1.067e+05
Df Residuals:                   10110   BIC:                         1.067e+05
Df Model:                           7                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                28.7387      3.212      8.948      0.000      22.443      35.034
urban                23.5037     12.279      1.914      0.056      -0.566      47.573
gender              -17.6096      8.057     -2.186      0.029     -33.404      -1.815
yearsofedu            7.9622      3.215      2.477      0.013       1.660      14.264
yearsofexperience     0.4576      0.236      1.939      0.053      -0.005       0.920
yhat2_million        -0.0157      0.014     -1.146      0.252      -0.042       0.011
yhat3_million      7.814e-05      0.000      0.574      0.566      -0.000       0.000
yhat4_million      3.258e-07   4.72e-07      0.691      0.490   -5.99e-07    1.25e-06
==============================================================================
Omnibus:                     6087.244   Durbin-Watson:                   1.439
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           164970.933
Skew:                           2.406   Prob(JB):                         0.00
Kurtosis:                      22.188   Cond. No.                     2.36e+09
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.36e+09. This might indicate that there are
strong multicollinearity or other numerical problems.
RSS_234 = m_ext234.ssr
q234    = 3
dfd234  = m_ext234.df_resid

F_234 = ((RSS_base - RSS_234) / q234) / (RSS_234 / dfd234)
p_234 = 1 - f_dist.cdf(F_234, dfn=q234, dfd=dfd234)
print(f"F({q234}, {int(dfd234)}) = {F_234:.2f},  Prob > F = {p_234:.4f}")
# F ≈ 133.79, p = 0.000
Output
F(3, 10110) = 133.79,  Prob > F = 0.0000
from statsmodels.stats.diagnostic import linear_reset

reset_test = linear_reset(m_reset, power=4, use_f=True)
print(f"Ramsey RESET F(3, {int(m_reset.df_resid - 3)}) = {reset_test.fvalue:.2f}")
print(f"Prob > F = {reset_test.pvalue:.4f}")
# F ≈ 133.79, Prob > F = 0.0000
# → Bác bỏ H₀: mô hình có dạng hàm không phù hợp
Output
Ramsey RESET F(3, 10110) = 133.79
Prob > F = 0.0000
X_lm_r = sm.add_constant(df_wage[xvars_r3])
m_lm_r = sm.OLS(df_wage["wage"], X_lm_r).fit()
print(m_lm_r.summary())
# N=10,118 | R²=0.2002
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.200
Model:                            OLS   Adj. R-squared:                  0.200
Method:                 Least Squares   F-statistic:                     633.0
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:09   Log-Likelihood:            -1.2341e+05
No. Observations:               10118   AIC:                         2.468e+05
Df Residuals:                   10113   BIC:                         2.469e+05
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              1.096e+04   2148.704      5.101      0.000    6748.303    1.52e+04
urban              2.233e+04   1037.454     21.525      0.000    2.03e+04    2.44e+04
gender            -1.453e+04    966.347    -15.035      0.000   -1.64e+04   -1.26e+04
yearsofedu         5781.1773    161.878     35.713      0.000    5463.865    6098.490
yearsofexperience   422.6402     42.581      9.926      0.000     339.174     506.107
==============================================================================
Omnibus:                     6384.033   Durbin-Watson:                   1.440
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           180008.186
Skew:                           2.566   Prob(JB):                         0.00
Kurtosis:                      23.016   Cond. No.                         122.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
r_lm     = m_lm_r.resid
X_lm_aux = sm.add_constant(df_wage[xvars_ur3])
m_lm_aux = sm.OLS(r_lm, X_lm_aux).fit()
print(m_lm_aux.summary())
# R² ≈ 0.1184
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.118
Model:                            OLS   Adj. R-squared:                  0.117
Method:                 Least Squares   F-statistic:                     123.4
Date:                Wed, 08 Apr 2026   Prob (F-statistic):          1.65e-266
Time:                        10:41:09   Log-Likelihood:            -1.2278e+05
No. Observations:               10118   AIC:                         2.456e+05
Df Residuals:                   10106   BIC:                         2.457e+05
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const               8119.1570   2662.710      3.049      0.002    2899.716    1.33e+04
urban              -3369.6439    992.050     -3.397      0.001   -5314.260   -1425.028
gender              -666.0370   1833.266     -0.363      0.716   -4259.602    2927.528
yearsofedu          -600.8829    159.162     -3.775      0.000    -912.873    -288.893
yearsofexperience   2537.0547    125.930     20.147      0.000    2290.207    2783.903
yearsofexperience2   -52.1863      2.311    -22.578      0.000     -56.717     -47.655
experienceXgender     13.2129     71.699      0.184      0.854    -127.332     153.758
RedRiverDelta      -1.121e+04   1633.459     -6.863      0.000   -1.44e+04   -8008.658
Northmidlandareas   -3.62e+04   1737.218    -20.836      0.000   -3.96e+04   -3.28e+04
CentralCoast       -3.196e+04   1612.507    -19.819      0.000   -3.51e+04   -2.88e+04
Centralhighlands   -4.552e+04   2162.284    -21.052      0.000   -4.98e+04   -4.13e+04
MekongRiverDelta    -2.42e+04   1683.790    -14.371      0.000   -2.75e+04   -2.09e+04
==============================================================================
Omnibus:                     6950.236   Durbin-Watson:                   1.558
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           246308.657
Skew:                           2.831   Prob(JB):                         0.00
Kurtosis:                      26.499   Cond. No.                     7.58e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.58e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
n_lm = int(m_lm_aux.nobs)
LM   = n_lm * m_lm_aux.rsquared
p_lm = 1 - chi2.cdf(LM, df=7)

print(f"LM = n × R² = {n_lm} × {m_lm_aux.rsquared:.4f} = {LM:.2f}")
print(f"p-value = {p_lm:.4e}")
# LM ≈ 1198, p ≈ 0 → bác bỏ H₀
Output
LM = n × R² = 10118 × 0.1184 = 1198.06
p-value = 0.0000e+00
df["agehead2"] = df["agehead"] ** 2
df["HHsize2"]  = df["HHsize"]  ** 2

xvar_full = ["ln_expenditure", "agehead", "agehead2", "primary", "secondary",
             "high_school", "higher_education", "HHsize", "HHsize2",
             "dependency_ratio", "domestic_remittances", "overseas_remittances",
             "urban", "RedRiverDelta", "Northmidlandareas", "MekongRiverDelta",
             "Centralhighlands", "CentralCoast"]

df_fs  = df.dropna(subset=["food_share"] + xvar_full).copy()
X_full = sm.add_constant(df_fs[xvar_full])
m_full = sm.OLS(df_fs["food_share"], X_full).fit()
print(m_full.summary())
# N=8,381 | F(18,8362)=1040.95 | R²=0.6914
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             food_share   R-squared:                       0.691
Model:                            OLS   Adj. R-squared:                  0.691
Method:                 Least Squares   F-statistic:                     1041.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:10   Log-Likelihood:                 13344.
No. Observations:                8381   AIC:                        -2.665e+04
Df Residuals:                    8362   BIC:                        -2.652e+04
Df Model:                          18                                         
Covariance Type:            nonrobust                                         
========================================================================================
                           coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------------
const                    0.8971      0.013     69.272      0.000       0.872       0.922
ln_expenditure          -0.0383      0.001    -34.788      0.000      -0.040      -0.036
agehead                 -0.0006      0.000     -2.167      0.030      -0.001   -5.47e-05
agehead2              6.104e-06    2.5e-06      2.442      0.015     1.2e-06     1.1e-05
primary                  0.0007      0.002      0.440      0.660      -0.002       0.004
secondary                0.0002      0.002      0.102      0.919      -0.003       0.003
high_school             -0.0005      0.002     -0.226      0.822      -0.004       0.003
higher_education         0.0015      0.003      0.581      0.561      -0.004       0.007
HHsize                  -0.1135      0.001    -78.683      0.000      -0.116      -0.111
HHsize2                  0.0086      0.000     58.678      0.000       0.008       0.009
dependency_ratio        -0.0017      0.001     -1.887      0.059      -0.003    6.47e-05
domestic_remittances    -0.0014      0.001     -0.990      0.322      -0.004       0.001
overseas_remittances    -0.0015      0.003     -0.512      0.608      -0.007       0.004
urban                    0.0124      0.001      9.450      0.000       0.010       0.015
RedRiverDelta           -0.0031      0.002     -1.557      0.120      -0.007       0.001
Northmidlandareas       -0.0043      0.002     -2.084      0.037      -0.008      -0.000
MekongRiverDelta        -0.0084      0.002     -4.222      0.000      -0.012      -0.005
Centralhighlands        -0.0112      0.003     -4.329      0.000      -0.016      -0.006
CentralCoast            -0.0010      0.002     -0.524      0.600      -0.005       0.003
==============================================================================
Omnibus:                     3937.239   Durbin-Watson:                   1.877
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            81037.717
Skew:                           1.765   Prob(JB):                         0.00
Kurtosis:                      17.819   Cond. No.                     7.09e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.09e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Loại: primary, secondary, high_school, higher_education,
#        domestic_remittances, overseas_remittances, RedRiverDelta, CentralCoast
xvar_red = ["ln_expenditure", "agehead", "agehead2", "HHsize", "HHsize2",
            "dependency_ratio", "urban", "Northmidlandareas",
            "MekongRiverDelta", "Centralhighlands"]

X_red = sm.add_constant(df_fs[xvar_red])
m_red = sm.OLS(df_fs["food_share"], X_red).fit()
print(m_red.summary())
# N=8,381 | F(10,8370)=1873.75 | R²=0.6912
# → R² gần như không đổi, mô hình đơn giản hơn
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             food_share   R-squared:                       0.691
Model:                            OLS   Adj. R-squared:                  0.691
Method:                 Least Squares   F-statistic:                     1874.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:10   Log-Likelihood:                 13341.
No. Observations:                8381   AIC:                        -2.666e+04
Df Residuals:                    8370   BIC:                        -2.658e+04
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                 0.8961      0.012     73.236      0.000       0.872       0.920
ln_expenditure       -0.0384      0.001    -38.106      0.000      -0.040      -0.036
agehead              -0.0006      0.000     -2.334      0.020      -0.001   -9.83e-05
agehead2           6.416e-06   2.48e-06      2.589      0.010    1.56e-06    1.13e-05
HHsize               -0.1135      0.001    -79.405      0.000      -0.116      -0.111
HHsize2               0.0086      0.000     58.877      0.000       0.008       0.009
dependency_ratio     -0.0018      0.001     -2.031      0.042      -0.003   -6.14e-05
urban                 0.0127      0.001      9.939      0.000       0.010       0.015
Northmidlandareas    -0.0026      0.001     -1.721      0.085      -0.005       0.000
MekongRiverDelta     -0.0067      0.001     -4.735      0.000      -0.009      -0.004
Centralhighlands     -0.0096      0.002     -4.450      0.000      -0.014      -0.005
==============================================================================
Omnibus:                     3935.458   Durbin-Watson:                   1.875
Prob(Omnibus):                  0.000   Jarque-Bera (JB):            80915.036
Skew:                           1.765   Prob(JB):                         0.00
Kurtosis:                      17.807   Cond. No.                     6.68e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 6.68e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
m_age = sm.OLS(df_wage["yearsofexperience"],
               sm.add_constant(df_wage["age"])).fit()
print(m_age.summary())
# Beta ≈ 0.964 → yearsofexperience và age gần như collinear
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      yearsofexperience   R-squared:                       0.930
Model:                            OLS   Adj. R-squared:                  0.930
Method:                 Least Squares   F-statistic:                 1.343e+05
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:10   Log-Likelihood:                -26617.
No. Observations:               10118   AIC:                         5.324e+04
Df Residuals:                   10116   BIC:                         5.325e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const        -17.4447      0.114   -153.393      0.000     -17.668     -17.222
age            1.0616      0.003    366.530      0.000       1.056       1.067
==============================================================================
Omnibus:                      946.278   Durbin-Watson:                   1.161
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             1230.766
Skew:                           0.843   Prob(JB):                    5.53e-268
Kurtosis:                       3.274   Cond. No.                         134.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Lọc obs có remittances > 0 để lấy ln_remittances
df["ln_per_expenditure"] = np.log(df["per_expenditure"])
df["ln_remittances"]     = np.where(df["remittances"] > 0, np.log(df["remittances"]), np.nan)

df_logex = df.dropna(subset=["ln_remittances"]).copy()
X_logex  = sm.add_constant(df_logex[["ln_remittances", "HHsize", "children15",
                                      "elderly60", "female_ratio", "genderhead",
                                      "agehead", "agehead2", "num_eduhead"]])
m_logex  = sm.OLS(df_logex["ln_per_expenditure"], X_logex).fit()
print(m_logex.summary())
# N=7,953 | F(9,7943)=366.24 | R²=0.2933
Output
/usr/local/lib/python3.12/dist-packages/pandas/core/arraylike.py:399: RuntimeWarning: divide by zero encountered in log
  result = getattr(ufunc, method)(*inputs, **kwargs)
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.293
Model:                            OLS   Adj. R-squared:                  0.292
Method:                 Least Squares   F-statistic:                     366.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:10   Log-Likelihood:                -6062.4
No. Observations:                7953   AIC:                         1.214e+04
Df Residuals:                    7943   BIC:                         1.221e+04
Df Model:                           9                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const              8.8838      0.079    113.149      0.000       8.730       9.038
ln_remittances     0.0740      0.004     20.571      0.000       0.067       0.081
HHsize            -0.0153      0.005     -2.805      0.005      -0.026      -0.005
children15        -0.1336      0.009    -14.657      0.000      -0.151      -0.116
elderly60         -0.1011      0.011     -9.202      0.000      -0.123      -0.080
female_ratio      -0.1029      0.031     -3.365      0.001      -0.163      -0.043
genderhead         0.1139      0.015      7.481      0.000       0.084       0.144
agehead            0.0116      0.003      4.115      0.000       0.006       0.017
agehead2          -0.0001   2.56e-05     -3.918      0.000      -0.000   -5.01e-05
num_eduhead        0.0634      0.002     38.059      0.000       0.060       0.067
==============================================================================
Omnibus:                      368.496   Durbin-Watson:                   1.423
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              667.341
Skew:                           0.365   Prob(JB):                    1.23e-145
Kurtosis:                       4.218   Cond. No.                     4.50e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.5e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Stata: sum ln_per_expenditure trên TẤT CẢ 9,399 obs (kể cả remittances=0)
mean_ln = df["ln_per_expenditure"].mean()   # = 9.98008
gmean   = np.exp(mean_ln)
print(f"Mean of ln_per_expenditure = {mean_ln:.5f}")
print(f"Geometric mean             = {gmean:,.2f}")  # ≈ 21,592
Output
Mean of ln_per_expenditure = 9.98008
Geometric mean             = 21,592.03
df["per_expenditure_g"]   = df["per_expenditure"] / gmean
df["lnper_expenditure_g"] = np.log(df["per_expenditure_g"])
X_lin_pe = sm.add_constant(df[xvars_full1])
m_lin_pe = sm.OLS(df["per_expenditure_g"], X_lin_pe).fit()
print(m_lin_pe.summary())
RSS1_pe = m_lin_pe.ssr
print(f"\nRSS₁ (linear) = {RSS1_pe:.4f}")   # ≈ 8962.72
# N=9,399 (toàn bộ mẫu kể cả remittances=0)
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      per_expenditure_g   R-squared:                       0.147
Model:                            OLS   Adj. R-squared:                  0.146
Method:                 Least Squares   F-statistic:                     179.6
Date:                Wed, 08 Apr 2026   Prob (F-statistic):          8.76e-316
Time:                        10:41:10   Log-Likelihood:                -13113.
No. Observations:                9399   AIC:                         2.625e+04
Df Residuals:                    9389   BIC:                         2.632e+04
Df Model:                           9                                         
Covariance Type:            nonrobust                                         
================================================================================
                   coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------
const            0.5819      0.132      4.419      0.000       0.324       0.840
remittances   5.362e-06    4.2e-07     12.771      0.000    4.54e-06    6.19e-06
HHsize          -0.0408      0.009     -4.364      0.000      -0.059      -0.022
children15      -0.1170      0.016     -7.499      0.000      -0.148      -0.086
elderly60       -0.1334      0.019     -6.905      0.000      -0.171      -0.096
female_ratio    -0.1303      0.053     -2.455      0.014      -0.234      -0.026
genderhead       0.1834      0.026      6.941      0.000       0.132       0.235
agehead          0.0106      0.005      2.170      0.030       0.001       0.020
agehead2     -7.079e-05   4.46e-05     -1.587      0.112      -0.000    1.66e-05
num_eduhead      0.0830      0.003     29.185      0.000       0.077       0.089
==============================================================================
Omnibus:                    11419.022   Durbin-Watson:                   1.678
Prob(Omnibus):                  0.000   Jarque-Bera (JB):          2231997.985
Skew:                           6.403   Prob(JB):                         0.00
Kurtosis:                      77.400   Cond. No.                     3.38e+05
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.38e+05. This might indicate that there are
strong multicollinearity or other numerical problems.

RSS₁ (linear) = 8962.7166
xvars_log = ["ln_remittances", "HHsize", "children15", "elderly60",
             "female_ratio", "genderhead", "agehead", "agehead2", "num_eduhead"]

# Chỉ obs có ln_remittances (7,953 obs)
df_log2  = df.dropna(subset=["ln_remittances"]).copy()
X_log_pe = sm.add_constant(df_log2[xvars_log])
m_log_pe = sm.OLS(df_log2["lnper_expenditure_g"], X_log_pe).fit()
print(m_log_pe.summary())
RSS2_pe = m_log_pe.ssr
print(f"\nRSS₂ (log) = {RSS2_pe:.4f}")   # ≈ 2138.76
# N=7,953
Output
                             OLS Regression Results                            
===============================================================================
Dep. Variable:     lnper_expenditure_g   R-squared:                       0.293
Model:                             OLS   Adj. R-squared:                  0.292
Method:                  Least Squares   F-statistic:                     366.2
Date:                 Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                         10:41:11   Log-Likelihood:                -6062.4
No. Observations:                 7953   AIC:                         1.214e+04
Df Residuals:                     7943   BIC:                         1.221e+04
Df Model:                            9                                         
Covariance Type:             nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const             -1.0963      0.079    -13.963      0.000      -1.250      -0.942
ln_remittances     0.0740      0.004     20.571      0.000       0.067       0.081
HHsize            -0.0153      0.005     -2.805      0.005      -0.026      -0.005
children15        -0.1336      0.009    -14.657      0.000      -0.151      -0.116
elderly60         -0.1011      0.011     -9.202      0.000      -0.123      -0.080
female_ratio      -0.1029      0.031     -3.365      0.001      -0.163      -0.043
genderhead         0.1139      0.015      7.481      0.000       0.084       0.144
agehead            0.0116      0.003      4.115      0.000       0.006       0.017
agehead2          -0.0001   2.56e-05     -3.918      0.000      -0.000   -5.01e-05
num_eduhead        0.0634      0.002     38.059      0.000       0.060       0.067
==============================================================================
Omnibus:                      368.496   Durbin-Watson:                   1.423
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              667.341
Skew:                           0.365   Prob(JB):                    1.23e-145
Kurtosis:                       4.218   Cond. No.                     4.50e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.5e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

RSS₂ (log) = 2138.7598
# n dùng trong công thức = N của mô hình log (7,953)
N_pe  = m_log_pe.nobs
T_pe  = (N_pe / 2) * np.log(RSS1_pe / RSS2_pe)
p_pe  = 1 - chi2.cdf(T_pe, df=1)

print(f"N     = {int(N_pe)}")
print(f"RSS₁  = {RSS1_pe:.4f}")
print(f"RSS₂  = {RSS2_pe:.4f}")
print(f"T     = (N/2) × ln(RSS₁/RSS₂) = {T_pe:.2f}")
print(f"p-value = {p_pe:.4e}")
# T ≈ 5697.72, p ≈ 0 → bác bỏ H₀ → dạng log phù hợp hơn linear
Output
N     = 7953
RSS₁  = 8962.7166
RSS₂  = 2138.7598
T     = (N/2) × ln(RSS₁/RSS₂) = 5697.72
p-value = 0.0000e+00
df_wage["ln_wage"] = np.log(df_wage["wage"])

X_log_w = sm.add_constant(df_wage[xvars_ur3])
m_log_w = sm.OLS(df_wage["ln_wage"], X_log_w).fit()
print(m_log_w.summary())
# N=10,118 | R²=0.3197
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                ln_wage   R-squared:                       0.320
Model:                            OLS   Adj. R-squared:                  0.319
Method:                 Least Squares   F-statistic:                     431.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:11   Log-Likelihood:                -10798.
No. Observations:               10118   AIC:                         2.162e+04
Df Residuals:                   10106   BIC:                         2.171e+04
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const                  9.9988      0.042    240.480      0.000       9.917      10.080
urban                  0.2551      0.015     16.470      0.000       0.225       0.285
gender                -0.1312      0.029     -4.585      0.000      -0.187      -0.075
yearsofedu             0.0806      0.002     32.441      0.000       0.076       0.085
yearsofexperience      0.0558      0.002     28.356      0.000       0.052       0.060
yearsofexperience2    -0.0010   3.61e-05    -28.345      0.000      -0.001      -0.001
experienceXgender     -0.0036      0.001     -3.241      0.001      -0.006      -0.001
RedRiverDelta         -0.1385      0.026     -5.431      0.000      -0.189      -0.089
Northmidlandareas     -0.6168      0.027    -22.739      0.000      -0.670      -0.564
CentralCoast          -0.4743      0.025    -18.838      0.000      -0.524      -0.425
Centralhighlands      -0.8505      0.034    -25.190      0.000      -0.917      -0.784
MekongRiverDelta      -0.3180      0.026    -12.096      0.000      -0.370      -0.267
==============================================================================
Omnibus:                     2673.102   Durbin-Watson:                   1.487
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             8552.170
Skew:                          -1.341   Prob(JB):                         0.00
Kurtosis:                       6.619   Cond. No.                     7.58e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.58e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
mean_lnw = df_wage["ln_wage"].mean()   # = 10.94526
gmean_w  = np.exp(mean_lnw)
print(f"Mean of ln_wage   = {mean_lnw:.5f}")
print(f"Geometric mean    = {gmean_w:,.2f}")  # ≈ 56,685
Output
Mean of ln_wage   = 10.94526
Geometric mean    = 56,684.96
df_wage["wage_g"]    = df_wage["wage"] / gmean_w
df_wage["lnwage_g"]  = np.log(df_wage["wage_g"])
X_lin_w = sm.add_constant(df_wage[xvars_ur3])
m_lin_w = sm.OLS(df_wage["wage_g"], X_lin_w).fit()
print(m_lin_w.summary())
RSS1_w = m_lin_w.ssr
print(f"\nRSS₁ (linear) = {RSS1_w:.4f}")  # ≈ 6390.48
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                 wage_g   R-squared:                       0.295
Model:                            OLS   Adj. R-squared:                  0.294
Method:                 Least Squares   F-statistic:                     384.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:11   Log-Likelihood:                -12032.
No. Observations:               10118   AIC:                         2.409e+04
Df Residuals:                   10106   BIC:                         2.418e+04
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const                  0.3366      0.047      7.165      0.000       0.245       0.429
urban                  0.3345      0.018     19.113      0.000       0.300       0.369
gender                -0.2681      0.032     -8.289      0.000      -0.331      -0.205
yearsofedu             0.0914      0.003     32.547      0.000       0.086       0.097
yearsofexperience      0.0522      0.002     23.503      0.000       0.048       0.057
yearsofexperience2    -0.0009   4.08e-05    -22.578      0.000      -0.001      -0.001
experienceXgender      0.0002      0.001      0.184      0.854      -0.002       0.003
RedRiverDelta         -0.1978      0.029     -6.863      0.000      -0.254      -0.141
Northmidlandareas     -0.6386      0.031    -20.836      0.000      -0.699      -0.578
CentralCoast          -0.5638      0.028    -19.819      0.000      -0.620      -0.508
Centralhighlands      -0.8030      0.038    -21.052      0.000      -0.878      -0.728
MekongRiverDelta      -0.4269      0.030    -14.371      0.000      -0.485      -0.369
==============================================================================
Omnibus:                     6950.236   Durbin-Watson:                   1.558
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           246308.657
Skew:                           2.831   Prob(JB):                         0.00
Kurtosis:                      26.499   Cond. No.                     7.58e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.58e+03. This might indicate that there are
strong multicollinearity or other numerical problems.

RSS₁ (linear) = 6390.4827
X_log_w2 = sm.add_constant(df_wage[xvars_ur3])
m_log_w2 = sm.OLS(df_wage["lnwage_g"], X_log_w2).fit()
print(m_log_w2.summary())
RSS2_w = m_log_w2.ssr
print(f"\nRSS₂ (log) = {RSS2_w:.4f}")  # ≈ 5006.82
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:               lnwage_g   R-squared:                       0.320
Model:                            OLS   Adj. R-squared:                  0.319
Method:                 Least Squares   F-statistic:                     431.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:11   Log-Likelihood:                -10798.
No. Observations:               10118   AIC:                         2.162e+04
Df Residuals:                   10106   BIC:                         2.171e+04
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const                 -0.9464      0.042    -22.762      0.000      -1.028      -0.865
urban                  0.2551      0.015     16.470      0.000       0.225       0.285
gender                -0.1312      0.029     -4.585      0.000      -0.187      -0.075
yearsofedu             0.0806      0.002     32.441      0.000       0.076       0.085
yearsofexperience      0.0558      0.002     28.356      0.000       0.052       0.060
yearsofexperience2    -0.0010   3.61e-05    -28.345      0.000      -0.001      -0.001
experienceXgender     -0.0036      0.001     -3.241      0.001      -0.006      -0.001
RedRiverDelta         -0.1385      0.026     -5.431      0.000      -0.189      -0.089
Northmidlandareas     -0.6168      0.027    -22.739      0.000      -0.670      -0.564
CentralCoast          -0.4743      0.025    -18.838      0.000      -0.524      -0.425
Centralhighlands      -0.8505      0.034    -25.190      0.000      -0.917      -0.784
MekongRiverDelta      -0.3180      0.026    -12.096      0.000      -0.370      -0.267
==============================================================================
Omnibus:                     2673.102   Durbin-Watson:                   1.487
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             8552.170
Skew:                          -1.341   Prob(JB):                         0.00
Kurtosis:                       6.619   Cond. No.                     7.58e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.58e+03. This might indicate that there are
strong multicollinearity or other numerical problems.

RSS₂ (log) = 5006.8189
N_w  = m_log_w2.nobs
T_w  = (N_w / 2) * np.log(RSS1_w / RSS2_w)
p_w  = 1 - chi2.cdf(T_w, df=1)
print(f"T = {T_w:.4f},  p-value = {p_w:.4e}")
# T ≈ 1234.44, p ≈ 2e-270 → bác bỏ H₀ → dạng log phù hợp hơn
Output
T = 1234.4417,  p-value = 0.0000e+00
df_acc, _ = pyreadstat.read_dta(
    "rawdata/rotations_accidents2022.dta",
    encoding="latin1",
)
df_acc["idprovince"] = range(1, len(df_acc) + 1)

X_acc = sm.add_constant(df_acc["rotations"])
m_acc = sm.OLS(df_acc["traffic_accidents"], X_acc).fit()
print(m_acc.summary())
df_acc["resid"] = m_acc.resid
# N=63 | F(1,61)=126.88 | R²=0.6753
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      traffic_accidents   R-squared:                       0.675
Model:                            OLS   Adj. R-squared:                  0.670
Method:                 Least Squares   F-statistic:                     126.9
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.55e-16
Time:                        10:41:11   Log-Likelihood:                -407.07
No. Observations:                  63   AIC:                             818.1
Df Residuals:                      61   BIC:                             822.4
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         29.4514     24.000      1.227      0.224     -18.539      77.441
rotations      0.0863      0.008     11.264      0.000       0.071       0.102
==============================================================================
Omnibus:                       15.054   Durbin-Watson:                   1.932
Prob(Omnibus):                  0.001   Jarque-Bera (JB):               33.118
Skew:                           0.652   Prob(JB):                     6.44e-08
Kurtosis:                       6.304   Cond. No.                     3.79e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.79e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
df_acc["resid_sq"] = df_acc["resid"] ** 2

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(df_acc["idprovince"], df_acc["resid_sq"],
        color=palette[2], linestyle="--", linewidth=1.5)
ax.axvline(x=50, color=palette[1], linestyle=":", linewidth=1.5, label="Tỉnh 50 (outlier)")
ax.set_xlabel("Tỉnh/thành")
ax.set_ylabel("Phần dư bình phương")
ax.set_title("Hình 4.1 – Bình phương phần dư theo tỉnh/thành")
ax.legend()
plt.tight_layout()
OutputOutput of chapter 4, cell 84
df_acc2 = df_acc[df_acc["idprovince"] != 50].copy()
m_acc2  = sm.OLS(df_acc2["traffic_accidents"],
                 sm.add_constant(df_acc2["rotations"])).fit()
print(m_acc2.summary())
# N=62 | F(1,60)=34.15 | R²=0.3627
# → Hệ số rotations giảm từ 0.086 xuống 0.046 khi bỏ outlier
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      traffic_accidents   R-squared:                       0.363
Model:                            OLS   Adj. R-squared:                  0.352
Method:                 Least Squares   F-statistic:                     34.15
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           2.24e-07
Time:                        10:41:13   Log-Likelihood:                -380.89
No. Observations:                  62   AIC:                             765.8
Df Residuals:                      60   BIC:                             770.0
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         82.1131     18.848      4.357      0.000      44.412     119.814
rotations      0.0457      0.008      5.844      0.000       0.030       0.061
==============================================================================
Omnibus:                       21.174   Durbin-Watson:                   2.207
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               30.287
Skew:                           1.297   Prob(JB):                     2.65e-07
Kurtosis:                       5.234   Cond. No.                     3.13e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.13e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
from statsmodels.robust.robust_linear_model import RLM
from statsmodels.robust.norms import HuberT, TukeyBiweight

# bước 1 Huber
m_huber = RLM(df_acc["traffic_accidents"], X_acc, M=HuberT()).fit()

# bước 2 Biweight
m_rlm = RLM(df_acc["traffic_accidents"], X_acc,
            M=TukeyBiweight(),
            init=m_huber.params).fit()

print(m_rlm.summary())
Output
                    Robust linear Model Regression Results                    
==============================================================================
Dep. Variable:      traffic_accidents   No. Observations:                   63
Model:                            RLM   Df Residuals:                       61
Method:                          IRLS   Df Model:                            1
Norm:                   TukeyBiweight                                         
Scale Est.:                       mad                                         
Cov Type:                          H1                                         
Date:                Wed, 08 Apr 2026                                         
Time:                        10:41:13                                         
No. Iterations:                    18                                         
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         90.6086      9.989      9.071      0.000      71.030     110.187
rotations      0.0147      0.003      4.613      0.000       0.008       0.021
==============================================================================

If the model instance has been used for another fit with different fit parameters, then the fit options might not be the correct ones anymore .
/usr/local/lib/python3.12/dist-packages/statsmodels/base/model.py:130: ValueWarning: unknown kwargs ['init']
  warnings.warn(msg, ValueWarning)
influence = m_acc.get_influence()          # ← m_acc, KHÔNG phải m_acc2
lev       = influence.hat_matrix_diag      # hii

resid_raw     = m_acc.resid
norm_resid_sq = resid_raw**2 / np.sum(resid_raw**2)   # eᵢ²/Σeᵢ²

mean_lev           = lev.mean()
mean_norm_resid_sq = norm_resid_sq.mean()

fig, ax = plt.subplots(figsize=(10, 7))

ax.scatter(norm_resid_sq, lev, color=palette[2], alpha=0.85, s=40, zorder=3)

# Label tất cả các điểm nổi bật (cao hơn ngưỡng trung bình)
for i in range(len(df_acc)):
    if lev[i] > mean_lev or norm_resid_sq[i] > mean_norm_resid_sq:
        ax.annotate(df_acc["province_en"].iloc[i],
                    (norm_resid_sq[i], lev[i]),
                    textcoords="offset points", xytext=(5, 3), fontsize=8)

# Hai đường dashed tại giá trị trung bình — đúng như Stata lvr2plot
ax.axhline(mean_lev,           color="black", linestyle="--", linewidth=1)
ax.axvline(mean_norm_resid_sq, color="black", linestyle="--", linewidth=1)

ax.set_xlabel("Normalized residual squared")
ax.set_ylabel("Leverage")
ax.set_xlim(left=0)
ax.set_ylim(bottom=0)

plt.tight_layout()
OutputOutput of chapter 4, cell 90
df_b, _ = pyreadstat.read_dta(
    "rawdata/migration_remittances_16_full.dta",
    encoding="latin1",
)
df_b["agehead2"] = df_b["agehead"] ** 2

# Battese (1997): thay remittances=0 bằng 1, thêm biến giả not_remittances
df_b["remittances_1"]    = df_b["remittances"].replace(0, 1)
df_b["ln_remittances_1"] = np.log(df_b["remittances_1"])
df_b["not_remittances"]  = (df_b["remittances"] == 0).astype(int)
df_b["ln_per_expenditure"] = np.log(df_b["per_expenditure"])
xvars_b = ["ln_remittances_1", "not_remittances", "HHsize", "children15",
           "elderly60", "female_ratio", "genderhead", "agehead", "agehead2", "num_eduhead"]

m_battese = sm.OLS(df_b["ln_per_expenditure"],
                   sm.add_constant(df_b[xvars_b])).fit()
print(m_battese.summary())
# N=9,399 | F(10,9388)=391.62 | R²=0.2944
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.294
Model:                            OLS   Adj. R-squared:                  0.294
Method:                 Least Squares   F-statistic:                     391.6
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:14   Log-Likelihood:                -7289.4
No. Observations:                9399   AIC:                         1.460e+04
Df Residuals:                    9388   BIC:                         1.468e+04
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
====================================================================================
                       coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------
const                8.8372      0.074    119.761      0.000       8.693       8.982
ln_remittances_1     0.0717      0.004     19.821      0.000       0.065       0.079
not_remittances      0.4987      0.032     15.750      0.000       0.437       0.561
HHsize              -0.0181      0.005     -3.553      0.000      -0.028      -0.008
children15          -0.1339      0.008    -15.834      0.000      -0.151      -0.117
elderly60           -0.1000      0.010     -9.589      0.000      -0.120      -0.080
female_ratio        -0.1004      0.029     -3.516      0.000      -0.156      -0.044
genderhead           0.1200      0.014      8.436      0.000       0.092       0.148
agehead              0.0132      0.003      5.029      0.000       0.008       0.018
agehead2            -0.0001    2.4e-05     -4.503      0.000      -0.000   -6.11e-05
num_eduhead          0.0648      0.002     42.028      0.000       0.062       0.068
==============================================================================
Omnibus:                      433.892   Durbin-Watson:                   1.399
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              779.548
Skew:                           0.366   Prob(JB):                    5.29e-170
Kurtosis:                       4.206   Cond. No.                     4.48e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.48e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
for var in ["remittances", "per_expenditure"]:
    q1, q3 = df_b[var].quantile([0.25, 0.75])
    iqr = q3 - q1
    df_b[f"outlier_{var}"] = (
        (df_b[var] < q1 - 1.5 * iqr) | (df_b[var] > q3 + 1.5 * iqr)
    ).astype(int)
    print(f"outlier_{var}: {df_b[f'outlier_{var}'].sum()} obs")
Output
outlier_remittances: 1331 obs
outlier_per_expenditure: 472 obs
xvars_b2 = xvars_b + ["outlier_per_expenditure", "outlier_remittances"]
m_outlier = sm.OLS(df_b["ln_per_expenditure"],
                   sm.add_constant(df_b[xvars_b2])).fit()
print(m_outlier.summary())
# N=9,399 | F(12,9386)=663.54 | R²=0.4590
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.459
Model:                            OLS   Adj. R-squared:                  0.458
Method:                 Least Squares   F-statistic:                     663.5
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:14   Log-Likelihood:                -6041.0
No. Observations:                9399   AIC:                         1.211e+04
Df Residuals:                    9386   BIC:                         1.220e+04
Df Model:                          12                                         
Covariance Type:            nonrobust                                         
===========================================================================================
                              coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------------
const                       8.8532      0.067    132.015      0.000       8.722       8.985
ln_remittances_1            0.0612      0.004     14.652      0.000       0.053       0.069
not_remittances             0.4052      0.033     12.192      0.000       0.340       0.470
HHsize                     -0.0108      0.004     -2.419      0.016      -0.020      -0.002
children15                 -0.1200      0.007    -16.186      0.000      -0.135      -0.105
elderly60                  -0.0778      0.009     -8.512      0.000      -0.096      -0.060
female_ratio               -0.0797      0.025     -3.187      0.001      -0.129      -0.031
genderhead                  0.0833      0.012      6.677      0.000       0.059       0.108
agehead                     0.0147      0.002      6.403      0.000       0.010       0.019
agehead2                   -0.0001    2.1e-05     -5.822      0.000      -0.000   -8.13e-05
num_eduhead                 0.0542      0.001     39.613      0.000       0.052       0.057
outlier_per_expenditure     1.1915      0.022     53.435      0.000       1.148       1.235
outlier_remittances        -0.0244      0.019     -1.312      0.190      -0.061       0.012
==============================================================================
Omnibus:                       29.165   Durbin-Watson:                   1.421
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               29.351
Skew:                          -0.134   Prob(JB):                     4.23e-07
Kurtosis:                       3.058   Cond. No.                     4.73e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.73e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Dùng lại m_acc (toàn bộ 63 tỉnh)
r_jb4 = m_acc.resid
S4 = skew(r_jb4)
K4 = kurtosis(r_jb4, fisher=False)
n4 = len(r_jb4)
print(f"Obs       = {n4}")
print(f"Mean      = {r_jb4.mean():.2e}")
print(f"Std dev   = {r_jb4.std():.2f}")
print(f"Skewness  = {S4:.4f}")
print(f"Kurtosis  = {K4:.4f}")
Output
Obs       = 63
Mean      = -1.57e-13
Std dev   = 156.11
Skewness  = 0.6520
Kurtosis  = 6.3039
JB4_manual = n4 * ((S4**2)/6 + ((K4-3)**2)/24)
chi2_crit  = chi2.ppf(0.95, df=2)
print(f"JB (thủ công) = {JB4_manual:.2f}")
print(f"chi2 critical (5%) = {chi2_crit:.4f}")
print("→ Bác bỏ H₀" if JB4_manual > chi2_crit else "→ Không bác bỏ H₀")
# JB ≈ 33.12 > 5.99
Output
JB (thủ công) = 33.12
chi2 critical (5%) = 5.9915
→ Bác bỏ H₀
JB4, p_jb4 = jarque_bera(r_jb4)
print(f"Jarque-Bera: {JB4:.2f}  Chi(2)  p = {p_jb4:.2e}")
# JB ≈ 33.12, p = 6.4e-08 → bác bỏ H₀
Output
Jarque-Bera: 33.12  Chi(2)  p = 6.44e-08
m_jb4b = sm.OLS(df_acc2["traffic_accidents"],
                sm.add_constant(df_acc2["rotations"])).fit()
print(m_jb4b.summary())
r_jb4b = m_jb4b.resid
JB4b, p_jb4b = jarque_bera(r_jb4b)
print(f"\nJarque-Bera: {JB4b:.2f},  p = {p_jb4b:.2e}")
# JB ≈ 30.29, p = 2.7e-07 → vẫn bác bỏ H₀
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:      traffic_accidents   R-squared:                       0.363
Model:                            OLS   Adj. R-squared:                  0.352
Method:                 Least Squares   F-statistic:                     34.15
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           2.24e-07
Time:                        10:41:14   Log-Likelihood:                -380.89
No. Observations:                  62   AIC:                             765.8
Df Residuals:                      60   BIC:                             770.0
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         82.1131     18.848      4.357      0.000      44.412     119.814
rotations      0.0457      0.008      5.844      0.000       0.030       0.061
==============================================================================
Omnibus:                       21.174   Durbin-Watson:                   2.207
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               30.287
Skew:                           1.297   Prob(JB):                     2.65e-07
Kurtosis:                       5.234   Cond. No.                     3.13e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 3.13e+03. This might indicate that there are
strong multicollinearity or other numerical problems.

Jarque-Bera: 30.29,  p = 2.65e-07
# Dùng lại m_outlier đã hồi quy ở phần 4.5
print(m_outlier.summary())
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.459
Model:                            OLS   Adj. R-squared:                  0.458
Method:                 Least Squares   F-statistic:                     663.5
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:14   Log-Likelihood:                -6041.0
No. Observations:                9399   AIC:                         1.211e+04
Df Residuals:                    9386   BIC:                         1.220e+04
Df Model:                          12                                         
Covariance Type:            nonrobust                                         
===========================================================================================
                              coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------------
const                       8.8532      0.067    132.015      0.000       8.722       8.985
ln_remittances_1            0.0612      0.004     14.652      0.000       0.053       0.069
not_remittances             0.4052      0.033     12.192      0.000       0.340       0.470
HHsize                     -0.0108      0.004     -2.419      0.016      -0.020      -0.002
children15                 -0.1200      0.007    -16.186      0.000      -0.135      -0.105
elderly60                  -0.0778      0.009     -8.512      0.000      -0.096      -0.060
female_ratio               -0.0797      0.025     -3.187      0.001      -0.129      -0.031
genderhead                  0.0833      0.012      6.677      0.000       0.059       0.108
agehead                     0.0147      0.002      6.403      0.000       0.010       0.019
agehead2                   -0.0001    2.1e-05     -5.822      0.000      -0.000   -8.13e-05
num_eduhead                 0.0542      0.001     39.613      0.000       0.052       0.057
outlier_per_expenditure     1.1915      0.022     53.435      0.000       1.148       1.235
outlier_remittances        -0.0244      0.019     -1.312      0.190      -0.061       0.012
==============================================================================
Omnibus:                       29.165   Durbin-Watson:                   1.421
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               29.351
Skew:                          -0.134   Prob(JB):                     4.23e-07
Kurtosis:                       3.058   Cond. No.                     4.73e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.73e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
r_jb1 = m_outlier.resid
S1 = skew(r_jb1)
K1 = kurtosis(r_jb1, fisher=False)
n1_jb = len(r_jb1)
JB1 = n1_jb * ((S1**2)/6 + ((K1-3)**2)/24)

print(f"Obs       = {n1_jb}")
print(f"Mean      = {r_jb1.mean():.2e}")
print(f"Std dev   = {r_jb1.std():.4f}")
print(f"Skewness  = {S1:.4f}")
print(f"Kurtosis  = {K1:.4f}")
print(f"JB        = {JB1:.2f}")
# JB ≈ 29.35 > 5.99 → bác bỏ H₀
Output
Obs       = 9399
Mean      = 1.68e-13
Std dev   = 0.4602
Skewness  = -0.1338
Kurtosis  = 3.0580
JB        = 29.35
JB1_auto, p_jb1 = jarque_bera(r_jb1)
print(f"Jarque-Bera: {JB1_auto:.2f},  p = {p_jb1:.2e}")

fig, ax = plt.subplots(figsize=(9, 5))
ax.hist(r_jb1, bins=40, color=palette[6], alpha=0.7, density=True)
x_fit = np.linspace(r_jb1.min(), r_jb1.max(), 300)
ax.plot(x_fit, norm.pdf(x_fit, r_jb1.mean(), r_jb1.std()),
        color=palette[1], lw=2, label="Chuẩn lý thuyết")
ax.set_xlabel("Phần dư")
ax.set_ylabel("Mật độ")
ax.set_title("Hình 4.3 – Phân phối phần dư mô hình Bảng 4.16")
ax.legend()
plt.tight_layout()
Output
Jarque-Bera: 29.35,  p = 4.23e-07
Output of chapter 4, cell 116
df_gdp, _ = pyreadstat.read_dta(
    "rawdata/GCF_FCE.dta",
    encoding="latin1",
)
df_gdp["Y"] = df_gdp["FCE"] + df_gdp["GCF"]
print(df_gdp[["FCE","GCF","Y"]].describe())
Output
              FCE         GCF           Y
count   30.000000   30.000000   30.000000
mean   125.842101   57.228286  183.070386
std     63.641917   36.675607  100.256334
min     46.499771   11.298114   57.797885
25%     67.287111   23.704912   90.992023
50%    113.414860   54.798756  168.213615
75%    175.057461   82.505323  257.562784
max    246.938583  127.442871  374.381454
m_ils1 = sm.OLS(df_gdp["FCE"], sm.add_constant(df_gdp["GCF"])).fit()
print(m_ils1.summary())
pi1_0 = m_ils1.params["const"]
pi1_1 = m_ils1.params["GCF"]
print(f"\nπ₁₀ = {pi1_0:.6f},  π₁₁ = {pi1_1:.6f}")
# F(1,28)=5304.06 | R²=0.9947
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    FCE   R-squared:                       0.995
Model:                            OLS   Adj. R-squared:                  0.995
Method:                 Least Squares   F-statistic:                     5304.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.82e-33
Time:                        10:41:15   Log-Likelihood:                -87.918
No. Observations:                  30   AIC:                             179.8
Df Residuals:                      28   BIC:                             182.6
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         26.7969      1.607     16.671      0.000      23.504      30.090
GCF            1.7307      0.024     72.829      0.000       1.682       1.779
==============================================================================
Omnibus:                        2.241   Durbin-Watson:                   0.544
Prob(Omnibus):                  0.326   Jarque-Bera (JB):                1.483
Skew:                          -0.544   Prob(JB):                        0.476
Kurtosis:                       3.062   Cond. No.                         127.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

π₁₀ = 26.796913,  π₁₁ = 1.730703
m_ils2 = sm.OLS(df_gdp["Y"], sm.add_constant(df_gdp["GCF"])).fit()
print(m_ils2.summary())
pi2_0 = m_ils2.params["const"]
pi2_1 = m_ils2.params["GCF"]
print(f"\nπ₂₀ = {pi2_0:.6f},  π₂₁ = {pi2_1:.6f}")
# F(1,28)=13204.20 | R²=0.9979
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      Y   R-squared:                       0.998
Model:                            OLS   Adj. R-squared:                  0.998
Method:                 Least Squares   F-statistic:                 1.320e+04
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           5.40e-39
Time:                        10:41:15   Log-Likelihood:                -87.918
No. Observations:                  30   AIC:                             179.8
Df Residuals:                      28   BIC:                             182.6
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         26.7969      1.607     16.671      0.000      23.504      30.090
GCF            2.7307      0.024    114.910      0.000       2.682       2.779
==============================================================================
Omnibus:                        2.241   Durbin-Watson:                   0.544
Prob(Omnibus):                  0.326   Jarque-Bera (JB):                1.483
Skew:                          -0.544   Prob(JB):                        0.476
Kurtosis:                       3.062   Cond. No.                         127.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

π₂₀ = 26.796913,  π₂₁ = 2.730703
beta_ILS = pi1_1 / pi2_1
cons_ILS = pi1_0 / pi2_1
print("=== Kết quả ILS (Bảng 4.17) ===")
print(f"β (ILS) = π₁₁ / π₂₁ = {pi1_1:.6f} / {pi2_1:.6f} = {beta_ILS:.6f}")
print(f"α (ILS) = π₁₀ / π₂₁ = {pi1_0:.6f} / {pi2_1:.6f} = {cons_ILS:.6f}")
# β ≈ 0.634, α ≈ 9.813
Output
=== Kết quả ILS (Bảng 4.17) ===
β (ILS) = π₁₁ / π₂₁ = 1.730703 / 2.730703 = 0.633794
α (ILS) = π₁₀ / π₂₁ = 26.796913 / 2.730703 = 9.813191
m_ols_gdp = sm.OLS(df_gdp["FCE"], sm.add_constant(df_gdp["Y"])).fit()
print(m_ols_gdp.summary())
# β OLS ≈ 0.635, α ≈ 9.671
# Gần giống ILS vì mô hình gần như xác định đúng
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    FCE   R-squared:                       0.999
Model:                            OLS   Adj. R-squared:                  0.999
Method:                 Least Squares   F-statistic:                 3.982e+04
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.07e-45
Time:                        10:41:15   Log-Likelihood:                -57.750
No. Observations:                  30   AIC:                             119.5
Df Residuals:                      28   BIC:                             122.3
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          9.6713      0.661     14.626      0.000       8.317      11.026
Y              0.6346      0.003    199.540      0.000       0.628       0.641
==============================================================================
Omnibus:                        2.374   Durbin-Watson:                   0.546
Prob(Omnibus):                  0.305   Jarque-Bera (JB):                1.636
Skew:                          -0.572   Prob(JB):                        0.441
Kurtosis:                       3.027   Cond. No.                         439.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
df_wc, _ = pyreadstat.read_dta(
    "rawdata/working_children.dta",
    encoding="latin1",
)
df_wc["yearsofexperience2"] = df_wc["yearsofexperience"] ** 2
df_wc["experienceXgender"]  = df_wc["yearsofexperience"] * df_wc["gender"]

controls    = ["urban", "gender", "yearsofexperience", "yearsofexperience2",
               "experienceXgender", "RedRiverDelta", "Northmidlandareas",
               "CentralCoast", "Centralhighlands", "MekongRiverDelta"]
instruments = ["fatheredu", "motheredu"]

print("Thống kê mô tả:")
print(df_wc[["ln_wage","yearsofedu"] + instruments].describe())
Output
Thống kê mô tả:
           ln_wage   yearsofedu    fatheredu    motheredu
count  3611.000000  3611.000000  3611.000000  3611.000000
mean     10.857340     9.235946     7.180559     6.587372
std       0.818964     3.390674     3.648408     3.756552
min       6.396930     0.000000     0.000000     0.000000
25%      10.500948     7.000000     5.000000     4.000000
50%      11.066638    10.000000     8.000000     7.000000
75%      11.392451    12.000000     9.000000     9.000000
max      12.952997    18.000000    21.000000    16.000000
print("Tương quan yearsofedu với biến công cụ:")
print(df_wc[["yearsofedu"] + instruments].corr())
# fatheredu: 0.570, motheredu: 0.553 → tương quan đủ mạnh
Output
Tương quan yearsofedu với biến công cụ:
            yearsofedu  fatheredu  motheredu
yearsofedu    1.000000   0.570297   0.553409
fatheredu     0.570297   1.000000   0.678058
motheredu     0.553409   0.678058   1.000000
X_s1 = sm.add_constant(df_wc[instruments + controls])
m_s1 = sm.OLS(df_wc["yearsofedu"], X_s1).fit()
print(m_s1.summary())
# N=3,611 | F(12,3598)=477.84 | R²=0.6145
# fatheredu t=24.17***, motheredu t=17.48*** → biến công cụ mạnh
df_wc["yearsofedu_hat"] = m_s1.fittedvalues
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             yearsofedu   R-squared:                       0.614
Model:                            OLS   Adj. R-squared:                  0.613
Method:                 Least Squares   F-statistic:                     477.8
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:41:16   Log-Likelihood:                -7811.6
No. Observations:                3611   AIC:                         1.565e+04
Df Residuals:                    3598   BIC:                         1.573e+04
Df Model:                          12                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const                  7.3156      0.161     45.505      0.000       7.000       7.631
fatheredu              0.3180      0.013     24.167      0.000       0.292       0.344
motheredu              0.2347      0.013     17.483      0.000       0.208       0.261
urban                  0.4395      0.079      5.539      0.000       0.284       0.595
gender                 0.4876      0.121      4.039      0.000       0.251       0.724
yearsofexperience     -0.1209      0.010    -12.322      0.000      -0.140      -0.102
yearsofexperience2     0.0003      0.000      1.678      0.093   -5.44e-05       0.001
experienceXgender     -0.0284      0.005     -5.431      0.000      -0.039      -0.018
RedRiverDelta          0.3266      0.136      2.405      0.016       0.060       0.593
Northmidlandareas      0.2520      0.141      1.793      0.073      -0.024       0.527
CentralCoast           0.1497      0.130      1.155      0.248      -0.104       0.404
Centralhighlands      -0.3385      0.179     -1.896      0.058      -0.688       0.011
MekongRiverDelta      -0.2804      0.133     -2.101      0.036      -0.542      -0.019
==============================================================================
Omnibus:                       54.337   Durbin-Watson:                   1.732
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               81.270
Skew:                          -0.159   Prob(JB):                     2.25e-18
Kurtosis:                       3.662   Cond. No.                     7.16e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.16e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
X_s2 = sm.add_constant(df_wc[["yearsofedu_hat"] + controls])
m_s2 = sm.OLS(df_wc["ln_wage"], X_s2).fit()
print(m_s2.summary())
# yearsofedu_hat coef ≈ 0.111
# SE ở giai đoạn 2 thủ công không chính xác → dùng IV2SLS để có SE đúng
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                ln_wage   R-squared:                       0.264
Model:                            OLS   Adj. R-squared:                  0.261
Method:                 Least Squares   F-statistic:                     117.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):          1.20e-229
Time:                        10:41:16   Log-Likelihood:                -3849.4
No. Observations:                3611   AIC:                             7723.
Df Residuals:                    3599   BIC:                             7797.
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
======================================================================================
                         coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------------
const                  9.6873      0.087    111.542      0.000       9.517       9.858
yearsofedu_hat         0.1112      0.007     15.968      0.000       0.098       0.125
urban                  0.1022      0.027      3.751      0.000       0.049       0.156
gender                -0.1231      0.041     -3.029      0.002      -0.203      -0.043
yearsofexperience      0.0599      0.003     18.173      0.000       0.053       0.066
yearsofexperience2    -0.0010    6.4e-05    -16.095      0.000      -0.001      -0.001
experienceXgender     -0.0041      0.002     -2.331      0.020      -0.008      -0.001
RedRiverDelta         -0.1770      0.046     -3.873      0.000      -0.267      -0.087
Northmidlandareas     -0.6797      0.047    -14.474      0.000      -0.772      -0.588
CentralCoast          -0.4718      0.043    -10.905      0.000      -0.557      -0.387
Centralhighlands      -0.7990      0.060    -13.404      0.000      -0.916      -0.682
MekongRiverDelta      -0.2934      0.045     -6.562      0.000      -0.381      -0.206
==============================================================================
Omnibus:                      934.582   Durbin-Watson:                   1.499
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             2724.167
Skew:                          -1.338   Prob(JB):                         0.00
Kurtosis:                       6.309   Cond. No.                     7.67e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 7.67e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
# Kiểm định Sargan (overidentification): H₀ = biến công cụ ngoại sinh
sargan = m_iv.sargan
print("=== Sargan test ===")
print(f"chi2(1) = {sargan.stat:.5f},  p = {sargan.pval:.4f}")
# chi2 ≈ 2.48, p ≈ 0.115 → không bác bỏ H₀ → biến công cụ hợp lệ

# Kiểm định Wu-Hausman (endogeneity): H₀ = yearsofedu ngoại sinh
wu = m_iv.wu_hausman()
print("\n=== Wu-Hausman test ===")
print(f"chi2(1) = {wu.stat:.4f},  p = {wu.pval:.4f}")
# chi2 ≈ 40.75, p = 0.000 → bác bỏ H₀ → yearsofedu nội sinh → 2SLS cần thiết
Output
=== Sargan test ===
chi2(1) = 2.48139,  p = 0.1152

=== Wu-Hausman test ===
chi2(1) = 41.1669,  p = 0.0000
# Chapter 4 - Regression Specification (R version of chapter4.ipynb)
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(MASS); library(ggplot2); library(AER); library(lmtest)

# Point data_dir at the repo's data folder (or set env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

if (!dir.exists('figures')) dir.create('figures')

rd <- function(f) { d <- haven::read_dta(file.path(data_dir, f)); d[] <- lapply(d, function(x) if (inherits(x, "haven_labelled")) as.numeric(x) else x); as.data.frame(d) }

fml <- function(y, x) as.formula(paste(y, "~", paste(x, collapse = " + ")))

ols <- function(y, x, d) lm(fml(y, x), data = d)

chi2p <- function(x, df) pchisq(x, df, lower.tail = FALSE)

skew <- function(x) { m <- mean(x); mean((x-m)^3) / mean((x-m)^2)^1.5 }

kurt <- function(x) { m <- mean(x); mean((x-m)^4) / mean((x-m)^2)^2 }

jb <- function(r) { n <- length(r); s <- skew(r); k <- kurt(r); st <- n*(s^2/6 + (k-3)^2/24); c(JB = st, p = chi2p(st, 2)) }

df <- rd("migration_remittances_16_full.dta")

# --- 4.1 Omitted Variable Bias ---
# Example 1 (Tables 4.1-4.2)
df$agehead2 <- df$agehead^2

xvars_full1 <- c("remittances","HHsize","children15","elderly60","female_ratio","genderhead","agehead","agehead2","num_eduhead")

m1_r  <- ols("per_expenditure", "remittances", df); print(summary(m1_r))   # Python: N=9399 R2=0.0186
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
   Min     1Q Median     3Q    Max 
-67602 -11976  -5051   5543 431360 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 2.556e+04  2.467e+02  103.61   <2e-16 ***
remittances 1.280e-01  9.601e-03   13.34   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 22620 on 9397 degrees of freedom
Multiple R-squared:  0.01857,	Adjusted R-squared:  0.01847 
F-statistic: 177.8 on 1 and 9397 DF,  p-value: < 2.2e-16
m1_ur <- ols("per_expenditure", xvars_full1, df);  print(summary(m1_ur))  # Python: R2=0.1469
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
   Min     1Q Median     3Q    Max 
-55505 -10237  -3499   4909 422058 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)    
(Intercept)   1.256e+04  2.844e+03   4.419 1.00e-05 ***
remittances   1.158e-01  9.067e-03  12.771  < 2e-16 ***
HHsize       -8.814e+02  2.020e+02  -4.364 1.29e-05 ***
children15   -2.526e+03  3.369e+02  -7.499 6.99e-14 ***
elderly60    -2.881e+03  4.173e+02  -6.905 5.35e-12 ***
female_ratio -2.813e+03  1.145e+03  -2.455   0.0141 *  
genderhead    3.960e+03  5.705e+02   6.941 4.16e-12 ***
agehead       2.279e+02  1.050e+02   2.170   0.0300 *  
agehead2     -1.528e+00  9.629e-01  -1.587   0.1125    
num_eduhead   1.793e+03  6.144e+01  29.185  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 21100 on 9389 degrees of freedom
Multiple R-squared:  0.1469,	Adjusted R-squared:  0.1461 
F-statistic: 179.6 on 9 and 9389 DF,  p-value: < 2.2e-16
R2_r <- summary(m1_r)$r.squared; R2_ur <- summary(m1_ur)$r.squared

m_add <- 8; n1 <- nobs(m1_ur); k1 <- length(xvars_full1) + 1

F1 <- ((R2_ur - R2_r)/m_add) / ((1 - R2_ur)/(n1 - k1))

cat(sprintf("N=%d R2_r=%.4f R2_ur=%.4f F=%.2f p=%.4f\n", n1, R2_r, R2_ur, F1, pf(F1, m_add, n1-k1, lower.tail=FALSE)))
Output
N=9399 R2_r=0.0186 R2_ur=0.1469 F=176.55 p=0.0000
# Example 3: wage (Tables 4.3-4.6)
dw <- rd("wage2020.dta")

dw$yearsofexperience2 <- dw$yearsofexperience^2

dw$experienceXgender <- dw$yearsofexperience * dw$gender

xvars_r3 <- c("urban","gender","yearsofedu","yearsofexperience")

xvars_ur3 <- c(xvars_r3, "yearsofexperience2","experienceXgender","RedRiverDelta","Northmidlandareas","CentralCoast","Centralhighlands","MekongRiverDelta")

m3_r <- ols("wage", xvars_r3, dw); m3_ur <- ols("wage", xvars_ur3, dw)

print(summary(m3_r)); print(summary(m3_ur))  # Python: R2=0.2002 / 0.2949
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-119710  -29082   -4699   20680  755501 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)        10960.19    2148.70   5.101 3.44e-07 ***
urban              22330.79    1037.45  21.525  < 2e-16 ***
gender            -14529.32     966.35 -15.035  < 2e-16 ***
yearsofedu          5781.18     161.88  35.713  < 2e-16 ***
yearsofexperience    422.64      42.58   9.926  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47990 on 10113 degrees of freedom
Multiple R-squared:  0.2002,	Adjusted R-squared:  0.1999 
F-statistic:   633 on 4 and 10113 DF,  p-value: < 2.2e-16


Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-114522  -26506   -4811   18898  727839 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         19079.346   2662.710   7.165 8.30e-13 ***
urban               18961.147    992.050  19.113  < 2e-16 ***
gender             -15195.355   1833.266  -8.289  < 2e-16 ***
yearsofedu           5180.294    159.162  32.547  < 2e-16 ***
yearsofexperience    2959.695    125.930  23.503  < 2e-16 ***
yearsofexperience2    -52.186      2.311 -22.578  < 2e-16 ***
experienceXgender      13.213     71.699   0.184    0.854    
RedRiverDelta      -11210.562   1633.459  -6.863 7.13e-12 ***
Northmidlandareas  -36196.835   1737.218 -20.836  < 2e-16 ***
CentralCoast       -31958.725   1612.507 -19.819  < 2e-16 ***
Centralhighlands   -45520.637   2162.284 -21.052  < 2e-16 ***
MekongRiverDelta   -24197.565   1683.790 -14.371  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 45080 on 10106 degrees of freedom
Multiple R-squared:  0.2949,	Adjusted R-squared:  0.2942 
F-statistic: 384.3 on 11 and 10106 DF,  p-value: < 2.2e-16
R2_r3 <- summary(m3_r)$r.squared; R2_ur3 <- summary(m3_ur)$r.squared

m_add3 <- 7; n3 <- nobs(m3_ur); k3 <- length(xvars_ur3) + 1

F3 <- ((R2_ur3 - R2_r3)/m_add3) / ((1 - R2_ur3)/(n3 - k3))

cat(sprintf("N=%d F=%.2f p=%.4f\n", n3, F3, pf(F3, m_add3, n3-k3, lower.tail=FALSE)))
Output
N=10118 F=193.91 p=0.0000
# --- 4.2 Specification tests ---
# RESET (manual)
dw$wage_million <- dw$wage / 1000

m_reset <- ols("wage_million", xvars_r3, dw); print(summary(m_reset))
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-119.71  -29.08   -4.70   20.68  755.50 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)        10.96019    2.14870   5.101 3.44e-07 ***
urban              22.33079    1.03745  21.525  < 2e-16 ***
gender            -14.52932    0.96635 -15.035  < 2e-16 ***
yearsofedu          5.78118    0.16188  35.713  < 2e-16 ***
yearsofexperience   0.42264    0.04258   9.926  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47.99 on 10113 degrees of freedom
Multiple R-squared:  0.2002,	Adjusted R-squared:  0.1999 
F-statistic:   633 on 4 and 10113 DF,  p-value: < 2.2e-16
dw$yhat_million <- fitted(m_reset)

dw$yhat2_million <- dw$yhat_million^2; dw$yhat3_million <- dw$yhat_million^3; dw$yhat4_million <- dw$yhat_million^4

m_ext23  <- ols("wage_million", c(xvars_r3, "yhat2_million","yhat3_million"), dw)

m_ext234 <- ols("wage_million", c(xvars_r3, "yhat2_million","yhat3_million","yhat4_million"), dw)

print(summary(m_ext23)); print(summary(m_ext234))
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-157.83  -29.25   -4.26   21.42  741.06 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        2.863e+01  3.208e+00   8.925  < 2e-16 ***
urban              3.087e+01  6.075e+00   5.082 3.80e-07 ***
gender            -2.250e+01  3.836e+00  -5.866 4.60e-09 ***
yearsofedu         9.934e+00  1.479e+00   6.716 1.97e-11 ***
yearsofexperience  5.996e-01  1.159e-01   5.175 2.33e-07 ***
yhat2_million     -2.470e-02  3.843e-03  -6.428 1.35e-10 ***
yhat3_million      1.714e-04  1.781e-05   9.627  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47.07 on 10111 degrees of freedom
Multiple R-squared:  0.2307,	Adjusted R-squared:  0.2303 
F-statistic: 505.5 on 6 and 10111 DF,  p-value: < 2.2e-16


Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-158.43  -29.17   -4.33   21.36  741.31 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        2.874e+01  3.212e+00   8.948   <2e-16 ***
urban              2.350e+01  1.228e+01   1.914   0.0556 .  
gender            -1.761e+01  8.057e+00  -2.186   0.0289 *  
yearsofedu         7.962e+00  3.215e+00   2.477   0.0133 *  
yearsofexperience  4.576e-01  2.360e-01   1.939   0.0525 .  
yhat2_million     -1.565e-02  1.366e-02  -1.146   0.2519    
yhat3_million      7.814e-05  1.362e-04   0.574   0.5662    
yhat4_million      3.258e-07  4.716e-07   0.691   0.4897    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47.07 on 10110 degrees of freedom
Multiple R-squared:  0.2308,	Adjusted R-squared:  0.2302 
F-statistic: 433.3 on 7 and 10110 DF,  p-value: < 2.2e-16
RSS_base <- sum(resid(m_reset)^2)

rss_F <- function(m, q) { rss <- sum(resid(m)^2); d <- df.residual(m); F <- ((RSS_base - rss)/q)/(rss/d); c(F = F, dfd = d, p = pf(F, q, d, lower.tail = FALSE)) }

print(rss_F(m_ext23, 2))    # Python: F=200.46
Output
           F          dfd            p 
2.004629e+02 1.011100e+04 4.186051e-86 
print(rss_F(m_ext234, 3))   # Python: F=133.79
Output
           F          dfd            p 
1.337941e+02 1.011000e+04 5.284695e-85 
# Automatic RESET (powers 2:4)
print(resettest(m_reset, power = 2:4, type = "fitted"))   # Python: F=133.79
Output
	RESET test

data:  m_reset
RESET = 133.79, df1 = 3, df2 = 10110, p-value < 2.2e-16
# LM test
m_lm_r <- ols("wage", xvars_r3, dw)

dw$r_lm <- resid(m_lm_r)

m_lm_aux <- ols("r_lm", xvars_ur3, dw)

n_lm <- nobs(m_lm_aux); LM <- n_lm * summary(m_lm_aux)$r.squared

cat(sprintf("LM = %d x %.4f = %.2f, p = %.4e\n", n_lm, summary(m_lm_aux)$r.squared, LM, chi2p(LM, 7)))  # Python: R2~0.1184, LM~1198
Output
LM = 10118 x 0.1184 = 1198.06, p = 1.8565e-254
# Dropping irrelevant variables - Example 2 (Table 4.7)
df$HHsize2 <- df$HHsize^2

xvar_full <- c("ln_expenditure","agehead","agehead2","primary","secondary","high_school","higher_education","HHsize","HHsize2","dependency_ratio","domestic_remittances","overseas_remittances","urban","RedRiverDelta","Northmidlandareas","MekongRiverDelta","Centralhighlands","CentralCoast")

df_fs <- df[complete.cases(df[, c("food_share", xvar_full)]), ]

m_full <- ols("food_share", xvar_full, df_fs); print(summary(m_full))   # Python: N=8381 R2=0.6914
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.31121 -0.02293  0.00076  0.02161  0.53028 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
(Intercept)           8.971e-01  1.295e-02  69.272  < 2e-16 ***
ln_expenditure       -3.831e-02  1.101e-03 -34.788  < 2e-16 ***
agehead              -5.739e-04  2.648e-04  -2.167   0.0303 *  
agehead2              6.104e-06  2.500e-06   2.442   0.0146 *  
primary               7.075e-04  1.607e-03   0.440   0.6598    
secondary             1.662e-04  1.637e-03   0.102   0.9191    
high_school          -4.539e-04  2.012e-03  -0.226   0.8215    
higher_education      1.488e-03  2.561e-03   0.581   0.5613    
HHsize               -1.135e-01  1.443e-03 -78.683  < 2e-16 ***
HHsize2               8.610e-03  1.467e-04  58.678  < 2e-16 ***
dependency_ratio     -1.659e-03  8.791e-04  -1.887   0.0592 .  
domestic_remittances -1.429e-03  1.444e-03  -0.990   0.3224    
overseas_remittances -1.482e-03  2.893e-03  -0.512   0.6084    
urban                 1.239e-02  1.311e-03   9.450  < 2e-16 ***
RedRiverDelta        -3.150e-03  2.023e-03  -1.557   0.1195    
Northmidlandareas    -4.311e-03  2.069e-03  -2.084   0.0372 *  
MekongRiverDelta     -8.437e-03  1.998e-03  -4.222 2.45e-05 ***
Centralhighlands     -1.116e-02  2.577e-03  -4.329 1.52e-05 ***
CentralCoast         -1.039e-03  1.981e-03  -0.524   0.6001    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.04929 on 8362 degrees of freedom
Multiple R-squared:  0.6914,	Adjusted R-squared:  0.6908 
F-statistic:  1041 on 18 and 8362 DF,  p-value: < 2.2e-16
xvar_red <- c("ln_expenditure","agehead","agehead2","HHsize","HHsize2","dependency_ratio","urban","Northmidlandareas","MekongRiverDelta","Centralhighlands")

m_red <- ols("food_share", xvar_red, df_fs); print(summary(m_red))      # Python: R2=0.6912
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.31096 -0.02294  0.00076  0.02162  0.52868 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        8.961e-01  1.224e-02  73.236  < 2e-16 ***
ln_expenditure    -3.835e-02  1.006e-03 -38.106  < 2e-16 ***
agehead           -6.136e-04  2.629e-04  -2.334  0.01961 *  
agehead2           6.416e-06  2.478e-06   2.589  0.00965 ** 
HHsize            -1.135e-01  1.430e-03 -79.405  < 2e-16 ***
HHsize2            8.612e-03  1.463e-04  58.877  < 2e-16 ***
dependency_ratio  -1.771e-03  8.720e-04  -2.031  0.04232 *  
urban              1.269e-02  1.277e-03   9.939  < 2e-16 ***
Northmidlandareas -2.566e-03  1.492e-03  -1.721  0.08537 .  
MekongRiverDelta  -6.665e-03  1.407e-03  -4.735 2.22e-06 ***
Centralhighlands  -9.600e-03  2.157e-03  -4.450 8.72e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.04929 on 8370 degrees of freedom
Multiple R-squared:  0.6912,	Adjusted R-squared:  0.6909 
F-statistic:  1874 on 10 and 8370 DF,  p-value: < 2.2e-16
# Example 3: multicollinearity experience vs age (Table 4.8)
m_age <- ols("yearsofexperience", "age", dw); print(summary(m_age))     # Python: beta~0.964
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.0651  -2.5257  -0.6956   2.0433  10.4595 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) -17.444684   0.113726  -153.4   <2e-16 ***
age           1.061574   0.002896   366.5   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.36 on 10116 degrees of freedom
Multiple R-squared:   0.93,	Adjusted R-squared:   0.93 
F-statistic: 1.343e+05 on 1 and 10116 DF,  p-value: < 2.2e-16
# --- 4.3 Functional form (PE / Davidson-MacKinnon) ---
# Example 1: expenditure
df$ln_per_expenditure <- log(df$per_expenditure)

df$ln_remittances <- ifelse(df$remittances > 0, log(df$remittances), NA)

xvars_log <- c("ln_remittances","HHsize","children15","elderly60","female_ratio","genderhead","agehead","agehead2","num_eduhead")

df_logex <- df[!is.na(df$ln_remittances), ]

m_logex <- ols("ln_per_expenditure", xvars_log, df_logex); print(summary(m_logex))  # Python: N=7953 R2=0.2933
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.8652 -0.3423 -0.0116  0.3211  3.2301 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)     8.884e+00  7.851e-02 113.149  < 2e-16 ***
ln_remittances  7.399e-02  3.597e-03  20.571  < 2e-16 ***
HHsize         -1.530e-02  5.455e-03  -2.805 0.005041 ** 
children15     -1.336e-01  9.112e-03 -14.657  < 2e-16 ***
elderly60      -1.011e-01  1.098e-02  -9.202  < 2e-16 ***
female_ratio   -1.029e-01  3.057e-02  -3.365 0.000769 ***
genderhead      1.139e-01  1.523e-02   7.481 8.18e-14 ***
agehead         1.158e-02  2.814e-03   4.115 3.91e-05 ***
agehead2       -1.002e-04  2.556e-05  -3.918 8.99e-05 ***
num_eduhead     6.341e-02  1.666e-03  38.059  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5189 on 7943 degrees of freedom
Multiple R-squared:  0.2933,	Adjusted R-squared:  0.2925 
F-statistic: 366.2 on 9 and 7943 DF,  p-value: < 2.2e-16
mean_ln <- mean(df$ln_per_expenditure); gmean <- exp(mean_ln)

cat(sprintf("Mean ln = %.5f, gmean = %.2f\n", mean_ln, gmean))   # Python: 9.98008 / ~21592
Output
Mean ln = 9.98008, gmean = 21592.03
df$per_expenditure_g <- df$per_expenditure / gmean

df$lnper_expenditure_g <- log(df$per_expenditure_g)

m_lin_pe <- ols("per_expenditure_g", xvars_full1, df); RSS1_pe <- sum(resid(m_lin_pe)^2)

df_log2 <- df[!is.na(df$ln_remittances), ]

m_log_pe <- ols("lnper_expenditure_g", xvars_log, df_log2); RSS2_pe <- sum(resid(m_log_pe)^2)

N_pe <- nobs(m_log_pe); T_pe <- (N_pe/2) * log(RSS1_pe/RSS2_pe)

cat(sprintf("RSS1=%.4f RSS2=%.4f N=%d T=%.2f p=%.4e\n", RSS1_pe, RSS2_pe, N_pe, T_pe, chi2p(T_pe, 1)))  # Python: 8962.72 / 2138.76 / T=5697.72
Output
RSS1=8962.7166 RSS2=2138.7598 N=7953 T=5697.72 p=0.0000e+00
# Example 3: wage
dw$ln_wage <- log(dw$wage)

m_log_w <- ols("ln_wage", xvars_ur3, dw); print(summary(m_log_w))   # Python: R2=0.3197
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.8665 -0.2925  0.1098  0.4422  2.3864 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         9.999e+00  4.158e-02 240.480  < 2e-16 ***
urban               2.551e-01  1.549e-02  16.470  < 2e-16 ***
gender             -1.312e-01  2.863e-02  -4.585 4.60e-06 ***
yearsofedu          8.063e-02  2.485e-03  32.441  < 2e-16 ***
yearsofexperience   5.576e-02  1.966e-03  28.356  < 2e-16 ***
yearsofexperience2 -1.023e-03  3.609e-05 -28.345  < 2e-16 ***
experienceXgender  -3.628e-03  1.120e-03  -3.241   0.0012 ** 
RedRiverDelta      -1.385e-01  2.551e-02  -5.431 5.73e-08 ***
Northmidlandareas  -6.168e-01  2.713e-02 -22.739  < 2e-16 ***
CentralCoast       -4.743e-01  2.518e-02 -18.838  < 2e-16 ***
Centralhighlands   -8.505e-01  3.376e-02 -25.190  < 2e-16 ***
MekongRiverDelta   -3.180e-01  2.629e-02 -12.096  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7039 on 10106 degrees of freedom
Multiple R-squared:  0.3197,	Adjusted R-squared:  0.319 
F-statistic: 431.8 on 11 and 10106 DF,  p-value: < 2.2e-16
mean_lnw <- mean(dw$ln_wage); gmean_w <- exp(mean_lnw)

cat(sprintf("Mean ln_wage = %.5f, gmean = %.2f\n", mean_lnw, gmean_w))  # Python: 10.94526 / ~56685
Output
Mean ln_wage = 10.94526, gmean = 56684.96
dw$wage_g <- dw$wage / gmean_w; dw$lnwage_g <- log(dw$wage_g)

RSS1_w <- sum(resid(ols("wage_g", xvars_ur3, dw))^2)

m_log_w2 <- ols("lnwage_g", xvars_ur3, dw); RSS2_w <- sum(resid(m_log_w2)^2)

N_w <- nobs(m_log_w2); T_w <- (N_w/2) * log(RSS1_w/RSS2_w)

cat(sprintf("RSS1=%.4f RSS2=%.4f T=%.4f p=%.4e\n", RSS1_w, RSS2_w, T_w, chi2p(T_w, 1)))  # Python: 6390.48 / 5006.82 / 1234.44
Output
RSS1=6390.4827 RSS2=5006.8189 T=1234.4417 p=1.9964e-270
# --- 4.5 Outliers ---
# Example 4: traffic accidents (Tables 4.12-4.14)
da <- rd("rotations_accidents2022.dta")

da$idprovince <- seq_len(nrow(da))

m_acc <- ols("traffic_accidents", "rotations", da); print(summary(m_acc))  # Python: N=63 R2=0.6753
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-430.44  -70.80    1.85   51.18  602.45 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 29.451411  23.999519   1.227    0.224    
rotations    0.086337   0.007665  11.264   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 157.4 on 61 degrees of freedom
Multiple R-squared:  0.6753,	Adjusted R-squared:   0.67 
F-statistic: 126.9 on 1 and 61 DF,  p-value: < 2.2e-16
da$resid <- resid(m_acc); da$resid_sq <- da$resid^2

p1 <- ggplot(da, aes(idprovince, resid_sq)) + geom_line(linetype = "dashed", color = "#2b6999") +
  geom_vline(xintercept = 50, linetype = "dotted", color = "#a31414") +
  labs(x = "Province", y = "Squared residual", title = "Figure 4.1 - Squared residuals by province")

ggsave("figures/fig4_1.png", p1, width = 8, height = 4, dpi = 100, create.dir = TRUE)
OutputR output: fig4_1.png
da2 <- da[da$idprovince != 50, ]

m_acc2 <- ols("traffic_accidents", "rotations", da2); print(summary(m_acc2))  # Python: N=62 R2=0.3627
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-219.33  -67.43  -19.11   28.14  405.80 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 82.113138  18.847542   4.357 5.24e-05 ***
rotations    0.045669   0.007815   5.844 2.24e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 114.5 on 60 degrees of freedom
Multiple R-squared:  0.3627,	Adjusted R-squared:  0.3521 
F-statistic: 34.15 on 1 and 60 DF,  p-value: 2.237e-07
# Robust regression: Huber first, then biweight initialised at Huber (Table 4.14)
m_huber <- rlm(traffic_accidents ~ rotations, data = da, psi = psi.huber, maxit = 100)

m_rlm <- rlm(traffic_accidents ~ rotations, data = da, psi = psi.bisquare, init = coef(m_huber), maxit = 100)

print(summary(m_rlm))
Output
Call: rlm(formula = traffic_accidents ~ rotations, data = da, psi = psi.bisquare, 
    init = coef(m_huber), maxit = 100)
Residuals:
     Min       1Q   Median       3Q      Max 
 -85.000  -37.788    2.005   55.879 1689.433 

Coefficients:
            Value   Std. Error t value
(Intercept) 90.6092  9.9914     9.0687
rotations    0.0147  0.0032     4.6124

Residual standard error: 65.44 on 61 degrees of freedom
# NOT VERIFIED: Python notebook has no saved numeric output for RLM; R's MASS::rlm scale/SE conventions differ slightly from statsmodels.
# Figure 4.2: leverage vs normalized squared residual
lev <- hatvalues(m_acc); nr <- resid(m_acc)^2 / sum(resid(m_acc)^2)

dl <- data.frame(nr = nr, lev = lev, prov = da$province_en)

dl$lab <- ifelse(dl$lev > mean(lev) | dl$nr > mean(nr), as.character(dl$prov), "")

p2 <- ggplot(dl, aes(nr, lev)) + geom_point(color = "#2b6999") +
  geom_text(aes(label = lab), size = 2.5, hjust = -0.1, vjust = 0) +
  geom_hline(yintercept = mean(lev), linetype = "dashed") + geom_vline(xintercept = mean(nr), linetype = "dashed") +
  expand_limits(x = 0, y = 0) + labs(x = "Normalized residual squared", y = "Leverage")

ggsave("figures/fig4_2.png", p2, width = 8, height = 6, dpi = 100, create.dir = TRUE)
OutputR output: fig4_2.png
# Keeping outliers - Example 1 (Tables 4.15-4.16)
db <- rd("migration_remittances_16_full.dta")

db$agehead2 <- db$agehead^2

db$remittances_1 <- ifelse(db$remittances == 0, 1, db$remittances)

db$ln_remittances_1 <- log(db$remittances_1)

db$not_remittances <- as.integer(db$remittances == 0)

db$ln_per_expenditure <- log(db$per_expenditure)

xvars_b <- c("ln_remittances_1","not_remittances","HHsize","children15","elderly60","female_ratio","genderhead","agehead","agehead2","num_eduhead")

m_battese <- ols("ln_per_expenditure", xvars_b, db); print(summary(m_battese))  # Python: N=9399 R2=0.2944
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.8681 -0.3457 -0.0109  0.3241  3.2104 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)       8.837e+00  7.379e-02 119.761  < 2e-16 ***
ln_remittances_1  7.170e-02  3.617e-03  19.821  < 2e-16 ***
not_remittances   4.987e-01  3.166e-02  15.750  < 2e-16 ***
HHsize           -1.806e-02  5.083e-03  -3.553 0.000383 ***
children15       -1.339e-01  8.460e-03 -15.834  < 2e-16 ***
elderly60        -1.000e-01  1.043e-02  -9.589  < 2e-16 ***
female_ratio     -1.004e-01  2.856e-02  -3.516 0.000440 ***
genderhead        1.200e-01  1.422e-02   8.436  < 2e-16 ***
agehead           1.321e-02  2.627e-03   5.029 5.02e-07 ***
agehead2         -1.082e-04  2.403e-05  -4.503 6.78e-06 ***
num_eduhead       6.483e-02  1.542e-03  42.028  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5258 on 9388 degrees of freedom
Multiple R-squared:  0.2944,	Adjusted R-squared:  0.2936 
F-statistic: 391.6 on 10 and 9388 DF,  p-value: < 2.2e-16
for (v in c("remittances","per_expenditure")) {
  q <- quantile(db[[v]], c(.25,.75), type = 7); iqr <- q[2]-q[1]
  db[[paste0("outlier_", v)]] <- as.integer(db[[v]] < q[1]-1.5*iqr | db[[v]] > q[2]+1.5*iqr)
  cat(sprintf("outlier_%s: %d obs\n", v, sum(db[[paste0("outlier_", v)]])))
}
Output
outlier_remittances: 1331 obs
outlier_per_expenditure: 472 obs
m_outlier <- ols("ln_per_expenditure", c(xvars_b, "outlier_per_expenditure","outlier_remittances"), db)

print(summary(m_outlier))  # Python: R2=0.4590
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.96711 -0.31011  0.00622  0.32263  1.97208 

Coefficients:
                          Estimate Std. Error t value Pr(>|t|)    
(Intercept)              8.853e+00  6.706e-02 132.015  < 2e-16 ***
ln_remittances_1         6.121e-02  4.177e-03  14.652  < 2e-16 ***
not_remittances          4.052e-01  3.323e-02  12.192  < 2e-16 ***
HHsize                  -1.078e-02  4.455e-03  -2.419  0.01558 *  
children15              -1.200e-01  7.413e-03 -16.186  < 2e-16 ***
elderly60               -7.784e-02  9.145e-03  -8.512  < 2e-16 ***
female_ratio            -7.973e-02  2.502e-02  -3.187  0.00144 ** 
genderhead               8.328e-02  1.247e-02   6.677 2.58e-11 ***
agehead                  1.473e-02  2.301e-03   6.403 1.59e-10 ***
agehead2                -1.225e-04  2.105e-05  -5.822 6.02e-09 ***
num_eduhead              5.419e-02  1.368e-03  39.613  < 2e-16 ***
outlier_per_expenditure  1.192e+00  2.230e-02  53.435  < 2e-16 ***
outlier_remittances     -2.443e-02  1.862e-02  -1.312  0.18952    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4605 on 9386 degrees of freedom
Multiple R-squared:  0.459,	Adjusted R-squared:  0.4583 
F-statistic: 663.5 on 12 and 9386 DF,  p-value: < 2.2e-16
# --- 4.6 Jarque-Bera ---
# Example 4: accidents
r4 <- resid(m_acc)

cat(sprintf("Obs=%d Mean=%.2e SD=%.2f Skew=%.4f Kurt=%.4f\n", length(r4), mean(r4), sd(r4), skew(r4), kurt(r4)))
Output
Obs=63 Mean=-4.52e-15 SD=156.11 Skew=0.6520 Kurt=6.3039
print(jb(r4))   # Python: JB~33.12, p=6.4e-08
Output
          JB            p 
3.311777e+01 6.435284e-08 
cat("chi2 crit 5%:", qchisq(.95, 2), "\n")
Output
chi2 crit 5%: 5.991465 
print(jb(resid(m_acc2)))   # Python: JB~30.29, p=2.7e-07
Output
          JB            p 
3.028681e+01 2.650344e-07 
# Example 1: expenditure
r1 <- resid(m_outlier)

cat(sprintf("Obs=%d Mean=%.2e SD=%.4f Skew=%.4f Kurt=%.4f\n", length(r1), mean(r1), sd(r1), skew(r1), kurt(r1)))
Output
Obs=9399 Mean=2.41e-17 SD=0.4602 Skew=-0.1338 Kurt=3.0580
print(jb(r1))   # Python: JB~29.35
Output
          JB            p 
2.935127e+01 4.231087e-07 
p3 <- ggplot(data.frame(r = r1), aes(r)) + geom_histogram(aes(y = after_stat(density)), bins = 40, fill = "#B3B3B3", alpha = .7) +
  stat_function(fun = dnorm, args = list(mean = mean(r1), sd = sd(r1)), color = "#a31414", linewidth = 1) +
  labs(x = "Residual", y = "Density", title = "Figure 4.3 - Residual distribution")

ggsave("figures/fig4_3.png", p3, width = 7, height = 4, dpi = 100, create.dir = TRUE)
OutputR output: fig4_3.png
# --- 4.8 Simultaneity ---
# ILS (Tables 4.17-4.18)
dg <- rd("GCF_FCE.dta"); dg$Y <- dg$FCE + dg$GCF

print(summary(dg[, c("FCE","GCF","Y")]))
Output
      FCE              GCF               Y         
 Min.   : 46.50   Min.   : 11.30   Min.   : 57.80  
 1st Qu.: 67.29   1st Qu.: 23.70   1st Qu.: 90.99  
 Median :113.41   Median : 54.80   Median :168.21  
 Mean   :125.84   Mean   : 57.23   Mean   :183.07  
 3rd Qu.:175.06   3rd Qu.: 82.51   3rd Qu.:257.56  
 Max.   :246.94   Max.   :127.44   Max.   :374.38  
m_ils1 <- lm(FCE ~ GCF, dg); m_ils2 <- lm(Y ~ GCF, dg)

print(summary(m_ils1)); print(summary(m_ils2))   # Python: R2=0.9947 / 0.9979
Output
Call:
lm(formula = FCE ~ GCF, data = dg)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.1852  -0.6036   0.1801   2.0830   7.8965 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 26.79691    1.60742   16.67 4.53e-16 ***
GCF          1.73070    0.02376   72.83  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.693 on 28 degrees of freedom
Multiple R-squared:  0.9947,	Adjusted R-squared:  0.9946 
F-statistic:  5304 on 1 and 28 DF,  p-value: < 2.2e-16


Call:
lm(formula = Y ~ GCF, data = dg)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.1852  -0.6036   0.1801   2.0830   7.8965 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 26.79691    1.60742   16.67 4.53e-16 ***
GCF          2.73070    0.02376  114.91  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.693 on 28 degrees of freedom
Multiple R-squared:  0.9979,	Adjusted R-squared:  0.9978 
F-statistic: 1.32e+04 on 1 and 28 DF,  p-value: < 2.2e-16
pi1_0 <- coef(m_ils1)[1]; pi1_1 <- coef(m_ils1)[2]; pi2_1 <- coef(m_ils2)[2]

cat(sprintf("ILS beta=%.6f alpha=%.6f\n", pi1_1/pi2_1, pi1_0/pi2_1))   # Python: 0.634 / 9.813
Output
ILS beta=0.633794 alpha=9.813191
m_ols_gdp <- lm(FCE ~ Y, dg); print(summary(m_ols_gdp))   # Python: beta 0.635, alpha 9.671
Output
Call:
lm(formula = FCE ~ Y, data = dg)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.7077 -0.2747  0.1610  0.7380  2.8708 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  9.67133    0.66122   14.63 1.22e-14 ***
Y            0.63457    0.00318  199.54  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.717 on 28 degrees of freedom
Multiple R-squared:  0.9993,	Adjusted R-squared:  0.9993 
F-statistic: 3.982e+04 on 1 and 28 DF,  p-value: < 2.2e-16
# 2SLS (Tables 4.20-4.23)
dc <- rd("working_children.dta")

dc$yearsofexperience2 <- dc$yearsofexperience^2; dc$experienceXgender <- dc$yearsofexperience * dc$gender

controls <- c("urban","gender","yearsofexperience","yearsofexperience2","experienceXgender","RedRiverDelta","Northmidlandareas","CentralCoast","Centralhighlands","MekongRiverDelta")

instruments <- c("fatheredu","motheredu")

print(summary(dc[, c("ln_wage","yearsofedu", instruments)]))
Output
    ln_wage         yearsofedu       fatheredu        motheredu     
 Min.   : 6.397   Min.   : 0.000   Min.   : 0.000   Min.   : 0.000  
 1st Qu.:10.501   1st Qu.: 7.000   1st Qu.: 5.000   1st Qu.: 4.000  
 Median :11.067   Median :10.000   Median : 8.000   Median : 7.000  
 Mean   :10.857   Mean   : 9.236   Mean   : 7.181   Mean   : 6.587  
 3rd Qu.:11.392   3rd Qu.:12.000   3rd Qu.: 9.000   3rd Qu.: 9.000  
 Max.   :12.953   Max.   :18.000   Max.   :21.000   Max.   :16.000  
print(cor(dc[, c("yearsofedu", instruments)], use = "complete.obs"))   # Python: 0.570, 0.553
Output
           yearsofedu fatheredu motheredu
yearsofedu  1.0000000 0.5702969 0.5534092
fatheredu   0.5702969 1.0000000 0.6780583
motheredu   0.5534092 0.6780583 1.0000000
m_s1 <- ols("yearsofedu", c(instruments, controls), dc); print(summary(m_s1))  # Python: N=3611 R2=0.6145
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-9.1041 -1.2695 -0.0165  1.3228  6.9317 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         7.3155997  0.1607661  45.505  < 2e-16 ***
fatheredu           0.3180009  0.0131585  24.167  < 2e-16 ***
motheredu           0.2347430  0.0134268  17.483  < 2e-16 ***
urban               0.4394760  0.0793490   5.539 3.27e-08 ***
gender              0.4876278  0.1207294   4.039 5.48e-05 ***
yearsofexperience  -0.1209178  0.0098128 -12.322  < 2e-16 ***
yearsofexperience2  0.0003228  0.0001924   1.678   0.0935 .  
experienceXgender  -0.0284025  0.0052295  -5.431 5.97e-08 ***
RedRiverDelta       0.3265724  0.1357989   2.405   0.0162 *  
Northmidlandareas   0.2519736  0.1405175   1.793   0.0730 .  
CentralCoast        0.1496506  0.1295474   1.155   0.2481    
Centralhighlands   -0.3385084  0.1785100  -1.896   0.0580 .  
MekongRiverDelta   -0.2804195  0.1334879  -2.101   0.0357 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.109 on 3598 degrees of freedom
Multiple R-squared:  0.6145,	Adjusted R-squared:  0.6132 
F-statistic: 477.8 on 12 and 3598 DF,  p-value: < 2.2e-16
dc$yearsofedu_hat <- fitted(m_s1)

m_s2 <- ols("ln_wage", c("yearsofedu_hat", controls), dc); print(summary(m_s2))  # Python: coef~0.111 (SE not valid)
Output
Call:
lm(formula = fml(y, x), data = d)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.1408 -0.2830  0.1176  0.4408  2.0963 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         9.687e+00  8.685e-02 111.542  < 2e-16 ***
yearsofedu_hat      1.112e-01  6.961e-03  15.968  < 2e-16 ***
urban               1.022e-01  2.725e-02   3.751 0.000179 ***
gender             -1.231e-01  4.065e-02  -3.029 0.002468 ** 
yearsofexperience   5.987e-02  3.295e-03  18.173  < 2e-16 ***
yearsofexperience2 -1.030e-03  6.398e-05 -16.095  < 2e-16 ***
experienceXgender  -4.115e-03  1.765e-03  -2.331 0.019800 *  
RedRiverDelta      -1.770e-01  4.569e-02  -3.873 0.000110 ***
Northmidlandareas  -6.797e-01  4.696e-02 -14.474  < 2e-16 ***
CentralCoast       -4.718e-01  4.326e-02 -10.905  < 2e-16 ***
Centralhighlands   -7.990e-01  5.961e-02 -13.404  < 2e-16 ***
MekongRiverDelta   -2.934e-01  4.472e-02  -6.562 6.07e-11 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7038 on 3599 degrees of freedom
Multiple R-squared:  0.2637,	Adjusted R-squared:  0.2615 
F-statistic: 117.2 on 11 and 3599 DF,  p-value: < 2.2e-16
iv_f <- as.formula(paste("ln_wage ~", paste(c("yearsofedu", controls), collapse = " + "), "|",
                         paste(c(instruments, controls), collapse = " + ")))

m_iv <- ivreg(iv_f, data = dc)

print(summary(m_iv, diagnostics = TRUE))   # Python: yearsofedu ~0.111, z=15.98
Output
Call:
ivreg(formula = iv_f, data = dc)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.1767 -0.2921  0.1119  0.4423  2.0597 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         9.687e+00  8.691e-02 111.457  < 2e-16 ***
yearsofedu          1.112e-01  6.967e-03  15.956  < 2e-16 ***
urban               1.022e-01  2.727e-02   3.748 0.000181 ***
gender             -1.231e-01  4.068e-02  -3.027 0.002487 ** 
yearsofexperience   5.987e-02  3.297e-03  18.159  < 2e-16 ***
yearsofexperience2 -1.030e-03  6.403e-05 -16.083  < 2e-16 ***
experienceXgender  -4.115e-03  1.767e-03  -2.329 0.019893 *  
RedRiverDelta      -1.770e-01  4.573e-02  -3.870 0.000111 ***
Northmidlandareas  -6.797e-01  4.699e-02 -14.463  < 2e-16 ***
CentralCoast       -4.718e-01  4.330e-02 -10.897  < 2e-16 ***
Centralhighlands   -7.990e-01  5.965e-02 -13.394  < 2e-16 ***
MekongRiverDelta   -2.934e-01  4.475e-02  -6.557 6.27e-11 ***

Diagnostic tests:
                  df1  df2 statistic  p-value    
Weak instruments    2 3598  1149.126  < 2e-16 ***
Wu-Hausman          1 3598    41.069 1.66e-10 ***
Sargan              1   NA     2.481    0.115    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.7043 on 3599 degrees of freedom
Multiple R-Squared: 0.2626,	Adjusted R-squared: 0.2603 
Wald test:   117 on 11 and 3599 DF,  p-value: < 2.2e-16 
# Sargan (overidentification), H0: instruments exogenous
ivres <- resid(m_iv); aux <- lm(ivres ~ ., data = dc[, c(instruments, controls)])

sg <- nobs(aux) * summary(aux)$r.squared

cat(sprintf("Sargan chi2(1) = %.5f, p = %.4f\n", sg, chi2p(sg, 1)))   # Python: 2.48, p=0.115
Output
Sargan chi2(1) = 2.48139, p = 0.1152
# Wu-Hausman (control-function version)
m_cf <- lm(fml("ln_wage", c("yearsofedu", controls, "v1")), data = transform(dc, v1 = resid(m_s1)))

cat("Wu-Hausman (control function) t-stat on first-stage residual:\n"); print(coef(summary(m_cf))["v1", ])
Output
Wu-Hausman (control function) t-stat on first-stage residual:
     Estimate    Std. Error       t value      Pr(>|t|) 
-5.634270e-02  8.791889e-03 -6.408486e+00  1.660296e-10 
# NOT VERIFIED: Wu-Hausman. ivreg reports the F version (41.07, p=1.7e-10); linearmodels' chi2 version in Python was 40.75. Same conclusion (reject exogeneity); the statistic differs by form, not a bug.
# NOTE: R's ivreg SEs use a df-corrected sigma (15.956 t-stat) vs Python's 'unadjusted' z=15.98 - asymptotically equivalent.
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chapter4" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chapter4" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 4                                                 */
/*      File Name:  chapter4.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Regression specification                      */  
/*      Input File:     migration_remittances_16_full.dta         */
/*                      wage2020.dta                              */
/*                      rotations_ accidents2022.dta              */
/*                      _migration_remittances_16_full.dta        */ 
/*                      GCF_FCE.dta                               */
/*                      working_children.dta                      */  
/*      Output File:    chapter4.log                              */  
/******************************************************************/ 

log using chapter4.log, text replace

use "$link\migration_remittances_16_full.dta",clear

gen agehead2 = agehead^2

global xvarfull1 "remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead"

reg per_expenditure $xvarfull1

test HHsize=children15=elderly60=female_ratio=genderhead=agehead=agehead2=num_eduhead=0

use "$link\wage2020.dta", clear

gen yearsofexperience2 = yearsofexperience^2

gen experienceXgender=yearsofexperience*gender

global xvarfull3 "urban gender yearsofedu yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta"

reg wage $xvarfull3

test yearsofexperience2=experienceXgender=RedRiverDelta=Northmidlandareas=CentralCoast=Centralhighlands=MekongRiverDelta=0

**# Kiểm định RESET (Ramsey's Regression Specification Error)

quietly reg wage urban gender yearsofedu yearsofexperience

//Bước 1: Tạo biến yhat là giá trị dự báo của biến giải thích
predict yhat

//Bước 2: Tạo hai biến là yhat2 là bình phương của yhat và yhat3 là lập phương của yhat. Sau đó hồi quy các biến yhat, yhat2 và yhat3 với mô hình ban đầu.

gen yhat2 = yhat^2

gen yhat3 = yhat^3

reg  wage urban gender yearsofedu yearsofexperience yhat2 yhat3

test yhat2 yhat3

sum wage urban gender yearsofedu yearsofexperience

gen wage_million = wage/1000

quietly reg wage_million urban gender yearsofedu yearsofexperience

predict yhat_million

gen yhat2_million = yhat_million^2

gen yhat3_million = yhat_million^3

reg  wage_million urban gender yearsofedu yearsofexperience yhat2_million yhat3_million

test yhat2_million yhat3_million

quietly reg wage_million urban gender yearsofedu yearsofexperience

ovtest

**# Kiểm định LM (Lagrange Multiplier)

//Bước 1: Tạo biến r là phần dư e

quietly reg wage urban gender yearsofedu yearsofexperience
predict r, residual 

//Bước 2: Hồi quy phần dư với toàn bộ các biến giải thích trong mô hình gốc và các biến bị bỏ sót

quietly reg r $xvarfull3 

display e(N)*e(r2)

display invchi2tail(2, 0.001)

display chi2tail(2, e(N)*e(r2))

**# Loại bỏ biến không liên quan (ngưỡng có mức ý nghĩa 90%)

use "$link\migration_remittances_16_full.dta",clear

gen agehead2=agehead^2

gen HHsize2=HHsize^2

regress food_share ln_expenditure agehead agehead2 HHsize HHsize2 dependency_ratio urban Northmidlandareas MekongRiverDelta Centralhighlands

use "$link\wage2020.dta", clear

reg yearsofexperience age,beta

**# Mô hình sử dụng dạng hàm không phù hợp
// Hồi quy ví dụ về chi tiêu

use "$link\migration_remittances_16_full.dta",clear

gen agehead2 = agehead^2

global xvarfull1 "remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead"

sum per_expenditure $xvarfull1

reg ln_per_expenditure ln_remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead

//Bước 1

quietly sum ln_per_expenditure

local gmean = exp(r(mean))     

display "Geometric mean: `gmean'"

//Bước 2

gen per_expenditure_g= per_expenditure/exp(r(mean))

gen lnper_expenditure_g=ln(per_expenditure_g)

//Bước 3

quietly reg per_expenditure_g $xvarfull1

scalar RSS1=e(rss)

di RSS1

//Bước 4

quietly reg lnper_expenditure_g ln_remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead

scalar RSS2 =e(rss)

scalar N =e(N)

di RSS2

//Bước 5

scalar test=(e(N)/2)*log(RSS1/RSS2)

di test 

scalar pvalue=chi2tail(1,test)

di pvalue


**# Hồi quy ví dụ về mức lương
use "$link\wage2020.dta", clear

gen yearsofexperience2 = yearsofexperience^2

gen experienceXgender=yearsofexperience*gender

global xvarfull3 "urban gender yearsofedu yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta"

reg ln_wage $xvarfull3 

//Bước 1

quietly sum ln_wage

local gmean = exp(r(mean))      

display "Geometric mean: `gmean'"

//Bước 2

gen wage_g= wage/exp(r(mean))

gen lnwage_g=ln(wage_g)

//Bước 3

quietly reg wage_g $xvarfull3

scalar RSS1=e(rss)

di RSS1

//Bước 4

quietly reg lnwage_g $xvarfull3

scalar RSS2 =e(rss)

scalar N =e(N)

di RSS2

//Bước 5

scalar test=(e(N)/2)*log(RSS1/RSS2)

di test 

scalar pvalue=chi2tail(1,test)

di pvalue

**# Quan sát có giá trị bất thường

use "$link\rotations_accidents2022.dta" , clear

reg traffic_accidents rotations

gen idprovince = _n

predict r,residual 

gen r2=r^2

line r2 idprovince

graph export Chapter4.5.1.png , as(png) name("Graph") replace

tempfile tmpdata

save `tmpdata'

drop if idprovince==50

reg traffic_accidents rotations

use `tmpdata', clear

rreg traffic_accidents rotations

quietly reg traffic_accidents rotations

lvr2plot

graph export Chapter4.5.2.png, as(png) name("Graph") replace

use "$link\migration_remittances_16_full.dta",clear

gen agehead2 = agehead^2

drop if ln_remittances==.

// Danh sách các biến cần kiểm tra outliers

local vars ln_per_expenditure ln_remittances  

foreach var in `vars' {
    * Tính mean và SD của biến
	sum `var',detail
    local mean = r(mean)
    local sd = r(sd)
    
    * Xác định ngưỡng outliers
    local lower = `mean' - 3*`sd'
    local upper = `mean' + 3*`sd'
    
    * Tạo biến chỉ báo outliers (1 nếu là outlier, 0 nếu không)
    gen outlier_`var' = (`var' < `lower' | `var' > `upper') 
}

reg ln_per_expenditure ln_remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead outlier_ln_per_expenditure outlier_ln_remittances

// Cách xử lý của  Battese (1997) trong một số trường hợp
use "$link\migration_remittances_16_full.dta",clear

gen agehead2 = agehead^2

gen remittances_1 = remittances 

replace remittances_1 = 1 if remittances_1 == 0

gen ln_remittances_1 = ln( remittances_1)

gen not_remittances=(remittances_1==1)

local vars remittances per_expenditure

foreach var of local vars {
    * Tính Q1, Q3 và IQR cho biến `var`
    quietly summarize `var', detail
    scalar Q1 = r(p25)
    scalar Q3 = r(p75)
    scalar IQR = Q3 - Q1

    * Tính giới hạn dưới và trên
    scalar lower_limit = Q1 - 1.5 * IQR
    scalar upper_limit = Q3 + 1.5 * IQR

    * Tạo biến đánh dấu outliers cho biến `var`
    gen outlier_`var' = 0
    replace outlier_`var' = 1 if `var' < lower_limit | `var' > upper_limit
}

reg ln_per_expenditure ln_remittances_1 not_remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead outlier_per_expenditure outlier_remittances

save _migration_remittances_16_full.dta, replace

**# Kiểm định JB (Jarque-Bera)

use "$link\rotations_accidents2022.dta" , clear

quietly reg traffic_accidents rotations

predict r, residual

sum r, detail

// Cài đặt gói jb: ssc install jb

jb r

use "$link\rotations_accidents2022.dta" , clear

gen idprovince = _n

drop if idprovince==50

quietly reg traffic_accidents rotations

predict r, residual

sum r, detail

jb r

use _migration_remittances_16_full.dta,clear

quietly reg ln_per_expenditure ln_remittances_1 not_remittances HHsize children15 elderly60 female_ratio genderhead agehead agehead2 num_eduhead outlier_per_expenditure outlier_remittances

predict r , residual

sum r, detail

histogram r, normal

graph export Chapter4.6.png , as(png) name("Graph") replace

jb r

display invchi2tail(2, 0.05)

**# Phương pháp bình phương tối thiểu gián tiếp (ILS)

use "$link\GCF_FCE.dta",clear

gen Y=FCE+GCF

//ILS

ivreg FCE ( Y = GCF )

//OLS

reg FCE Y

**# Phương pháp bình phương nhỏ nhất hai giai đoạn (2SLS)

use "$link\working_children.dta",clear

gen yearsofexperience2 = yearsofexperience^2

gen experienceXgender=yearsofexperience*gender

sum  ln_wage urban gender yearsofedu yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta fatheredu motheredu

//Tương quan biến công cụ và biến nội sinh

corr yearsofedu fatheredu motheredu

//Hồi quy giai đoạn 1, đồng thời tạo ra biến dự đoán yearsofedu_hat

reg yearsofedu fatheredu motheredu urban gender  yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta

predict yearsofedu_hat

//Hồi quy giai đoạn 2

reg ln_wage yearsofedu_hat urban gender  yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta

ivregress 2sls ln_wage ( yearsofedu= fatheredu motheredu) urban gender  yearsofexperience yearsofexperience2 experienceXgender RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta

//Kiểm định tính ngoại sinh

estat overid

//Kiểm định mô hình nội sinh

estat endogenous

log close

R, not checked against Python: Robust regression (rlm) has no Python output to compare. Wu-Hausman is reported as F in R (41.07) and chi-square in Python (40.75).

Files: Notebook · Open in Colab · R script · Stata do-file

Data: GCF_FCE.dta · migration_remittances_16_full.dta · rotations_accidents2022.dta · wage2020.dta · working_children.dta

Chapter 5 Dummy variables

Qualitative regressors, interactions, no-constant models, COVID shock, piecewise regression.

df_wage, _ = pyreadstat.read_dta(
    "rawdata/wage2020.dta",
    encoding="latin1",
)

df_gdp, _ = pyreadstat.read_dta(
    "rawdata/GDP_population_top.dta",
    encoding="latin1",
)

df_gcf, _ = pyreadstat.read_dta(
    "rawdata/GCF_GS.dta",
    encoding="latin1",
)

df_gdp_unemp, _ = pyreadstat.read_dta(
    "rawdata/GDP_unemploymentrate.dta",
    encoding="latin1",
)

df_disaster, _ = pyreadstat.read_dta(
    "rawdata/disaster.dta",
    encoding="latin1",
)

df_migration, _ = pyreadstat.read_dta(
    "rawdata/migration_remittances_16_full.dta",
    encoding="latin1",
)

print(df_wage.shape, df_gdp.shape, df_gcf.shape, df_disaster.shape, df_migration.shape)
Output
(10118, 19) (63, 7) (28, 3) (2813, 13) (9399, 65)
X1 = sm.add_constant(df_wage[["yearsofexperience", "gender"]])
model1 = sm.OLS(df_wage["wage"], X1).fit()
print(model1.summary())
# gender ≈ -13 248 → nữ thu nhập thấp hơn nam ~13 248 VNĐ/tháng (kiểm soát kinh nghiệm)
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.019
Model:                            OLS   Adj. R-squared:                  0.019
Method:                 Least Squares   F-statistic:                     98.57
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           4.01e-43
Time:                        10:37:08   Log-Likelihood:            -1.2445e+05
No. Observations:               10118   AIC:                         2.489e+05
Df Residuals:                   10115   BIC:                         2.489e+05
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              8.732e+04   1189.065     73.438      0.000     8.5e+04    8.97e+04
yearsofexperience  -306.1279     41.694     -7.342      0.000    -387.857    -224.399
gender            -1.325e+04   1069.342    -12.389      0.000   -1.53e+04   -1.12e+04
==============================================================================
Omnibus:                     6386.467   Durbin-Watson:                   1.213
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           147460.768
Skew:                           2.640   Prob(JB):                         0.00
Kurtosis:                      20.942   Cond. No.                         66.3
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Tạo biến topPCI bằng pandas (tương đương xtile nq(4) của Stata)
X2 = sm.add_constant(df_gdp[["topPCI", "population"]])
model2 = sm.OLS(df_gdp["GDP"], X2).fit()
print(model2.summary())
# topPCI ≈ +62 → tỉnh nhóm PCI cao có GDP cao hơn ~62 nghìn tỷ so với nhóm còn lại
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GDP   R-squared:                       0.895
Model:                            OLS   Adj. R-squared:                  0.892
Method:                 Least Squares   F-statistic:                     256.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           4.10e-30
Time:                        10:37:08   Log-Likelihood:                -362.90
No. Observations:                  63   AIC:                             731.8
Df Residuals:                      60   BIC:                             738.2
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       -101.2741     15.913     -6.364      0.000    -133.105     -69.443
topPCI        61.9812     23.393      2.650      0.010      15.188     108.774
population   151.9592      6.714     22.633      0.000     138.529     165.390
==============================================================================
Omnibus:                       12.978   Durbin-Watson:                   1.370
Prob(Omnibus):                  0.002   Jarque-Bera (JB):               42.019
Skew:                           0.255   Prob(JB):                     7.51e-10
Kurtosis:                       6.968   Cond. No.                         5.77
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
for s in range(6):   # sector 0..5
    df_wage[f"sector{s}"] = (df_wage["sector"] == s).astype(int)

X3 = sm.add_constant(df_wage[["yearsofexperience"] + [f"sector{i}" for i in range(1, 6)]])
model3 = sm.OLS(df_wage["wage"], X3).fit()
print(model3.summary())
# sector0 = nhóm cơ sở; sector3 ≈ +61 757, sector4 ≈ +69 540 so với nhóm cơ sở
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.223
Model:                            OLS   Adj. R-squared:                  0.222
Method:                 Least Squares   F-statistic:                     483.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:37:08   Log-Likelihood:            -1.2327e+05
No. Observations:               10118   AIC:                         2.466e+05
Df Residuals:                   10111   BIC:                         2.466e+05
Df Model:                           6                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              2.793e+04   1496.897     18.661      0.000     2.5e+04    3.09e+04
yearsofexperience   201.6355     38.522      5.234      0.000     126.124     277.147
sector1            2.828e+04   1409.962     20.056      0.000    2.55e+04     3.1e+04
sector2            4.441e+04   6057.653      7.331      0.000    3.25e+04    5.63e+04
sector3            6.176e+04   1444.305     42.759      0.000    5.89e+04    6.46e+04
sector4            6.954e+04   1589.868     43.739      0.000    6.64e+04    7.27e+04
sector5             6.37e+04   1852.115     34.392      0.000    6.01e+04    6.73e+04
==============================================================================
Omnibus:                     7430.689   Durbin-Watson:                   1.537
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           275056.898
Skew:                           3.122   Prob(JB):                         0.00
Kurtosis:                      27.768   Cond. No.                         333.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
region_map = {1: "RedRiverDelta", 2: "Northmidlandareas", 3: "CentralCoast",
              4: "Centralhighlands", 5: "MekongRiverDelta"}
for code_r, name in region_map.items():
    df_gdp[name] = (df_gdp["region"] == code_r).astype(int)

region_dummies = list(region_map.values())
X4 = sm.add_constant(df_gdp[["topPCI", "population"] + region_dummies])
model4 = sm.OLS(df_gdp["GDP"], X4).fit()
print(model4.summary())
# MekongRiverDelta ≈ -168 → vùng Mê Kông GDP thấp hơn Đông Nam Bộ ~168 nghìn tỷ
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GDP   R-squared:                       0.929
Model:                            OLS   Adj. R-squared:                  0.920
Method:                 Least Squares   F-statistic:                     103.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           2.75e-29
Time:                        10:37:08   Log-Likelihood:                -350.53
No. Observations:                  63   AIC:                             717.1
Df Residuals:                      55   BIC:                             734.2
Df Model:                           7                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                49.7003     34.620      1.436      0.157     -19.679     119.080
topPCI               57.2488     21.180      2.703      0.009      14.802      99.695
population          140.7084      6.414     21.936      0.000     127.854     153.563
RedRiverDelta      -114.5051     35.248     -3.249      0.002    -185.144     -43.866
Northmidlandareas  -134.4360     35.825     -3.753      0.000    -206.230     -62.642
CentralCoast       -161.3102     34.666     -4.653      0.000    -230.782     -91.839
Centralhighlands   -147.2701     43.009     -3.424      0.001    -233.463     -61.077
MekongRiverDelta   -168.0678     35.254     -4.767      0.000    -238.718     -97.417
==============================================================================
Omnibus:                        5.806   Durbin-Watson:                   1.629
Prob(Omnibus):                  0.055   Jarque-Bera (JB):                5.053
Skew:                          -0.526   Prob(JB):                       0.0799
Kurtosis:                       3.904   Cond. No.                         21.0
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
X_wrong = sm.add_constant(df_wage[["yearsofexperience", "sector"]])
model_wrong = sm.OLS(df_wage["wage"], X_wrong).fit()
print(model_wrong.summary())
# R² ≈ 0.196 – thấp hơn mô hình biến giả (0.223)
# Hệ số sector = 14 361 giả định mỗi mức sector tăng thêm chính xác bằng nhau → sai
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.196
Model:                            OLS   Adj. R-squared:                  0.195
Method:                 Least Squares   F-statistic:                     1230.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:37:08   Log-Likelihood:            -1.2344e+05
No. Observations:               10118   AIC:                         2.469e+05
Df Residuals:                   10115   BIC:                         2.469e+05
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const               3.81e+04   1305.492     29.182      0.000    3.55e+04    4.07e+04
yearsofexperience   189.7031     38.860      4.882      0.000     113.529     265.877
sector             1.436e+04    292.742     49.056      0.000    1.38e+04    1.49e+04
==============================================================================
Omnibus:                     7353.528   Durbin-Watson:                   1.505
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           256115.628
Skew:                           3.095   Prob(JB):                         0.00
Kurtosis:                      26.858   Cond. No.                         71.3
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Không add_constant → statsmodels bỏ hệ số chặn (tương đương noconst của Stata)
X_noconst = df_wage[["yearsofexperience"] + [f"sector{i}" for i in range(6)]]
model_noconst = sm.OLS(df_wage["wage"], X_noconst).fit()
print(model_noconst.summary())
# sector0 ≈ 27 933, sector3 ≈ 89 690 → lương trung bình của từng ngành khi exp = 0
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.223
Model:                            OLS   Adj. R-squared:                  0.222
Method:                 Least Squares   F-statistic:                     483.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:37:08   Log-Likelihood:            -1.2327e+05
No. Observations:               10118   AIC:                         2.466e+05
Df Residuals:                   10111   BIC:                         2.466e+05
Df Model:                           6                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
yearsofexperience   201.6355     38.522      5.234      0.000     126.124     277.147
sector0            2.793e+04   1496.897     18.661      0.000     2.5e+04    3.09e+04
sector1            5.621e+04   1313.490     42.796      0.000    5.36e+04    5.88e+04
sector2            7.234e+04   6035.643     11.986      0.000    6.05e+04    8.42e+04
sector3            8.969e+04   1179.903     76.015      0.000    8.74e+04     9.2e+04
sector4            9.747e+04   1438.065     67.781      0.000    9.47e+04       1e+05
sector5            9.163e+04   1579.091     58.027      0.000    8.85e+04    9.47e+04
==============================================================================
Omnibus:                     7430.689   Durbin-Watson:                   1.537
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           275056.898
Skew:                           3.122   Prob(JB):                         0.00
Kurtosis:                      27.768   Cond. No.                         331.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
df5 = df_wage.copy()

# Tương tác gender × yearsofexperience
df5["gender_x_exp"] = df5["gender"] * df5["yearsofexperience"]

# Tương tác sector × yearsofexperience (sector1–sector5)
for i in range(1, 6):
    df5[f"sec{i}_x_exp"] = df5[f"sector{i}"] * df5["yearsofexperience"]

interact_vars = (
    ["yearsofexperience", "gender", "gender_x_exp"]
    + [f"sector{i}" for i in range(1, 6)]
    + [f"sec{i}_x_exp" for i in range(1, 6)]
)
X5 = sm.add_constant(df5[interact_vars])
model5 = sm.OLS(df5["wage"], X5).fit()
print(model5.summary())
# gender_x_exp ≈ +4.28 (p = 0.954) → tốc độ tăng lương theo kinh nghiệm không khác biệt giữa nữ/nam
# sec5_x_exp  ≈ +583 (p < 0.001) → trong ngành 5, thêm 1 năm KN tăng thêm 583 VNĐ/tháng
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.260
Model:                            OLS   Adj. R-squared:                  0.259
Method:                 Least Squares   F-statistic:                     272.9
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        10:37:08   Log-Likelihood:            -1.2302e+05
No. Observations:               10118   AIC:                         2.461e+05
Df Residuals:                   10104   BIC:                         2.462e+05
Df Model:                          13                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const              3.794e+04   2432.731     15.595      0.000    3.32e+04    4.27e+04
yearsofexperience   110.6326     82.684      1.338      0.181     -51.445     272.711
gender            -2.085e+04   1903.743    -10.952      0.000   -2.46e+04   -1.71e+04
gender_x_exp          4.2828     73.693      0.058      0.954    -140.169     148.735
sector1            2.843e+04   2958.888      9.610      0.000    2.26e+04    3.42e+04
sector2            4.913e+04   1.24e+04      3.975      0.000    2.49e+04    7.34e+04
sector3            5.864e+04   2935.073     19.980      0.000    5.29e+04    6.44e+04
sector4            7.126e+04   3547.302     20.089      0.000    6.43e+04    7.82e+04
sector5            5.905e+04   3635.196     16.243      0.000    5.19e+04    6.62e+04
sec1_x_exp          -48.3765    100.528     -0.481      0.630    -245.430     148.677
sec2_x_exp         -159.3456    439.686     -0.362      0.717   -1021.218     702.527
sec3_x_exp          224.5792    110.473      2.033      0.042       8.031     441.128
sec4_x_exp           28.7912    132.797      0.217      0.828    -231.517     289.100
sec5_x_exp          582.9398    164.941      3.534      0.000     259.623     906.256
==============================================================================
Omnibus:                     7417.372   Durbin-Watson:                   1.460
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           285385.605
Skew:                           3.099   Prob(JB):                         0.00
Kurtosis:                      28.269   Cond. No.                         818.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
import numpy as np

# Lin-Lin: wage ~ gender
df_wage["ln_wage"] = np.log(df_wage["wage"])

Xa = sm.add_constant(df_wage[["gender"]])
model_a = sm.OLS(df_wage["wage"],    Xa).fit()
model_b = sm.OLS(df_wage["ln_wage"], Xa).fit()

print("=== Lin-Lin: wage ~ gender ===")
print(model_a.summary())
# gender ≈ -12 774 → nữ thấp hơn nam ~12 774 VNĐ/tháng

print("\n=== Log-Lin: ln_wage ~ gender ===")
print(model_b.summary())
# gender ≈ -0.177 → nữ thấp hơn nam ~(e^-0.177 - 1)*100 ≈ -16.2%
coef_gender = model_b.params["gender"]
print(f"\nTác động phần trăm: {(np.exp(coef_gender)-1)*100:.2f}%")
Output
=== Lin-Lin: wage ~ gender ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                   wage   R-squared:                       0.014
Model:                            OLS   Adj. R-squared:                  0.014
Method:                 Least Squares   F-statistic:                     142.5
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.26e-32
Time:                        10:37:08   Log-Likelihood:            -1.2447e+05
No. Observations:               10118   AIC:                         2.490e+05
Df Residuals:                   10116   BIC:                         2.490e+05
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       8.026e+04    701.140    114.472      0.000    7.89e+04    8.16e+04
gender     -1.277e+04   1070.180    -11.937      0.000   -1.49e+04   -1.07e+04
==============================================================================
Omnibus:                     6340.073   Durbin-Watson:                   1.209
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           143670.136
Skew:                           2.619   Prob(JB):                         0.00
Kurtosis:                      20.702   Cond. No.                         2.49
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

=== Log-Lin: ln_wage ~ gender ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                ln_wage   R-squared:                       0.011
Model:                            OLS   Adj. R-squared:                  0.010
Method:                 Least Squares   F-statistic:                     107.4
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           4.88e-25
Time:                        10:37:08   Log-Likelihood:                -12693.
No. Observations:               10118   AIC:                         2.539e+04
Df Residuals:                   10116   BIC:                         2.540e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         11.0211      0.011    987.105      0.000      10.999      11.043
gender        -0.1766      0.017    -10.363      0.000      -0.210      -0.143
==============================================================================
Omnibus:                     2278.518   Durbin-Watson:                   1.153
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             5343.366
Skew:                          -1.263   Prob(JB):                         0.00
Kurtosis:                       5.509   Cond. No.                         2.49
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

Tác động phần trăm: -16.19%
df_gdp["ln_GDP"] = np.log(df_gdp["GDP"])

X_ln = sm.add_constant(df_gdp[["topPCI", "population"] + region_dummies])
model_ln = sm.OLS(df_gdp["ln_GDP"], X_ln).fit()
print(model_ln.summary())
# topPCI ≈ +0.443 → tỉnh nhóm PCI cao có GDP cao hơn ~(e^0.443-1)*100 ≈ 55.7%
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                 ln_GDP   R-squared:                       0.803
Model:                            OLS   Adj. R-squared:                  0.777
Method:                 Least Squares   F-statistic:                     31.95
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           3.44e-17
Time:                        10:37:08   Log-Likelihood:                -28.777
No. Observations:                  63   AIC:                             73.55
Df Residuals:                      55   BIC:                             90.70
Df Model:                           7                                         
Covariance Type:            nonrobust                                         
=====================================================================================
                        coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                 4.5555      0.210     21.739      0.000       4.136       4.975
topPCI                0.4425      0.128      3.452      0.001       0.186       0.699
population            0.3676      0.039      9.469      0.000       0.290       0.445
RedRiverDelta        -0.3570      0.213     -1.673      0.100      -0.785       0.071
Northmidlandareas    -1.1624      0.217     -5.360      0.000      -1.597      -0.728
CentralCoast         -0.6461      0.210     -3.079      0.003      -1.067      -0.226
Centralhighlands     -0.8213      0.260     -3.155      0.003      -1.343      -0.300
MekongRiverDelta     -0.7620      0.213     -3.571      0.001      -1.190      -0.334
==============================================================================
Omnibus:                        0.353   Durbin-Watson:                   2.011
Prob(Omnibus):                  0.838   Jarque-Bera (JB):                0.525
Skew:                           0.117   Prob(JB):                        0.769
Kurtosis:                       2.619   Cond. No.                         21.0
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Lọc quan sát có chi phí y tế > 0 (như trong log: healthcare_child>0)
df_dis = df_disaster[df_disaster["healthcare_child"] > 0].copy()
df_dis["ln_healthcare_child"] = np.log(df_dis["healthcare_child"])

disaster_vars = ["HHsize", "agechild", "genderchild", "agehead", "genderhead",
                 "num_eduhead", "jobhead", "land", "storm", "flood"]

print("=== Thống kê mô tả ===")
print(df_dis[["healthcare_child"] + disaster_vars].describe().round(3))
Output
=== Thống kê mô tả ===
       healthcare_child    HHsize  agechild  genderchild   agehead  \
count          2813.000  2813.000  2813.000     2813.000  2813.000   
mean            995.277     4.763     8.389        0.483    45.682   
std            3081.570     1.338     4.204        0.500    12.569   
min               5.000     2.000     0.000        0.000    19.000   
25%             403.000     4.000     6.000        0.000    36.000   
50%             563.000     5.000     9.000        0.000    42.000   
75%             638.000     5.000    12.000        1.000    53.000   
max           82000.000    12.000    15.000        1.000    99.000   

       genderhead  num_eduhead   jobhead      land     storm     flood  
count    2813.000     2813.000  2813.000  2813.000  2813.000  2813.000  
mean        0.172        7.869     0.927    99.196     0.042     0.024  
std         0.377        3.447     0.259    55.068     0.201     0.153  
min         0.000        0.000     0.000    10.000     0.000     0.000  
25%         0.000        5.000     1.000    60.000     0.000     0.000  
50%         0.000        9.000     1.000    84.000     0.000     0.000  
75%         0.000       11.000     1.000   120.000     0.000     0.000  
max         1.000       12.000     1.000   400.000     1.000     1.000  
# OLS: healthcare_child (Lin-Lin)
Xd = sm.add_constant(df_dis[disaster_vars])
model_d1 = sm.OLS(df_dis["healthcare_child"], Xd).fit()
print("=== Lin-Lin: healthcare_child ===")
print(model_d1.summary())
# agechild ≈ -84 → trẻ lớn hơn 1 tuổi thì chi phí y tế thấp hơn ~84 VNĐ/tháng
Output
=== Lin-Lin: healthcare_child ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:       healthcare_child   R-squared:                       0.014
Model:                            OLS   Adj. R-squared:                  0.011
Method:                 Least Squares   F-statistic:                     4.114
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.18e-05
Time:                        10:37:09   Log-Likelihood:                -26568.
No. Observations:                2813   AIC:                         5.316e+04
Df Residuals:                    2802   BIC:                         5.322e+04
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const        1288.7804    497.059      2.593      0.010     314.142    2263.419
HHsize         -5.6074     47.850     -0.117      0.907     -99.432      88.217
agechild      -84.1445     14.022     -6.001      0.000    -111.639     -56.650
genderchild   -75.8823    116.235     -0.653      0.514    -303.797     152.032
agehead         1.0303      5.549      0.186      0.853      -9.851      11.911
genderhead     13.6059    162.716      0.084      0.933    -305.449     332.661
num_eduhead    20.8042     17.952      1.159      0.247     -14.396      56.005
jobhead       160.9751    255.509      0.630      0.529    -340.030     661.980
land            1.2090      1.093      1.106      0.269      -0.934       3.352
storm        -119.5325    302.839     -0.395      0.693    -713.343     474.278
flood         -68.1202    399.656     -0.170      0.865    -851.770     715.530
==============================================================================
Omnibus:                     5612.963   Durbin-Watson:                   1.947
Prob(Omnibus):                  0.000   Jarque-Bera (JB):         14844563.687
Skew:                          15.882   Prob(JB):                         0.00
Kurtosis:                     357.460   Cond. No.                     1.12e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.12e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
# OLS: ln_healthcare_child (Log-Lin)
model_d2 = sm.OLS(df_dis["ln_healthcare_child"], Xd).fit()
print("=== Log-Lin: ln_healthcare_child ===")
print(model_d2.summary())
# num_eduhead ≈ +0.040 → chủ hộ học thêm 1 năm thì chi phí y tế tăng ~4.1%
Output
=== Log-Lin: ln_healthcare_child ===
                             OLS Regression Results                            
===============================================================================
Dep. Variable:     ln_healthcare_child   R-squared:                       0.035
Model:                             OLS   Adj. R-squared:                  0.032
Method:                  Least Squares   F-statistic:                     10.22
Date:                 Wed, 08 Apr 2026   Prob (F-statistic):           4.30e-17
Time:                         10:37:09   Log-Likelihood:                -4018.6
No. Observations:                 2813   AIC:                             8059.
Df Residuals:                     2802   BIC:                             8125.
Df Model:                           10                                         
Covariance Type:             nonrobust                                         
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
const           6.0203      0.164     36.691      0.000       5.699       6.342
HHsize         -0.0372      0.016     -2.354      0.019      -0.068      -0.006
agechild        0.0137      0.005      2.954      0.003       0.005       0.023
genderchild    -0.0651      0.038     -1.696      0.090      -0.140       0.010
agehead         0.0001      0.002      0.082      0.935      -0.003       0.004
genderhead     -0.0027      0.054     -0.049      0.961      -0.108       0.103
num_eduhead     0.0402      0.006      6.784      0.000       0.029       0.052
jobhead        -0.1452      0.084     -1.721      0.085      -0.311       0.020
land            0.0012      0.000      3.296      0.001       0.000       0.002
storm          -0.1324      0.100     -1.324      0.186      -0.328       0.064
flood           0.2514      0.132      1.906      0.057      -0.007       0.510
==============================================================================
Omnibus:                      272.560   Durbin-Watson:                   1.579
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             1998.962
Skew:                          -0.064   Prob(JB):                         0.00
Kurtosis:                       7.128   Cond. No.                     1.12e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.12e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
# Tạo biến giả COVID19
df_gcf["COVID19"]   = (df_gcf["year"] > 2019).astype(int)
df_gcf["GSXCOVID19"] = df_gcf["GS"] * df_gcf["COVID19"]

# Mô hình gốc (không có COVID)
Xgcf0 = sm.add_constant(df_gcf[["GS"]])
model_gcf0 = sm.OLS(df_gcf["GCF"], Xgcf0).fit()
print("=== Mô hình gốc: GCF ~ GS ===")
print(model_gcf0.summary())
Output
=== Mô hình gốc: GCF ~ GS ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GCF   R-squared:                       0.985
Model:                            OLS   Adj. R-squared:                  0.984
Method:                 Least Squares   F-statistic:                     1712.
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           2.93e-25
Time:                        10:37:09   Log-Likelihood:                -85.567
No. Observations:                  28   AIC:                             175.1
Df Residuals:                      26   BIC:                             177.8
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          2.9494      1.587      1.858      0.075      -0.314       6.212
GS             0.9650      0.023     41.377      0.000       0.917       1.013
==============================================================================
Omnibus:                        1.042   Durbin-Watson:                   0.823
Prob(Omnibus):                  0.594   Jarque-Bera (JB):                0.946
Skew:                           0.247   Prob(JB):                        0.623
Kurtosis:                       2.247   Cond. No.                         107.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Mô hình thay đổi đường chặn
Xgcf1 = sm.add_constant(df_gcf[["GS", "COVID19"]])
model_gcf1 = sm.OLS(df_gcf["GCF"], Xgcf1).fit()
print("=== Mô hình dịch chuyển chặn: GCF ~ GS + COVID19 ===")
print(model_gcf1.summary())
# COVID19 ≈ -4.70 (p = 0.267) → không có ý nghĩa thống kê
Output
=== Mô hình dịch chuyển chặn: GCF ~ GS + COVID19 ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GCF   R-squared:                       0.986
Model:                            OLS   Adj. R-squared:                  0.985
Method:                 Least Squares   F-statistic:                     866.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           8.19e-24
Time:                        10:37:09   Log-Likelihood:                -84.863
No. Observations:                  28   AIC:                             175.7
Df Residuals:                      25   BIC:                             179.7
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          2.1755      1.720      1.265      0.217      -1.366       5.717
GS             0.9924      0.034     29.600      0.000       0.923       1.062
COVID19       -4.7022      4.141     -1.135      0.267     -13.232       3.827
==============================================================================
Omnibus:                        0.370   Durbin-Watson:                   0.868
Prob(Omnibus):                  0.831   Jarque-Bera (JB):                0.527
Skew:                          -0.110   Prob(JB):                        0.768
Kurtosis:                       2.365   Cond. No.                         286.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Mô hình thay đổi cả chặn và độ dốc
Xgcf2 = sm.add_constant(df_gcf[["GS", "COVID19", "GSXCOVID19"]])
model_gcf2 = sm.OLS(df_gcf["GCF"], Xgcf2).fit()
print("=== Mô hình dịch chuyển cả chặn lẫn độ dốc: GCF ~ GS + COVID19 + GS×COVID19 ===")
print(model_gcf2.summary())
# GSXCOVID19 ≈ -0.223 (p = 0.286) → độ dốc không thay đổi đáng kể sau COVID
Output
=== Mô hình dịch chuyển cả chặn lẫn độ dốc: GCF ~ GS + COVID19 + GS×COVID19 ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GCF   R-squared:                       0.986
Model:                            OLS   Adj. R-squared:                  0.985
Method:                 Least Squares   F-statistic:                     582.2
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           1.54e-22
Time:                        10:37:09   Log-Likelihood:                -84.186
No. Observations:                  28   AIC:                             176.4
Df Residuals:                      24   BIC:                             181.7
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.9321      1.728      1.118      0.274      -1.633       5.498
GS             0.9986      0.034     29.483      0.000       0.929       1.068
COVID19       23.5569     26.241      0.898      0.378     -30.601      77.715
GSXCOVID19    -0.2232      0.205     -1.090      0.286      -0.646       0.199
==============================================================================
Omnibus:                        0.146   Durbin-Watson:                   0.890
Prob(Omnibus):                  0.930   Jarque-Bera (JB):                0.327
Skew:                          -0.129   Prob(JB):                        0.849
Kurtosis:                       2.538   Cond. No.                     2.06e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.06e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
# Tạo biến giả COVID19 cho dữ liệu theo quý (COVID từ Q1/2020 = qdate > 238)
# qdate dạng Stata quarterly: 2019Q4 = 239, 2020Q1 = 240
df_gdp_unemp["COVID19"] = (df_gdp_unemp["qdate"] > 238).astype(int)

Xu0 = sm.add_constant(df_gdp_unemp[["unemploymentrate"]])
model_u0 = sm.OLS(df_gdp_unemp["GDP"], Xu0).fit()
print("=== GDP ~ unemploymentrate (không có COVID) ===")
print(model_u0.summary())
# unemploymentrate ≈ +255 603 (R² = 0.19) — mô hình thiếu biến
Output
=== GDP ~ unemploymentrate (không có COVID) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GDP   R-squared:                       0.194
Model:                            OLS   Adj. R-squared:                  0.175
Method:                 Least Squares   F-statistic:                     10.34
Date:                Wed, 08 Apr 2026   Prob (F-statistic):            0.00247
Time:                        10:37:09   Log-Likelihood:                -610.75
No. Observations:                  45   AIC:                             1226.
Df Residuals:                      43   BIC:                             1229.
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
====================================================================================
                       coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------
const             4.654e+05   1.86e+05      2.507      0.016    9.11e+04     8.4e+05
unemploymentrate  2.556e+05   7.95e+04      3.216      0.002    9.53e+04    4.16e+05
==============================================================================
Omnibus:                        2.231   Durbin-Watson:                   0.383
Prob(Omnibus):                  0.328   Jarque-Bera (JB):                1.934
Skew:                           0.388   Prob(JB):                        0.380
Kurtosis:                       2.346   Cond. No.                         17.7
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Xu1 = sm.add_constant(df_gdp_unemp[["unemploymentrate", "COVID19"]])
model_u1 = sm.OLS(df_gdp_unemp["GDP"], Xu1).fit()
print("=== GDP ~ unemploymentrate + COVID19 ===")
print(model_u1.summary())
# COVID19 ≈ +343 151 (p < 0.001), R² tăng lên 0.58
# → sau COVID GDP tăng mạnh do gói kích thích kinh tế
Output
=== GDP ~ unemploymentrate + COVID19 ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    GDP   R-squared:                       0.585
Model:                            OLS   Adj. R-squared:                  0.565
Method:                 Least Squares   F-statistic:                     29.56
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           9.72e-09
Time:                        10:37:09   Log-Likelihood:                -595.83
No. Observations:                  45   AIC:                             1198.
Df Residuals:                      42   BIC:                             1203.
Df Model:                           2                                         
Covariance Type:            nonrobust                                         
====================================================================================
                       coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------------
const             8.866e+05   1.51e+05      5.889      0.000    5.83e+05    1.19e+06
unemploymentrate  3.004e+04    6.8e+04      0.442      0.661   -1.07e+05    1.67e+05
COVID19           3.432e+05   5.46e+04      6.285      0.000    2.33e+05    4.53e+05
==============================================================================
Omnibus:                        3.402   Durbin-Watson:                   0.426
Prob(Omnibus):                  0.182   Jarque-Bera (JB):                2.441
Skew:                           0.405   Prob(JB):                        0.295
Kurtosis:                       2.196   Cond. No.                         20.3
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Đọc dữ liệu doanh số ô tô từ file Excel
df_car = pd.read_excel("rawdata/sales.xlsx",
                       sheet_name="car")

# Tạo biến giả quý (quý 1 là nhóm cơ sở)
df_car["D2"] = (df_car["quarter"] == 2).astype(int)
df_car["D3"] = (df_car["quarter"] == 3).astype(int)
df_car["D4"] = (df_car["quarter"] == 4).astype(int)

Xcar = sm.add_constant(df_car[["D2", "D3", "D4"]])
model_car = sm.OLS(df_car["sales"], Xcar).fit()
print(model_car.summary())
# D2 ≈ +9 853 (p=0.222), D3 ≈ +8 649 (p=0.283) → không có ý nghĩa thống kê
# D4 ≈ +33 691 (p<0.001) → Quý 4 doanh số cao hơn quý 1 ~33 691 chiếc
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                  sales   R-squared:                       0.331
Model:                            OLS   Adj. R-squared:                  0.281
Method:                 Least Squares   F-statistic:                     6.603
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           0.000992
Time:                        10:37:10   Log-Likelihood:                -493.00
No. Observations:                  44   AIC:                             994.0
Df Residuals:                      40   BIC:                             1001.
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const       6.001e+04   5621.375     10.676      0.000    4.87e+04    7.14e+04
D2          9853.0000   7949.825      1.239      0.222   -6214.196    2.59e+04
D3          8648.7273   7949.825      1.088      0.283   -7418.469    2.47e+04
D4          3.369e+04   7949.825      4.238      0.000    1.76e+04    4.98e+04
==============================================================================
Omnibus:                        0.524   Durbin-Watson:                   0.684
Prob(Omnibus):                  0.770   Jarque-Bera (JB):                0.312
Skew:                          -0.205   Prob(JB):                        0.855
Kurtosis:                       2.954   Cond. No.                         4.79
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Tính doanh số điều chỉnh mùa vụ
df_car["sales_predict"] = model_car.fittedvalues
df_car["resid"]          = model_car.resid
mean_predict             = df_car["sales_predict"].mean()
df_car["sales_adj"]      = mean_predict + df_car["resid"]

# Tạo cột ngày theo quý
df_car["qdate"] = pd.PeriodIndex(
    df_car["year"].astype(int).astype(str) + "Q"
    + df_car["quarter"].astype(int).astype(str),
    freq="Q"
).to_timestamp()

print(df_car[["qdate", "sales", "sales_predict", "resid", "sales_adj"]].head(10).to_string())
Output
       qdate  sales  sales_predict         resid     sales_adj
0 2014-01-01  30027   60014.454545 -29987.454545  43075.136364
1 2014-04-01  35362   69867.454545 -34505.454545  38557.136364
2 2014-07-01  41320   68663.181818 -27343.181818  45719.409091
3 2014-10-01  51100   93705.272727 -42605.272727  30457.318182
4 2015-01-01  48707   60014.454545 -11307.454545  61755.136364
5 2015-04-01  54785   69867.454545 -15082.454545  57980.136364
6 2015-07-01  59951   68663.181818  -8712.181818  64350.409091
7 2015-10-01  81471   93705.272727 -12234.272727  60828.318182
8 2016-01-01  59714   60014.454545   -300.454545  72762.136364
9 2016-04-01  76172   69867.454545   6304.545455  79367.136364
# Đồ thị: doanh số thực tế vs. doanh số điều chỉnh mùa vụ
fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(df_car["qdate"], df_car["sales"],
        color=palette[2], linewidth=1.5, label="Doanh số thực tế")
ax.plot(df_car["qdate"], df_car["sales_adj"],
        color=palette[0], linewidth=1.5, linestyle="--", label="Doanh số điều chỉnh")
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x:,.0f}"))
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
plt.xticks(rotation=45)
ax.set_ylabel("Doanh số (chiếc)")
ax.set_title("Doanh số xe ô tô – thực tế và điều chỉnh mùa vụ")
ax.legend(loc="upper left")
plt.tight_layout()
OutputOutput of chapter 5, cell 39
import numpy as np
import matplotlib.pyplot as plt

df_mig = df_migration.copy()
df_mig["ln_per_expenditure"] = np.log(df_mig["per_expenditure"])

# Điểm nút = 59 (theo mkspline trong Stata)
KNOT_AGE = 59

# Hồi quy từng đoạn (không điều chỉnh chặn)
dfA = df_mig[df_mig["agehead"] < KNOT_AGE].copy()
dfB = df_mig[df_mig["agehead"] >= KNOT_AGE].copy()

mA = sm.OLS(dfA["ln_per_expenditure"], sm.add_constant(dfA["agehead"])).fit()
mB = sm.OLS(dfB["ln_per_expenditure"], sm.add_constant(dfB["agehead"])).fit()

print(f"=== Dưới {KNOT_AGE} tuổi (n={len(dfA)}) ===")
print(mA.summary())
print(f"\n=== Từ {KNOT_AGE} tuổi trở lên (n={len(dfB)}) ===")
print(mB.summary())
Output
=== Dưới 59 tuổi (n=6687) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.030
Model:                            OLS   Adj. R-squared:                  0.030
Method:                 Least Squares   F-statistic:                     205.7
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           5.80e-46
Time:                        10:37:10   Log-Likelihood:                -6374.6
No. Observations:                6687   AIC:                         1.275e+04
Df Residuals:                    6685   BIC:                         1.277e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          9.4195      0.041    231.266      0.000       9.340       9.499
agehead        0.0128      0.001     14.341      0.000       0.011       0.015
==============================================================================
Omnibus:                      175.221   Durbin-Watson:                   1.218
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              277.371
Skew:                           0.254   Prob(JB):                     5.88e-61
Kurtosis:                       3.859   Cond. No.                         242.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

=== Từ 59 tuổi trở lên (n=2712) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.014
Model:                            OLS   Adj. R-squared:                  0.014
Method:                 Least Squares   F-statistic:                     38.10
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           7.72e-10
Time:                        10:37:10   Log-Likelihood:                -2418.8
No. Observations:                2712   AIC:                             4842.
Df Residuals:                    2710   BIC:                             4853.
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         10.5189      0.093    112.878      0.000      10.336      10.702
agehead       -0.0083      0.001     -6.173      0.000      -0.011      -0.006
==============================================================================
Omnibus:                       54.513   Durbin-Watson:                   1.467
Prob(Omnibus):                  0.000   Jarque-Bera (JB):               91.655
Skew:                           0.167   Prob(JB):                     1.25e-20
Kurtosis:                       3.836   Cond. No.                         571.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Mô hình piecewise có hệ số chặn riêng (hascons)
df_pw = df_mig.copy()
df_pw["age1"] = np.maximum(0, KNOT_AGE - df_pw["agehead"]) * -1  # (agehead - 59), = 0 nếu >=59
df_pw["age1"] = (df_pw["agehead"] - KNOT_AGE).clip(upper=0) * -1
# Viết lại đúng theo Stata
df_pw["age1"] = df_pw["agehead"] - KNOT_AGE
df_pw.loc[df_pw["agehead"] >= KNOT_AGE, "age1"] = 0

df_pw["age2"] = df_pw["agehead"] - KNOT_AGE
df_pw.loc[df_pw["agehead"] < KNOT_AGE, "age2"] = 0

df_pw["int1"] = (df_pw["agehead"] < KNOT_AGE).astype(int)
df_pw["int2"] = (df_pw["agehead"] >= KNOT_AGE).astype(int)

X_pw = df_pw[["int1", "int2", "age1", "age2"]]   # hascons = không add_constant
model_pw = sm.OLS(df_pw["ln_per_expenditure"], X_pw).fit()
print("=== Piecewise với hệ số chặn riêng ===")
print(model_pw.summary())
# int1 ≈ 10.177, int2 ≈ 10.030 → hai đường không liên tục tại knot
# age1 ≈ +0.013 → dưới 59 tuổi, lớn hơn 1 tuổi thì chi tiêu tăng ~1.3%
# age2 ≈ -0.008 → trên 59 tuổi, lớn hơn 1 tuổi thì chi tiêu giảm ~0.8%
Output
=== Piecewise với hệ số chặn riêng ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.027
Model:                            OLS   Adj. R-squared:                  0.026
Method:                 Least Squares   F-statistic:                     85.98
Date:                Wed, 08 Apr 2026   Prob (F-statistic):           7.02e-55
Time:                        10:37:10   Log-Likelihood:                -8800.5
No. Observations:                9399   AIC:                         1.761e+04
Df Residuals:                    9395   BIC:                         1.764e+04
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
int1          10.1765      0.015    693.940      0.000      10.148      10.205
int2          10.0302      0.018    548.214      0.000       9.994      10.066
age1           0.0128      0.001     14.585      0.000       0.011       0.015
age2          -0.0083      0.001     -5.905      0.000      -0.011      -0.006
==============================================================================
Omnibus:                      231.517   Durbin-Watson:                   1.206
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              377.359
Skew:                           0.232   Prob(JB):                     1.14e-82
Kurtosis:                       3.865   Cond. No.                         40.5
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Kiểm định sự khác biệt chặn và độ dốc (lincom tương đương)
from scipy import stats

# Kiểm tra chặn: int2 - int1
diff_intercept = model_pw.params["int2"] - model_pw.params["int1"]
se_diff_int = np.sqrt(
    model_pw.cov_params().loc["int2", "int2"]
    + model_pw.cov_params().loc["int1", "int1"]
    - 2 * model_pw.cov_params().loc["int2", "int1"]
)
t_int = diff_intercept / se_diff_int
p_int = 2 * stats.t.sf(abs(t_int), df=model_pw.df_resid)
print(f"Kiểm định int2 - int1: coef={diff_intercept:.4f}, t={t_int:.2f}, p={p_int:.3f}")
# Tương đương lincom int2 - int1 trong Stata → coef ≈ -0.146, p < 0.001

# Kiểm tra độ dốc: age2 - age1
diff_slope = model_pw.params["age2"] - model_pw.params["age1"]
se_diff_slp = np.sqrt(
    model_pw.cov_params().loc["age2", "age2"]
    + model_pw.cov_params().loc["age1", "age1"]
    - 2 * model_pw.cov_params().loc["age2", "age1"]
)
t_slp = diff_slope / se_diff_slp
p_slp = 2 * stats.t.sf(abs(t_slp), df=model_pw.df_resid)
print(f"Kiểm định age2 - age1: coef={diff_slope:.4f}, t={t_slp:.2f}, p={p_slp:.3f}")
# Tương đương lincom age2 - age1 → coef ≈ -0.021, p < 0.001
Output
Kiểm định int2 - int1: coef=-0.1463, t=-6.24, p=0.000
Kiểm định age2 - age1: coef=-0.0211, t=-12.75, p=0.000
# Đồ thị scatter + đường piecewise
df_pw["yhat"] = model_pw.fittedvalues

fig, ax = plt.subplots(figsize=(9, 5))
ax.scatter(df_pw["agehead"], df_pw["ln_per_expenditure"],
           color=palette[2], alpha=0.2, s=5, label="Quan sát")
ax.plot(df_pw[df_pw["agehead"] < KNOT_AGE].sort_values("agehead")["agehead"],
        df_pw[df_pw["agehead"] < KNOT_AGE].sort_values("agehead")["yhat"],
        color=palette[5], lw=2, label=f"Dưới {KNOT_AGE} tuổi")
ax.plot(df_pw[df_pw["agehead"] >= KNOT_AGE].sort_values("agehead")["agehead"],
        df_pw[df_pw["agehead"] >= KNOT_AGE].sort_values("agehead")["yhat"],
        color=palette[3], lw=2, label=f"Từ {KNOT_AGE} tuổi")
ax.axvline(KNOT_AGE, color=palette[1], linestyle="--", lw=1.2, label=f"Điểm nút = {KNOT_AGE}")
ax.set_xlabel("Tuổi của chủ hộ")
ax.set_ylabel("ln(Chi tiêu bình quân)")
ax.set_title("Hồi quy piecewise: Chi tiêu ~ Tuổi chủ hộ")
ax.legend()
plt.tight_layout()
OutputOutput of chapter 5, cell 44
df_dis2 = df_disaster[df_disaster["healthcare_child"] > 0].copy()
df_dis2["ln_healthcare_child"] = np.log(df_dis2["healthcare_child"])

KNOT_LAND = 205  # mkspline cho knot = 205

# Hồi quy từng đoạn
dfL1 = df_dis2[df_dis2["land"] < KNOT_LAND].copy()
dfL2 = df_dis2[df_dis2["land"] >= KNOT_LAND].copy()

mL1 = sm.OLS(dfL1["ln_healthcare_child"], sm.add_constant(dfL1["land"] - KNOT_LAND)).fit()
mL2 = sm.OLS(dfL2["ln_healthcare_child"], sm.add_constant(dfL2["land"] - KNOT_LAND)).fit()

print(f"=== Dưới {KNOT_LAND} m² (n={len(dfL1)}) ===")
print(mL1.summary())
print(f"\n=== Từ {KNOT_LAND} m² trở lên (n={len(dfL2)}) ===")
print(mL2.summary())
Output
=== Dưới 205 m² (n=2687) ===
                             OLS Regression Results                            
===============================================================================
Dep. Variable:     ln_healthcare_child   R-squared:                       0.004
Model:                             OLS   Adj. R-squared:                  0.003
Method:                  Least Squares   F-statistic:                     10.29
Date:                 Wed, 08 Apr 2026   Prob (F-statistic):            0.00135
Time:                         10:37:11   Log-Likelihood:                -3898.6
No. Observations:                 2687   AIC:                             7801.
Df Residuals:                     2685   BIC:                             7813.
Df Model:                            1                                         
Covariance Type:             nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          6.3979      0.058    110.630      0.000       6.284       6.511
land           0.0015      0.000      3.207      0.001       0.001       0.002
==============================================================================
Omnibus:                      274.890   Durbin-Watson:                   1.563
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             1664.835
Skew:                          -0.275   Prob(JB):                         0.00
Kurtosis:                       6.817   Cond. No.                         351.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

=== Từ 205 m² trở lên (n=126) ===
                             OLS Regression Results                            
===============================================================================
Dep. Variable:     ln_healthcare_child   R-squared:                       0.045
Model:                             OLS   Adj. R-squared:                  0.037
Method:                  Least Squares   F-statistic:                     5.780
Date:                 Wed, 08 Apr 2026   Prob (F-statistic):             0.0177
Time:                         10:37:11   Log-Likelihood:                -155.97
No. Observations:                  126   AIC:                             315.9
Df Residuals:                      124   BIC:                             321.6
Df Model:                            1                                         
Covariance Type:             nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const          6.1945      0.123     50.270      0.000       5.951       6.438
land           0.0040      0.002      2.404      0.018       0.001       0.007
==============================================================================
Omnibus:                       42.672   Durbin-Watson:                   1.670
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              173.467
Skew:                           1.106   Prob(JB):                     2.15e-38
Kurtosis:                       8.306   Cond. No.                         123.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Piecewise có hệ số chặn riêng
df_lnd = df_dis2.copy()
df_lnd["land1"] = df_lnd["land"] - KNOT_LAND
df_lnd.loc[df_lnd["land"] >= KNOT_LAND, "land1"] = 0

df_lnd["land2"] = df_lnd["land"] - KNOT_LAND
df_lnd.loc[df_lnd["land"] < KNOT_LAND, "land2"] = 0

df_lnd["int1"] = (df_lnd["land"] < KNOT_LAND).astype(int)
df_lnd["int2"] = (df_lnd["land"] >= KNOT_LAND).astype(int)

X_lnd = df_lnd[["int1", "int2", "land1", "land2"]]
model_lnd = sm.OLS(df_lnd["ln_healthcare_child"], X_lnd).fit()
print("=== Piecewise: ln_healthcare_child ~ land ===")
print(model_lnd.summary())
# land1 ≈ +0.0015 (p=0.001) → đất < 205 m², thêm 1 m² tăng chi phí y tế ~0.15%
# land2 ≈ +0.0040 (p=0.049) → đất >= 205 m², thêm 1 m² tăng chi phí y tế ~0.40%
Output
=== Piecewise: ln_healthcare_child ~ land ===
                             OLS Regression Results                            
===============================================================================
Dep. Variable:     ln_healthcare_child   R-squared:                       0.007
Model:                             OLS   Adj. R-squared:                  0.006
Method:                  Least Squares   F-statistic:                     6.398
Date:                 Wed, 08 Apr 2026   Prob (F-statistic):           0.000257
Time:                         10:37:11   Log-Likelihood:                -4059.4
No. Observations:                 2813   AIC:                             8127.
Df Residuals:                     2809   BIC:                             8151.
Df Model:                            3                                         
Covariance Type:             nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
int1           6.3979      0.057    111.462      0.000       6.285       6.510
int2           6.1945      0.150     41.243      0.000       5.900       6.489
land1          0.0015      0.000      3.232      0.001       0.001       0.002
land2          0.0040      0.002      1.972      0.049    2.34e-05       0.008
==============================================================================
Omnibus:                      283.721   Durbin-Watson:                   1.554
Prob(Omnibus):                  0.000   Jarque-Bera (JB):             1794.128
Skew:                          -0.242   Prob(JB):                         0.00
Kurtosis:                       6.882   Cond. No.                         919.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Kiểm định độ dốc và chặn (lincom)
df_lnd["yhat"] = model_lnd.fittedvalues

diff_int_l  = model_lnd.params["int2"]  - model_lnd.params["int1"]
diff_slp_l  = model_lnd.params["land2"] - model_lnd.params["land1"]

se_int_l = np.sqrt(
    model_lnd.cov_params().loc["int2", "int2"]
    + model_lnd.cov_params().loc["int1", "int1"]
    - 2 * model_lnd.cov_params().loc["int2", "int1"]
)
se_slp_l = np.sqrt(
    model_lnd.cov_params().loc["land2", "land2"]
    + model_lnd.cov_params().loc["land1", "land1"]
    - 2 * model_lnd.cov_params().loc["land2", "land1"]
)
t_int_l = diff_int_l  / se_int_l
t_slp_l = diff_slp_l  / se_slp_l
p_int_l = 2 * stats.t.sf(abs(t_int_l), df=model_lnd.df_resid)
p_slp_l = 2 * stats.t.sf(abs(t_slp_l), df=model_lnd.df_resid)

print(f"lincom int2 - int1:   coef={diff_int_l:.4f}, t={t_int_l:.2f}, p={p_int_l:.3f}")
print(f"lincom land2 - land1: coef={diff_slp_l:.4f}, t={t_slp_l:.2f}, p={p_slp_l:.3f}")
# Chặn: coef ≈ -0.203 (p=0.206) → hai đường chặn không khác biệt có ý nghĩa
# Độ dốc: coef ≈ +0.002 (p=0.240) → hai độ dốc không khác biệt có ý nghĩa
Output
lincom int2 - int1:   coef=-0.2033, t=-1.26, p=0.206
lincom land2 - land1: coef=0.0024, t=1.18, p=0.240
# Đồ thị scatter + đường piecewise
fig, ax = plt.subplots(figsize=(9, 5))
ax.scatter(df_lnd["land"], df_lnd["ln_healthcare_child"],
           color=palette[2], alpha=0.3, s=5, label="Quan sát")
ax.plot(df_lnd[df_lnd["land"] < KNOT_LAND].sort_values("land")["land"],
        df_lnd[df_lnd["land"] < KNOT_LAND].sort_values("land")["yhat"],
        color=palette[3], lw=2, label=f"Dưới {KNOT_LAND} m²")
ax.plot(df_lnd[df_lnd["land"] >= KNOT_LAND].sort_values("land")["land"],
        df_lnd[df_lnd["land"] >= KNOT_LAND].sort_values("land")["yhat"],
        color=palette[5], lw=2, label=f"Từ {KNOT_LAND} m²")
ax.axvline(KNOT_LAND, color="red", linestyle="--", lw=1.2, label=f"Điểm nút = {KNOT_LAND} m²")
ax.set_xlabel("Diện tích đất ở (m²)")
ax.set_ylabel("ln(Chi phí y tế trẻ em)")
ax.set_title("Hồi quy piecewise: ln_healthcare_child ~ land")
ax.legend()
plt.tight_layout()
OutputOutput of chapter 5, cell 49
# Chapter 5 - Qualitative Variables & Dummy Variables (R version)
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(readxl); library(ggplot2)

# Point data_dir at the repo's data folder (default 'rawdata'; override with env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

dir.create('figures', showWarnings = FALSE)

palette <- c("#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d", "#B3B3B3")

rd <- function(f) as.data.frame(haven::read_dta(file.path(data_dir, f)))

show <- function(m, title = NULL) {
  if (!is.null(title)) cat("\n===", title, "===\n")
  print(summary(m)); cat("N =", nobs(m), "\n")
}

# lincom-style test: b[a] - b[b]
lincom <- function(m, a, b, label) {
  v <- vcov(m); est <- coef(m)[a] - coef(m)[b]
  se <- sqrt(v[a, a] + v[b, b] - 2 * v[a, b]); t <- est / se
  p <- 2 * pt(abs(t), df.residual(m), lower.tail = FALSE)
  cat(sprintf("%s: coef=%.4f, t=%.2f, p=%.3f\n", label, est, t, p))
}

# --- Read data
df_wage      <- rd("wage2020.dta")

df_gdp       <- rd("GDP_population_top.dta")

df_gcf       <- rd("GCF_GS.dta")

df_gdp_unemp <- rd("GDP_unemploymentrate.dta")

df_disaster  <- rd("disaster.dta")

df_migration <- rd("migration_remittances_16_full.dta")

print(rbind(wage=dim(df_wage), gdp=dim(df_gdp), gcf=dim(df_gcf),
            disaster=dim(df_disaster), migration=dim(df_migration)))
Output
           [,1] [,2]
wage      10118   19
gdp          63    7
gcf          28    3
disaster   2813   13
migration  9399   65
# --- 5.1 Qualitative variables
# Example 1: wage ~ yearsofexperience + gender
model1 <- lm(wage ~ yearsofexperience + gender, data = df_wage)

show(model1, "5.1 wage ~ exp + gender")
Output
=== 5.1 wage ~ exp + gender ===

Call:
lm(formula = wage ~ yearsofexperience + gender, data = df_wage)

Residuals:
   Min     1Q Median     3Q    Max 
-85016 -33712  -6179  20652 791249 

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)    
(Intercept)        87322.12    1189.07  73.438  < 2e-16 ***
yearsofexperience   -306.13      41.69  -7.342 2.26e-13 ***
gender            -13248.32    1069.34 -12.389  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 53140 on 10115 degrees of freedom
Multiple R-squared:  0.01912,	Adjusted R-squared:  0.01892 
F-statistic: 98.57 on 2 and 10115 DF,  p-value: < 2.2e-16

N = 10118 
# Example 2: GDP ~ topPCI + population
model2 <- lm(GDP ~ topPCI + population, data = df_gdp)

show(model2, "5.1 GDP ~ topPCI + population")
Output
=== 5.1 GDP ~ topPCI + population ===

Call:
lm(formula = GDP ~ topPCI + population, data = df_gdp)

Residuals:
    Min      1Q  Median      3Q     Max 
-243.32  -35.83   10.72   35.45  298.77 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) -101.274     15.913  -6.364    3e-08 ***
topPCI        61.981     23.393   2.650   0.0103 *  
population   151.959      6.714  22.633   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 78.71 on 60 degrees of freedom
Multiple R-squared:  0.8952,	Adjusted R-squared:  0.8917 
F-statistic: 256.2 on 2 and 60 DF,  p-value: < 2.2e-16

N = 63 
# --- 5.2 Dummy variable trap: k groups -> k-1 dummies
for (s in 0:5) df_wage[[paste0("sector", s)]] <- as.integer(df_wage$sector == s)

model3 <- lm(wage ~ yearsofexperience + sector1 + sector2 + sector3 + sector4 + sector5, data = df_wage)

show(model3, "5.2 wage ~ exp + sector dummies")
Output
=== 5.2 wage ~ exp + sector dummies ===

Call:
lm(formula = wage ~ yearsofexperience + sector1 + sector2 + sector3 + 
    sector4 + sector5, data = df_wage)

Residuals:
    Min      1Q  Median      3Q     Max 
-104166  -25809   -7630   16492  774664 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)       27933.04    1496.90  18.661  < 2e-16 ***
yearsofexperience   201.64      38.52   5.234 1.69e-07 ***
sector1           28278.54    1409.96  20.056  < 2e-16 ***
sector2           44408.28    6057.65   7.331 2.46e-13 ***
sector3           61757.35    1444.30  42.759  < 2e-16 ***
sector4           69539.82    1589.87  43.739  < 2e-16 ***
sector5           63697.13    1852.11  34.392  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47310 on 10111 degrees of freedom
Multiple R-squared:  0.2229,	Adjusted R-squared:  0.2224 
F-statistic: 483.3 on 6 and 10111 DF,  p-value: < 2.2e-16

N = 10118 
region_map <- c(RedRiverDelta = 1, Northmidlandareas = 2, CentralCoast = 3,
                Centralhighlands = 4, MekongRiverDelta = 5)

for (nm in names(region_map)) df_gdp[[nm]] <- as.integer(df_gdp$region == region_map[[nm]])

region_dummies <- names(region_map)

f4 <- reformulate(c("topPCI", "population", region_dummies), "GDP")

model4 <- lm(f4, data = df_gdp)

show(model4, "5.2 GDP ~ topPCI + population + region dummies")
Output
=== 5.2 GDP ~ topPCI + population + region dummies ===

Call:
lm(formula = f4, data = df_gdp)

Residuals:
    Min      1Q  Median      3Q     Max 
-194.51  -39.31   13.28   42.25  165.79 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)         49.700     34.620   1.436 0.156778    
topPCI              57.249     21.180   2.703 0.009125 ** 
population         140.708      6.414  21.936  < 2e-16 ***
RedRiverDelta     -114.505     35.248  -3.249 0.001980 ** 
Northmidlandareas -134.436     35.825  -3.753 0.000423 ***
CentralCoast      -161.310     34.666  -4.653 2.10e-05 ***
Centralhighlands  -147.270     43.009  -3.424 0.001172 ** 
MekongRiverDelta  -168.068     35.254  -4.767 1.41e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 67.55 on 55 degrees of freedom
Multiple R-squared:  0.9292,	Adjusted R-squared:  0.9202 
F-statistic: 103.2 on 7 and 55 DF,  p-value: < 2.2e-16

N = 63 
# --- 5.3 Misusing a categorical variable as continuous
model_wrong <- lm(wage ~ yearsofexperience + sector, data = df_wage)

show(model_wrong, "5.3 wage ~ exp + sector (wrong)")
Output
=== 5.3 wage ~ exp + sector (wrong) ===

Call:
lm(formula = wage ~ yearsofexperience + sector, data = df_wage)

Residuals:
    Min      1Q  Median      3Q     Max 
-106100  -28265   -8140   17177  783509 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)       38096.88    1305.49  29.182  < 2e-16 ***
yearsofexperience   189.70      38.86   4.882 1.07e-06 ***
sector            14360.72     292.74  49.056  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 48130 on 10115 degrees of freedom
Multiple R-squared:  0.1956,	Adjusted R-squared:  0.1954 
F-statistic:  1230 on 2 and 10115 DF,  p-value: < 2.2e-16

N = 10118 
# --- 5.4 No constant: all k dummies
model_noconst <- lm(wage ~ 0 + yearsofexperience + sector0 + sector1 + sector2 + sector3 + sector4 + sector5, data = df_wage)

show(model_noconst, "5.4 no constant")
Output
=== 5.4 no constant ===

Call:
lm(formula = wage ~ 0 + yearsofexperience + sector0 + sector1 + 
    sector2 + sector3 + sector4 + sector5, data = df_wage)

Residuals:
    Min      1Q  Median      3Q     Max 
-104166  -25809   -7630   16492  774664 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
yearsofexperience   201.64      38.52   5.234 1.69e-07 ***
sector0           27933.04    1496.90  18.661  < 2e-16 ***
sector1           56211.58    1313.49  42.796  < 2e-16 ***
sector2           72341.32    6035.64  11.986  < 2e-16 ***
sector3           89690.39    1179.90  76.015  < 2e-16 ***
sector4           97472.86    1438.07  67.781  < 2e-16 ***
sector5           91630.16    1579.09  58.027  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 47310 on 10111 degrees of freedom
Multiple R-squared:  0.7359,	Adjusted R-squared:  0.7357 
F-statistic:  4025 on 7 and 10111 DF,  p-value: < 2.2e-16

N = 10118 
# --- 5.5 Interaction terms
df5 <- df_wage

df5$gender_x_exp <- df5$gender * df5$yearsofexperience

for (i in 1:5) df5[[paste0("sec", i, "_x_exp")]] <- df5[[paste0("sector", i)]] * df5$yearsofexperience

iv <- c("yearsofexperience", "gender", "gender_x_exp", paste0("sector", 1:5), paste0("sec", 1:5, "_x_exp"))

model5 <- lm(reformulate(iv, "wage"), data = df5)

show(model5, "5.5 interactions")
Output
=== 5.5 interactions ===

Call:
lm(formula = reformulate(iv, "wage"), data = df5)

Residuals:
    Min      1Q  Median      3Q     Max 
-110666  -25450   -6001   16353  764033 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        37937.667   2432.731  15.595  < 2e-16 ***
yearsofexperience    110.633     82.684   1.338 0.180923    
gender            -20849.493   1903.743 -10.952  < 2e-16 ***
gender_x_exp           4.283     73.693   0.058 0.953657    
sector1            28434.134   2958.888   9.610  < 2e-16 ***
sector2            49129.910  12358.305   3.975 7.07e-05 ***
sector3            58643.022   2935.073  19.980  < 2e-16 ***
sector4            71260.308   3547.302  20.089  < 2e-16 ***
sector5            59045.299   3635.196  16.243  < 2e-16 ***
sec1_x_exp           -48.376    100.528  -0.481 0.630366    
sec2_x_exp          -159.346    439.686  -0.362 0.717055    
sec3_x_exp           224.579    110.473   2.033 0.042089 *  
sec4_x_exp            28.791    132.797   0.217 0.828364    
sec5_x_exp           582.940    164.941   3.534 0.000411 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 46190 on 10104 degrees of freedom
Multiple R-squared:  0.2599,	Adjusted R-squared:  0.2589 
F-statistic: 272.9 on 13 and 10104 DF,  p-value: < 2.2e-16

N = 10118 
# --- 5.6 Interpreting dummy coefficients
df_wage$ln_wage <- log(df_wage$wage)

model_a <- lm(wage ~ gender, data = df_wage)

model_b <- lm(ln_wage ~ gender, data = df_wage)

show(model_a, "5.6 Lin-Lin: wage ~ gender")
Output
=== 5.6 Lin-Lin: wage ~ gender ===

Call:
lm(formula = wage ~ gender, data = df_wage)

Residuals:
   Min     1Q Median     3Q    Max 
-79761 -34661  -6261  21332 789739 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  80261.2      701.1  114.47   <2e-16 ***
gender      -12774.5     1070.2  -11.94   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 53280 on 10116 degrees of freedom
Multiple R-squared:  0.01389,	Adjusted R-squared:  0.01379 
F-statistic: 142.5 on 1 and 10116 DF,  p-value: < 2.2e-16

N = 10118 
show(model_b, "5.6 Log-Lin: ln_wage ~ gender")
Output
=== 5.6 Log-Lin: ln_wage ~ gender ===

Call:
lm(formula = ln_wage ~ gender, data = df_wage)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.8065 -0.3529  0.1848  0.5264  2.6552 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 11.02107    0.01117  987.11   <2e-16 ***
gender      -0.17660    0.01704  -10.36   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8485 on 10116 degrees of freedom
Multiple R-squared:  0.0105,	Adjusted R-squared:  0.01041 
F-statistic: 107.4 on 1 and 10116 DF,  p-value: < 2.2e-16

N = 10118 
cat(sprintf("Percent effect: %.2f%%\n", (exp(coef(model_b)["gender"]) - 1) * 100))
Output
Percent effect: -16.19%
df_gdp$ln_GDP <- log(df_gdp$GDP)

model_ln <- lm(reformulate(c("topPCI", "population", region_dummies), "ln_GDP"), data = df_gdp)

show(model_ln, "5.6 ln_GDP ~ topPCI + population + regions")
Output
=== 5.6 ln_GDP ~ topPCI + population + regions ===

Call:
lm(formula = reformulate(c("topPCI", "population", region_dummies), 
    "ln_GDP"), data = df_gdp)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.78802 -0.31387  0.03221  0.27552  1.08843 

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        4.55551    0.20955  21.739  < 2e-16 ***
topPCI             0.44252    0.12821   3.452 0.001078 ** 
population         0.36765    0.03883   9.469 3.80e-13 ***
RedRiverDelta     -0.35705    0.21336  -1.673 0.099916 .  
Northmidlandareas -1.16239    0.21685  -5.360 1.69e-06 ***
CentralCoast      -0.64608    0.20983  -3.079 0.003238 ** 
Centralhighlands  -0.82134    0.26034  -3.155 0.002603 ** 
MekongRiverDelta  -0.76196    0.21339  -3.571 0.000749 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4089 on 55 degrees of freedom
Multiple R-squared:  0.8026,	Adjusted R-squared:  0.7775 
F-statistic: 31.95 on 7 and 55 DF,  p-value: < 2.2e-16

N = 63 
# Disaster application
df_dis <- subset(df_disaster, healthcare_child > 0)

df_dis$ln_healthcare_child <- log(df_dis$healthcare_child)

disaster_vars <- c("HHsize", "agechild", "genderchild", "agehead", "genderhead",
                   "num_eduhead", "jobhead", "land", "storm", "flood")

cat("\n=== Descriptive statistics ===\n")
Output
=== Descriptive statistics ===
print(round(sapply(df_dis[c("healthcare_child", disaster_vars)],
  function(x) c(count = length(x), mean = mean(x), sd = sd(x), min = min(x),
                q25 = quantile(x, .25, names = FALSE), median = median(x),
                q75 = quantile(x, .75, names = FALSE), max = max(x))), 3))
Output
       healthcare_child   HHsize agechild genderchild  agehead genderhead
count          2813.000 2813.000 2813.000    2813.000 2813.000   2813.000
mean            995.277    4.763    8.389       0.483   45.682      0.172
sd             3081.570    1.338    4.204       0.500   12.569      0.377
min               5.000    2.000    0.000       0.000   19.000      0.000
q25             403.000    4.000    6.000       0.000   36.000      0.000
median          563.000    5.000    9.000       0.000   42.000      0.000
q75             638.000    5.000   12.000       1.000   53.000      0.000
max           82000.000   12.000   15.000       1.000   99.000      1.000
       num_eduhead  jobhead     land    storm    flood
count     2813.000 2813.000 2813.000 2813.000 2813.000
mean         7.869    0.927   99.196    0.042    0.024
sd           3.447    0.259   55.068    0.201    0.153
min          0.000    0.000   10.000    0.000    0.000
q25          5.000    1.000   60.000    0.000    0.000
median       9.000    1.000   84.000    0.000    0.000
q75         11.000    1.000  120.000    0.000    0.000
max         12.000    1.000  400.000    1.000    1.000
model_d1 <- lm(reformulate(disaster_vars, "healthcare_child"), data = df_dis)

show(model_d1, "5.6 Lin-Lin: healthcare_child")
Output
=== 5.6 Lin-Lin: healthcare_child ===

Call:
lm(formula = reformulate(disaster_vars, "healthcare_child"), 
    data = df_dis)

Residuals:
   Min     1Q Median     3Q    Max 
 -1875   -664   -349    -27  81197 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 1288.780    497.059   2.593  0.00957 ** 
HHsize        -5.607     47.850  -0.117  0.90672    
agechild     -84.144     14.022  -6.001 2.21e-09 ***
genderchild  -75.882    116.235  -0.653  0.51392    
agehead        1.030      5.549   0.186  0.85273    
genderhead    13.606    162.716   0.084  0.93337    
num_eduhead   20.804     17.952   1.159  0.24660    
jobhead      160.975    255.509   0.630  0.52873    
land           1.209      1.093   1.106  0.26872    
storm       -119.532    302.839  -0.395  0.69309    
flood        -68.120    399.656  -0.170  0.86467    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3065 on 2802 degrees of freedom
Multiple R-squared:  0.01447,	Adjusted R-squared:  0.01095 
F-statistic: 4.114 on 10 and 2802 DF,  p-value: 1.177e-05

N = 2813 
model_d2 <- lm(reformulate(disaster_vars, "ln_healthcare_child"), data = df_dis)

show(model_d2, "5.6 Log-Lin: ln_healthcare_child")
Output
=== 5.6 Log-Lin: ln_healthcare_child ===

Call:
lm(formula = reformulate(disaster_vars, "ln_healthcare_child"), 
    data = df_dis)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.7324 -0.2802  0.0263  0.2835  5.5274 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  6.0202797  0.1640823  36.691  < 2e-16 ***
HHsize      -0.0371893  0.0157955  -2.354 0.018620 *  
agechild     0.0136734  0.0046287   2.954 0.003163 ** 
genderchild -0.0650901  0.0383699  -1.696 0.089924 .  
agehead      0.0001500  0.0018318   0.082 0.934753    
genderhead  -0.0026567  0.0537136  -0.049 0.960556    
num_eduhead  0.0402017  0.0059261   6.784 1.42e-11 ***
jobhead     -0.1451570  0.0843451  -1.721 0.085363 .  
land         0.0011893  0.0003608   3.296 0.000991 ***
storm       -0.1323752  0.0999692  -1.324 0.185558    
flood        0.2514067  0.1319290   1.906 0.056802 .  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.012 on 2802 degrees of freedom
Multiple R-squared:  0.03519,	Adjusted R-squared:  0.03174 
F-statistic: 10.22 on 10 and 2802 DF,  p-value: < 2.2e-16

N = 2813 
# --- 5.7 Dummies for structural change
df_gcf$COVID19 <- as.integer(df_gcf$year > 2019)

df_gcf$GSXCOVID19 <- df_gcf$GS * df_gcf$COVID19

show(lm(GCF ~ GS, data = df_gcf), "5.7 GCF ~ GS")
Output
=== 5.7 GCF ~ GS ===

Call:
lm(formula = GCF ~ GS, data = df_gcf)

Residuals:
   Min     1Q Median     3Q    Max 
-8.981 -2.656 -1.119  3.813  9.598 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  2.94937    1.58744   1.858   0.0745 .  
GS           0.96496    0.02332  41.377   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.334 on 26 degrees of freedom
Multiple R-squared:  0.985,	Adjusted R-squared:  0.9845 
F-statistic:  1712 on 1 and 26 DF,  p-value: < 2.2e-16

N = 28 
show(lm(GCF ~ GS + COVID19, data = df_gcf), "5.7 GCF ~ GS + COVID19")
Output
=== 5.7 GCF ~ GS + COVID19 ===

Call:
lm(formula = GCF ~ GS + COVID19, data = df_gcf)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.0822  -1.9600  -0.4758   3.6888   8.2854 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  2.17554    1.71952   1.265    0.217    
GS           0.99245    0.03353  29.600   <2e-16 ***
COVID19     -4.70223    4.14143  -1.135    0.267    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.305 on 25 degrees of freedom
Multiple R-squared:  0.9858,	Adjusted R-squared:  0.9846 
F-statistic: 866.2 on 2 and 25 DF,  p-value: < 2.2e-16

N = 28 
show(lm(GCF ~ GS + COVID19 + GSXCOVID19, data = df_gcf), "5.7 GCF ~ GS + COVID19 + GS x COVID19")
Output
=== 5.7 GCF ~ GS + COVID19 + GS x COVID19 ===

Call:
lm(formula = GCF ~ GS + COVID19 + GSXCOVID19, data = df_gcf)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.2555  -2.0768  -0.3609   3.5968   8.3507 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  1.93207    1.72754   1.118    0.274    
GS           0.99856    0.03387  29.483   <2e-16 ***
COVID19     23.55693   26.24063   0.898    0.378    
GSXCOVID19  -0.22322    0.20470  -1.090    0.286    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.285 on 24 degrees of freedom
Multiple R-squared:  0.9864,	Adjusted R-squared:  0.9848 
F-statistic: 582.2 on 3 and 24 DF,  p-value: < 2.2e-16

N = 28 
# Example 2: quarterly (COVID from 2020Q1: qdate > 238)
df_gdp_unemp$COVID19 <- as.integer(df_gdp_unemp$qdate > 238)

show(lm(GDP ~ unemploymentrate, data = df_gdp_unemp), "5.7 GDP ~ unemploymentrate")
Output
=== 5.7 GDP ~ unemploymentrate ===

Call:
lm(formula = GDP ~ unemploymentrate, data = df_gdp_unemp)

Residuals:
    Min      1Q  Median      3Q     Max 
-299469 -139859  -21770  132944  480586 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)   
(Intercept)        465367     185606   2.507  0.01602 * 
unemploymentrate   255603      79474   3.216  0.00247 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 194100 on 43 degrees of freedom
Multiple R-squared:  0.1939,	Adjusted R-squared:  0.1752 
F-statistic: 10.34 on 1 and 43 DF,  p-value: 0.002468

N = 45 
show(lm(GDP ~ unemploymentrate + COVID19, data = df_gdp_unemp), "5.7 GDP ~ unemploymentrate + COVID19")
Output
=== 5.7 GDP ~ unemploymentrate + COVID19 ===

Call:
lm(formula = GDP ~ unemploymentrate + COVID19, data = df_gdp_unemp)

Residuals:
    Min      1Q  Median      3Q     Max 
-201890 -127077  -16283   96556  299294 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)        886587     150553   5.889 5.74e-07 ***
unemploymentrate    30038      67972   0.442    0.661    
COVID19            343151      54596   6.285 1.54e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 141000 on 42 degrees of freedom
Multiple R-squared:  0.5846,	Adjusted R-squared:  0.5648 
F-statistic: 29.56 on 2 and 42 DF,  p-value: 9.716e-09

N = 45 
# --- 5.8 Seasonal dummies
df_car <- as.data.frame(readxl::read_excel(file.path(data_dir, "sales.xlsx"), sheet = "car"))

df_car$D2 <- as.integer(df_car$quarter == 2)

df_car$D3 <- as.integer(df_car$quarter == 3)

df_car$D4 <- as.integer(df_car$quarter == 4)

model_car <- lm(sales ~ D2 + D3 + D4, data = df_car)

show(model_car, "5.8 sales ~ D2 + D3 + D4")
Output
=== 5.8 sales ~ D2 + D3 + D4 ===

Call:
lm(formula = sales ~ D2 + D3 + D4, data = df_car)

Residuals:
   Min     1Q Median     3Q    Max 
-42605  -9361   -313   9994  41467 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)    60015       5621  10.676 2.83e-13 ***
D2              9853       7950   1.239 0.222421    
D3              8649       7950   1.088 0.283145    
D4             33691       7950   4.238 0.000129 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 18640 on 40 degrees of freedom
Multiple R-squared:  0.3312,	Adjusted R-squared:  0.281 
F-statistic: 6.603 on 3 and 40 DF,  p-value: 0.0009922

N = 44 
df_car$sales_predict <- fitted(model_car)

df_car$resid <- resid(model_car)

df_car$sales_adj <- mean(df_car$sales_predict) + df_car$resid

df_car$qdate <- as.Date(sprintf("%d-%02d-01", as.integer(df_car$year), (as.integer(df_car$quarter) - 1) * 3 + 1))

print(head(df_car[c("qdate", "sales", "sales_predict", "resid", "sales_adj")], 10))
Output
        qdate sales sales_predict       resid sales_adj
1  2014-01-01 30027      60014.45 -29987.4545  43075.14
2  2014-04-01 35362      69867.45 -34505.4545  38557.14
3  2014-07-01 41320      68663.18 -27343.1818  45719.41
4  2014-10-01 51100      93705.27 -42605.2727  30457.32
5  2015-01-01 48707      60014.45 -11307.4545  61755.14
6  2015-04-01 54785      69867.45 -15082.4545  57980.14
7  2015-07-01 59951      68663.18  -8712.1818  64350.41
8  2015-10-01 81471      93705.27 -12234.2727  60828.32
9  2016-01-01 59714      60014.45   -300.4545  72762.14
10 2016-04-01 76172      69867.45   6304.5455  79367.14
p <- ggplot(df_car, aes(qdate)) +
  geom_line(aes(y = sales, colour = "Actual sales")) +
  geom_line(aes(y = sales_adj, colour = "Seasonally adjusted"), linetype = "dashed") +
  scale_colour_manual(values = c("Actual sales" = palette[3], "Seasonally adjusted" = palette[1])) +
  labs(x = NULL, y = "Sales (units)", colour = NULL, title = "Car sales: actual vs seasonally adjusted") +
  theme_minimal() + theme(legend.position = "top")

ggsave("figures/ch5_car_sales.png", p, width = 12, height = 5, dpi = 100)
OutputR output: ch5_car_sales.png
# --- 5.10 Piecewise linear regression
df_mig <- df_migration

df_mig$ln_per_expenditure <- log(df_mig$per_expenditure)

KNOT_AGE <- 59

dfA <- subset(df_mig, agehead < KNOT_AGE)

dfB <- subset(df_mig, agehead >= KNOT_AGE)

mA <- lm(ln_per_expenditure ~ agehead, data = dfA)

mB <- lm(ln_per_expenditure ~ agehead, data = dfB)

show(mA, sprintf("5.10 Below %d (n=%d)", KNOT_AGE, nrow(dfA)))
Output
=== 5.10 Below 59 (n=6687) ===

Call:
lm(formula = ln_per_expenditure ~ agehead, data = dfA)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.33593 -0.40561 -0.00813  0.39564  2.97204 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 9.4194803  0.0407301  231.27   <2e-16 ***
agehead     0.0128308  0.0008947   14.34   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.6278 on 6685 degrees of freedom
Multiple R-squared:  0.02985,	Adjusted R-squared:  0.0297 
F-statistic: 205.7 on 1 and 6685 DF,  p-value: < 2.2e-16

N = 6687 
show(mB, sprintf("5.10 %d and above (n=%d)", KNOT_AGE, nrow(dfB)))
Output
=== 5.10 59 and above (n=2712) ===

Call:
lm(formula = ln_per_expenditure ~ agehead, data = dfB)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.68399 -0.38295 -0.01513  0.36008  2.56295 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept) 10.518868   0.093188 112.878  < 2e-16 ***
agehead     -0.008282   0.001342  -6.173 7.72e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5906 on 2710 degrees of freedom
Multiple R-squared:  0.01386,	Adjusted R-squared:  0.0135 
F-statistic:  38.1 on 1 and 2710 DF,  p-value: 7.722e-10

N = 2712 
df_pw <- df_mig

df_pw$age1 <- ifelse(df_pw$agehead >= KNOT_AGE, 0, df_pw$agehead - KNOT_AGE)

df_pw$age2 <- ifelse(df_pw$agehead < KNOT_AGE, 0, df_pw$agehead - KNOT_AGE)

df_pw$int1 <- as.integer(df_pw$agehead < KNOT_AGE)

df_pw$int2 <- as.integer(df_pw$agehead >= KNOT_AGE)

model_pw <- lm(ln_per_expenditure ~ 0 + int1 + int2 + age1 + age2, data = df_pw)

show(model_pw, "5.10 Piecewise with separate intercepts")
Output
=== 5.10 Piecewise with separate intercepts ===

Call:
lm(formula = ln_per_expenditure ~ 0 + int1 + int2 + age1 + age2, 
    data = df_pw)

Residuals:
     Min       1Q   Median       3Q      Max 
-2.68399 -0.39891 -0.01098  0.38430  2.97204 

Coefficients:
       Estimate Std. Error t value Pr(>|t|)    
int1 10.1764962  0.0146648 693.940  < 2e-16 ***
int2 10.0302278  0.0182962 548.214  < 2e-16 ***
age1  0.0128308  0.0008797  14.585  < 2e-16 ***
age2 -0.0082820  0.0014025  -5.905 3.64e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.6173 on 9395 degrees of freedom
Multiple R-squared:  0.9962,	Adjusted R-squared:  0.9962 
F-statistic: 6.142e+05 on 4 and 9395 DF,  p-value: < 2.2e-16

N = 9399 
lincom(model_pw, "int2", "int1", "int2 - int1")
Output
int2 - int1: coef=-0.1463, t=-6.24, p=0.000
lincom(model_pw, "age2", "age1", "age2 - age1")
Output
age2 - age1: coef=-0.0211, t=-12.75, p=0.000
df_pw$yhat <- fitted(model_pw)

p <- ggplot(df_pw, aes(agehead, ln_per_expenditure)) +
  geom_point(alpha = 0.2, size = 0.5, colour = palette[3]) +
  geom_line(data = subset(df_pw, agehead < KNOT_AGE)[order(subset(df_pw, agehead < KNOT_AGE)$agehead), ], aes(y = yhat), colour = palette[6], linewidth = 1) +
  geom_line(data = subset(df_pw, agehead >= KNOT_AGE)[order(subset(df_pw, agehead >= KNOT_AGE)$agehead), ], aes(y = yhat), colour = palette[4], linewidth = 1) +
  geom_vline(xintercept = KNOT_AGE, colour = palette[2], linetype = "dashed") +
  labs(x = "Age of household head", y = "ln(per capita expenditure)", title = "Piecewise regression: expenditure ~ age") +
  theme_minimal()

ggsave("figures/ch5_piecewise_age.png", p, width = 9, height = 5, dpi = 100)
OutputR output: ch5_piecewise_age.png
# Example 2: ln_healthcare_child ~ land (knot = 205)
df_dis2 <- subset(df_disaster, healthcare_child > 0)

df_dis2$ln_healthcare_child <- log(df_dis2$healthcare_child)

KNOT_LAND <- 205

dfL1 <- subset(df_dis2, land < KNOT_LAND)

dfL2 <- subset(df_dis2, land >= KNOT_LAND)

mL1 <- lm(ln_healthcare_child ~ I(land - KNOT_LAND), data = dfL1)

mL2 <- lm(ln_healthcare_child ~ I(land - KNOT_LAND), data = dfL2)

show(mL1, sprintf("5.10 Below %d m2 (n=%d)", KNOT_LAND, nrow(dfL1)))
Output
=== 5.10 Below 205 m2 (n=2687) ===

Call:
lm(formula = ln_healthcare_child ~ I(land - KNOT_LAND), data = dfL1)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.7807 -0.1998  0.0934  0.2326  5.1237 

Coefficients:
                     Estimate Std. Error t value Pr(>|t|)    
(Intercept)         6.3978530  0.0578311 110.630  < 2e-16 ***
I(land - KNOT_LAND) 0.0015335  0.0004781   3.207  0.00135 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.033 on 2685 degrees of freedom
Multiple R-squared:  0.003817,	Adjusted R-squared:  0.003446 
F-statistic: 10.29 on 1 and 2685 DF,  p-value: 0.001355

N = 2687 
show(mL2, sprintf("5.10 %d m2 and above (n=%d)", KNOT_LAND, nrow(dfL2)))
Output
=== 5.10 205 m2 and above (n=126) ===

Call:
lm(formula = ln_healthcare_child ~ I(land - KNOT_LAND), data = dfL2)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.4211 -0.3326 -0.0421  0.1598  3.4720 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)         6.194508   0.123224  50.270   <2e-16 ***
I(land - KNOT_LAND) 0.003960   0.001647   2.404   0.0177 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.8411 on 124 degrees of freedom
Multiple R-squared:  0.04454,	Adjusted R-squared:  0.03683 
F-statistic:  5.78 on 1 and 124 DF,  p-value: 0.01769

N = 126 
df_lnd <- df_dis2

df_lnd$land1 <- ifelse(df_lnd$land >= KNOT_LAND, 0, df_lnd$land - KNOT_LAND)

df_lnd$land2 <- ifelse(df_lnd$land < KNOT_LAND, 0, df_lnd$land - KNOT_LAND)

df_lnd$int1 <- as.integer(df_lnd$land < KNOT_LAND)

df_lnd$int2 <- as.integer(df_lnd$land >= KNOT_LAND)

model_lnd <- lm(ln_healthcare_child ~ 0 + int1 + int2 + land1 + land2, data = df_lnd)

show(model_lnd, "5.10 Piecewise: ln_healthcare_child ~ land")
Output
=== 5.10 Piecewise: ln_healthcare_child ~ land ===

Call:
lm(formula = ln_healthcare_child ~ 0 + int1 + int2 + land1 + 
    land2, data = df_lnd)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.7807 -0.2097  0.0845  0.2260  5.1237 

Coefficients:
       Estimate Std. Error t value Pr(>|t|)    
int1  6.3978530  0.0573995 111.462  < 2e-16 ***
int2  6.1945076  0.1501959  41.243  < 2e-16 ***
land1 0.0015335  0.0004745   3.232  0.00125 ** 
land2 0.0039602  0.0020078   1.972  0.04866 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.025 on 2809 degrees of freedom
Multiple R-squared:  0.9737,	Adjusted R-squared:  0.9737 
F-statistic: 2.6e+04 on 4 and 2809 DF,  p-value: < 2.2e-16

N = 2813 
lincom(model_lnd, "int2", "int1", "lincom int2 - int1")
Output
lincom int2 - int1: coef=-0.2033, t=-1.26, p=0.206
lincom(model_lnd, "land2", "land1", "lincom land2 - land1")
Output
lincom land2 - land1: coef=0.0024, t=1.18, p=0.240
df_lnd$yhat <- fitted(model_lnd)

p <- ggplot(df_lnd, aes(land, ln_healthcare_child)) +
  geom_point(alpha = 0.3, size = 0.5, colour = palette[3]) +
  geom_line(data = df_lnd[df_lnd$land < KNOT_LAND, ][order(df_lnd$land[df_lnd$land < KNOT_LAND]), ], aes(y = yhat), colour = palette[4], linewidth = 1) +
  geom_line(data = df_lnd[df_lnd$land >= KNOT_LAND, ][order(df_lnd$land[df_lnd$land >= KNOT_LAND]), ], aes(y = yhat), colour = palette[6], linewidth = 1) +
  geom_vline(xintercept = KNOT_LAND, colour = "red", linetype = "dashed") +
  labs(x = "Residential land area (m2)", y = "ln(child healthcare cost)", title = "Piecewise regression: ln_healthcare_child ~ land") +
  theme_minimal()

ggsave("figures/ch5_piecewise_land.png", p, width = 9, height = 5, dpi = 100)
OutputR output: ch5_piecewise_land.png
clear
global link "C:\Stata\data and dofile\1.data\chương 5" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chương 5" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chương 5" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 5                                                 */
/*      File Name:  chapter5.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Qualitative variables                         */  
/*      Input File:     GDP_population.dta                        */
/*                      wage2020.dta                              */  
/*                      disaster.dta                              */
/*                      GCF_GS.dta                                */
/*                      GDP_unemploymentrate                      */
/*                      sales.xlsx                                */
/*                      migration_remittances_16_full.dta         */   
/*      Output File:    chapter5.log                              */  
/******************************************************************/ 

log using chapter5.log, text replace

use "$link\wage2020.dta", clear

reg wage yearsofexperience gender

use "$link\GDP_population.dta",clear

xtile quartile = PCI , nq(4)

gen topPCI =(quartile==4)

//gen topPCI = 1 if quartile==4
//replace  topPCI = 0 if topPCI==.

reg GDP topPCI population

use "$link\wage2020.dta", clear

gen sector1 = (sector==1)

gen sector2 = (sector==2)

gen sector3 = (sector==3)

gen sector4 = (sector==4)

gen sector5 = (sector==5)

gen sector0 = (sector==0)

reg wage yearsofexperience sector1 sector2 sector3 sector4 sector5 

save wage2020.dta, replace

use "$link\GDP_population.dta",clear

xtile quartile = PCI , nq(4)

gen topPCI =(quartile==4)

gen RedRiverDelta= (region == 1)

gen Northmidlandareas= (region == 2)

gen CentralCoast= (region == 3)

gen Centralhighlands= (region == 4)

gen MekongRiverDelta= (region == 5)

reg GDP topPCI population RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta

save GDP_population.dta, replace

use wage2020, clear

reg wage yearsofexperience sector

//Bỏ hệ số chặn

reg wage yearsofexperience sector0 sector1 sector2 sector3 sector4 sector5, noconst

**# Biến tương tác

reg wage yearsofexperience gender i.gender#c.yearsofexperience  sector1 sector2 sector3 sector4 sector5 i.sector1#c.yearsofexperience i.sector2#c.yearsofexperience i.sector3#c.yearsofexperience i.sector4#c.yearsofexperience i.sector5#c.yearsofexperience 

reg wage gender

reg ln_wage gender

use GDP_population.dta,clear

gen ln_GDP=ln(GDP)

reg ln_GDP topPCI population RedRiverDelta Northmidlandareas CentralCoast Centralhighlands MekongRiverDelta

use "$link\disaster.dta" ,clear

sum healthcare_child HHsize agechild genderchild agehead genderhead num_eduhead jobhead land storm flood 

reg healthcare_child HHsize agechild genderchild agehead genderhead num_eduhead jobhead land storm flood

reg ln_healthcare_child HHsize agechild genderchild agehead genderhead num_eduhead jobhead land storm flood

use "$link\GCF_GS.dta",clear

reg GCF GS

gen COVID19=(year>2019)

reg GCF GS COVID19

gen GSXCOVID19= GS*COVID19

reg GCF GS COVID19 GSXCOVID19

use "$link\GDP_unemploymentrate.dta",clear

reg GDP unemploymentrate 

reg GDP unemploymentrate COVID19

clear

import excel "$link\sales.xlsx", sheet("car") firstrow

gen D2=(quarter==2) 

gen D3=(quarter==3) 

gen D4=(quarter==4)
 
reg sales D2 D3 D4

predict sales_predict

predict r,r 

sum sales_predict, detail

gen sales_adj = r(mean) + r

gen qdate = yq(year, quarter) 

format qdate %tq

line sales_adj sales qdate 

graph export Chapter5.9.png, as(png) name("Graph") replace

**# Hồi quy tuyến tính Piecewise

use "$link\migration_remittances_16_full.dta",clear

twoway (scatter ln_per_expenditure agehead) (lfit ln_per_expenditure agehead) (qfit ln_per_expenditure agehead)

graph export Chapter5.9.1.png, as(png) name("Graph") replace

mkspline age0 2 = agehead , displayknots

reg ln_per_expenditure agehead if agehead <59

reg ln_per_expenditure agehead if agehead >=59

//Hồi quy tính đến hệ số chặn

gen age1 = (agehead - 59)

replace age1 = 0 if agehead >= 59

gen age2 = ( agehead - 59) 

replace  age2 = 0 if agehead < 59

gen int1 = 1

replace  int1 = 0 if agehead >= 59

gen int2 = 1

replace  int2 = 0 if agehead < 59

reg ln_per_expenditure age1 if agehead <59

di "y = " _b[_cons] " + " _b[age1] " * age1"

reg ln_per_expenditure age2 if agehead >=59

di "y = " _b[_cons] " + " _b[age2] " * age2"

regress ln_per_expenditure int1 int2 age1 age2 ,hascons

predict yhat

twoway (scatter ln_per_expenditure agehead )(line yhat agehead if agehead <59) (line yhat agehead if agehead >=59)

graph export Chapter5.9.2.png, as(png) name("Graph") replace

use "$link\disaster.dta",clear

mkspline land0 2 = land , displayknots

gen land1 = (land - 205)

replace land1 = 0 if land >= 205

gen land2 = ( land - 205) 

replace  land2 = 0 if land < 205

gen int1 = 1

replace  int1 = 0 if land >= 205

gen int2 = 1

replace  int2 = 0 if land < 205

reg ln_healthcare_child land1 if land <205

di "y = " _b[_cons] " + " _b[land1] " * land1"

reg ln_healthcare_child land2 if land >=205

di "y = " _b[_cons] " + " _b[land2] " * land2"

regress ln_healthcare_child int1 int2 land1 land2 ,hascons

predict yhat

twoway (scatter ln_healthcare_child land)(line yhat land if land <205) (line yhat land if land >=205)

graph export Chapter5.9.3.png, as(png) name("Graph") replace

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: disaster.dta · GCF_GS.dta · GDP_population.dta · GDP_unemploymentrate.dta · migration_remittances_16_full.dta · sales.xlsx · wage2020.dta

Chapter 6 Multinomial and conditional logit

Migration-destination choice: MNL, relative risk ratios, marginal effects, conditional and mixed logit.

df, meta = pyreadstat.read_dta(
    "rawdata/migration.dta",
    encoding="latin1",
)
df.head()
Output
tinh huyen xa diaban hoso m1ama HHsize gender genderhead age agehead agehead2 children_ratio elderly_ratio migration_place urban ethnicity agrland house_structure
0 1 1 7 6 1 1 5.0 0.0 0.0 59.0 59.0 3481.0 0.4 0.0 0.0 1.0 1.0 0.0 1.0
1 1 1 7 6 1 2 5.0 1.0 0.0 45.0 59.0 3481.0 0.4 0.0 0.0 1.0 1.0 0.0 1.0
2 1 1 7 6 1 3 5.0 0.0 0.0 15.0 59.0 3481.0 0.4 0.0 0.0 1.0 1.0 0.0 1.0
3 1 1 7 6 2 1 3.0 0.0 0.0 50.0 50.0 2500.0 0.0 0.0 0.0 1.0 1.0 0.0 1.0
4 1 1 7 6 2 2 3.0 1.0 0.0 50.0 50.0 2500.0 0.0 0.0 0.0 1.0 1.0 0.0 1.0
# Phân phối migration_place
counts = df['migration_place'].value_counts().sort_index()
labels = [
    'Không di cư\n(0)',
    'Di cư HN/HCM\n(1)',
    'Di cư tỉnh khác\n(2)',
    'Di cư nước ngoài\n(3)'
]

fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.bar(labels, counts.values, color=palette[:4], edgecolor='white', linewidth=1.2)

for bar, val in zip(bars, counts.values):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 200,
            f'{val:,}', ha='center', va='bottom', fontsize=10, fontweight='bold')

ax.set_title('Phân phối lựa chọn nơi di cư (migration_place)', fontsize=13, fontweight='bold')
ax.set_ylabel('Số quan sát')
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'{int(x):,}'))
ax.spines[['top','right']].set_visible(False)
plt.tight_layout()
plt.show()

print("\nPhân phối chi tiết:")
print(counts.rename({0:'Không di cư',1:'Di cư HN/HCM',2:'Di cư tỉnh khác',3:'Di cư nước ngoài'}))
OutputOutput of chapter 6, cell 11
Phân phối chi tiết:
migration_place
Không di cư         46697
Di cư HN/HCM          167
Di cư tỉnh khác       154
Di cư nước ngoài       26
Name: count, dtype: int64
from statsmodels.discrete.discrete_model import MNLogit

# Chuẩn bị biến
indep_vars = [
    'gender', 'age', 'HHsize', 'genderhead', 'agehead', 'agehead2',
    'children_ratio', 'elderly_ratio', 'urban', 'ethnicity', 'agrland', 'house_structure'
]

df_model = df.dropna(subset=['migration_place'] + indep_vars).copy()

X = sm.add_constant(df_model[indep_vars])
y = df_model['migration_place']

# Ước lượng mô hình MLM
model = MNLogit(y, X)
result = model.fit(method='newton', maxiter=200, disp=False)

print(result.summary())
Output
                          MNLogit Regression Results                          
==============================================================================
Dep. Variable:        migration_place   No. Observations:                47044
Model:                        MNLogit   Df Residuals:                    47005
Method:                           MLE   Df Model:                           36
Date:                Wed, 08 Apr 2026   Pseudo R-squ.:                  0.1399
Time:                        10:39:14   Log-Likelihood:                -2033.1
converged:                       True   LL-Null:                       -2363.9
Covariance Type:            nonrobust   LLR p-value:                4.280e-116
=====================================================================================
migration_place=1       coef    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
const               -12.0823      2.152     -5.615      0.000     -16.300      -7.865
gender                0.2236      0.159      1.411      0.158      -0.087       0.534
age                  -0.1158      0.009    -13.240      0.000      -0.133      -0.099
HHsize               -0.4381      0.080     -5.501      0.000      -0.594      -0.282
genderhead           -0.2172      0.202     -1.074      0.283      -0.614       0.179
agehead               0.3514      0.079      4.424      0.000       0.196       0.507
agehead2             -0.0028      0.001     -3.769      0.000      -0.004      -0.001
children_ratio        1.2131      0.645      1.880      0.060      -0.051       2.478
elderly_ratio        -0.6129      0.716     -0.857      0.392      -2.015       0.790
urban                -0.0685      0.209     -0.328      0.743      -0.479       0.342
ethnicity             0.8753      0.265      3.306      0.001       0.356       1.394
agrland               0.6549      0.216      3.032      0.002       0.232       1.078
house_structure      -0.5585      0.181     -3.079      0.002      -0.914      -0.203
-------------------------------------------------------------------------------------
migration_place=2       coef    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                -6.9888      1.453     -4.811      0.000      -9.836      -4.142
gender                0.0205      0.164      0.124      0.901      -0.302       0.343
age                  -0.1064      0.009    -11.917      0.000      -0.124      -0.089
HHsize               -0.2985      0.073     -4.092      0.000      -0.441      -0.156
genderhead           -0.4599      0.224     -2.056      0.040      -0.898      -0.022
agehead               0.1640      0.051      3.220      0.001       0.064       0.264
agehead2             -0.0009      0.000     -2.044      0.041      -0.002   -3.67e-05
children_ratio        1.9533      0.623      3.133      0.002       0.731       3.175
elderly_ratio        -1.5449      0.769     -2.010      0.044      -3.052      -0.038
urban                -0.7047      0.248     -2.841      0.004      -1.191      -0.219
ethnicity            -0.0736      0.207     -0.355      0.723      -0.480       0.332
agrland              -0.0316      0.215     -0.147      0.883      -0.453       0.390
house_structure      -0.3484      0.187     -1.859      0.063      -0.716       0.019
-------------------------------------------------------------------------------------
migration_place=3       coef    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
const                 0.2980      2.048      0.146      0.884      -3.716       4.312
gender                0.3170      0.402      0.789      0.430      -0.470       1.104
age                  -0.0975      0.020     -4.822      0.000      -0.137      -0.058
HHsize               -0.6559      0.231     -2.845      0.004      -1.108      -0.204
genderhead            0.2179      0.482      0.452      0.651      -0.727       1.162
agehead              -0.1901      0.074     -2.555      0.011      -0.336      -0.044
agehead2              0.0017      0.001      2.525      0.012       0.000       0.003
children_ratio       -0.0620      1.441     -0.043      0.966      -2.887       2.763
elderly_ratio        -0.3583      1.825     -0.196      0.844      -3.935       3.219
urban                -1.2296      0.793     -1.550      0.121      -2.784       0.325
ethnicity             1.4912      0.769      1.938      0.053      -0.017       2.999
agrland               1.3321      0.670      1.989      0.047       0.019       2.645
house_structure       0.8802      0.404      2.179      0.029       0.088       1.672
=====================================================================================
# Tính RRR = exp(coefficient)
params = result.params   # shape: (n_vars, n_outcomes)
rrr    = np.exp(params)

outcome_labels = ['Di cư HN/HCM (1)', 'Di cư tỉnh khác (2)', 'Di cư nước ngoài (3)']

rrr_df = pd.DataFrame(
    rrr.values,
    index=params.index,
    columns=outcome_labels
)

print("Bảng 6.2 – Tỷ số rủi ro tương đối (RRR)")
print("=" * 65)
print(rrr_df.round(4).to_string())
Output
Bảng 6.2 – Tỷ số rủi ro tương đối (RRR)
=================================================================
                 Di cư HN/HCM (1)  Di cư tỉnh khác (2)  Di cư nước ngoài (3)
const                      0.0000               0.0009                1.3472
gender                     1.2506               1.0207                1.3730
age                        0.8907               0.8991                0.9071
HHsize                     0.6453               0.7419                0.5190
genderhead                 0.8048               0.6313                1.2435
agehead                    1.4210               1.1782                0.8269
agehead2                   0.9972               0.9991                1.0017
children_ratio             3.3640               7.0517                0.9398
elderly_ratio              0.5418               0.2133                0.6989
urban                      0.9338               0.4943                0.2924
ethnicity                  2.3997               0.9291                4.4422
agrland                    1.9250               0.9689                3.7890
house_structure            0.5721               0.7058                2.4114
# Trực quan hóa RRR cho từng biến (outcome 1 – Di cư HN/HCM)
rrr_out1 = rrr_df[outcome_labels[0]].drop('const')

colors = [palette[0] if v >= 1 else palette[1] for v in rrr_out1]

fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(rrr_out1.index, rrr_out1.values, color=colors, edgecolor='white')
ax.axvline(x=1, color='black', linestyle='--', linewidth=1.2, label='RRR = 1')
ax.set_xlabel('Tỷ số rủi ro tương đối (RRR)')
ax.set_title('Hình 6.1 – RRR cho phương án Di cư HN/HCM (Outcome 1)', fontsize=12, fontweight='bold')
ax.legend()
ax.spines[['top','right']].set_visible(False)
plt.tight_layout()
plt.show()
OutputOutput of chapter 6, cell 17
# Hàm dự đoán xác suất theo kiểu Stata "margins, at()"
# Thay thế biến được chỉ định, giữ nguyên các biến còn lại tại giá trị quan sát thực,
# sau đó lấy trung bình xác suất dự đoán trên toàn bộ mẫu.
def predict_margins_at(result, at_dict, df_model, var_order):
    df_at = df_model[var_order].copy()
    for var, val in at_dict.items():
        df_at[var] = val
    # Dùng numpy array thay vì DataFrame để tránh lỗi column index
    X_at = np.column_stack([np.ones(len(df_at)), df_at[var_order].values])
    probs = result.predict(X_at)  # shape (n_obs, n_outcomes)
    return probs.mean(axis=0)

# Quan sát thứ 10 – Stata: margins, at(gender==1 age==22 ... agehead==52 ...)
# agehead2 KHÔNG được chỉ định trong lệnh Stata → giữ tại giá trị quan sát thực
obs10_at = {
    'gender': 1, 'age': 22, 'HHsize': 4, 'genderhead': 0,
    'agehead': 52,
    'children_ratio': 0, 'elderly_ratio': 0.5,
    'urban': 1, 'ethnicity': 1, 'agrland': 0, 'house_structure': 1
}
p10 = predict_margins_at(result, obs10_at, df_model, indep_vars)

print("Dự đoán xác suất – Quan sát thứ 10 (khớp Stata margins, at()):")
outcomes = ['Không di cư (0)', 'Di cư HN/HCM (1)', 'Di cư tỉnh khác (2)', 'Di cư nước ngoài (3)']
for o, p in zip(outcomes, p10):
    print(f"  {o:30s}: {p:.7f}")
Output
Dự đoán xác suất – Quan sát thứ 10 (khớp Stata margins, at()):
  Không di cư (0)               : 0.9406088
  Di cư HN/HCM (1)              : 0.0491226
  Di cư tỉnh khác (2)           : 0.0025345
  Di cư nước ngoài (3)          : 0.0077341
# Bảng 6.3 – Dự đoán xác suất: nữ 18 tuổi, nông thôn
# Stata: margins, at(gender=1 age=18 HHsize=3 genderhead=0 agehead=60 urban=0 ethnicity=1 agrland=1 house_structure=0)
# agehead2, children_ratio, elderly_ratio KHÔNG được chỉ định trong Stata
# → giữ nguyên tại giá trị quan sát thực của từng cá nhân, sau đó lấy trung bình
obs_custom_at = {
    'gender': 1, 'age': 18, 'HHsize': 3, 'genderhead': 0,
    'agehead': 60,
    'urban': 0, 'ethnicity': 1, 'agrland': 1, 'house_structure': 0
}
p_custom = predict_margins_at(result, obs_custom_at, df_model, indep_vars)

print("Bảng 6.3 – Dự đoán xác suất: nữ, 18t, nông thôn, có đất nông nghiệp, nhà không kiên cố")
print("-" * 60)
for o, p in zip(outcomes, p_custom):
    print(f"  {o:30s}: {p:.7f}")
print(f"  {'Tổng':30s}: {sum(p_custom):.7f}")
Output
Bảng 6.3 – Dự đoán xác suất: nữ, 18t, nông thôn, có đất nông nghiệp, nhà không kiên cố
------------------------------------------------------------
  Không di cư (0)               : 0.4019876
  Di cư HN/HCM (1)              : 0.5516351
  Di cư tỉnh khác (2)           : 0.0315241
  Di cư nước ngoài (3)          : 0.0148532
  Tổng                          : 1.0000000
# Trực quan hóa xác suất dự đoán so sánh hai cá nhân
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
short_labels = ['Không\ndi cư', 'Di cư\nHN/HCM', 'Di cư\ntỉnh khác', 'Di cư\nnước ngoài']

for ax, probs, title in zip(
    axes,
    [p10, p_custom],
    ['Quan sát 10: Nữ, 22t, Thành thị', 'Giả định: Nữ, 18t, Nông thôn']
):
    bars = ax.bar(short_labels, probs, color=palette[:4], edgecolor='white')
    for bar, v in zip(bars, probs):
        ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005,
                f'{v:.3f}', ha='center', va='bottom', fontsize=10)
    ax.set_ylim(0, 1.1)
    ax.set_ylabel('Xác suất dự đoán')
    ax.set_title(title, fontsize=11, fontweight='bold')
    ax.spines[['top','right']].set_visible(False)

plt.suptitle('Hình 6.2 – So sánh xác suất dự đoán hai cá nhân', fontsize=13, fontweight='bold', y=1.02)
plt.tight_layout()
plt.show()
OutputOutput of chapter 6, cell 21
# Dự đoán tại giá trị trung bình (atmeans)
means = df_model[indep_vars].mean()
print("Giá trị trung bình các biến:")
for var, val in means.items():
    print(f"  {var:20s}: {val:.6f}")

obs_means = means.to_dict()
p_means = predict_margins_at(result, obs_means, df_model, indep_vars)

print("\nXác suất tại giá trị trung bình (atmeans):")
for o, p in zip(outcomes, p_means):
    print(f"  {o:30s}: {p:.7f}")
Output
Giá trị trung bình các biến:
  gender              : 0.501127
  age                 : 37.860514
  HHsize              : 4.371354
  genderhead          : 0.200684
  agehead             : 50.303864
  agehead2            : 2650.533989
  children_ratio      : 0.201450
  elderly_ratio       : 0.066368
  urban               : 0.285116
  ethnicity           : 0.795000
  agrland             : 0.682404
  house_structure     : 0.367677

Xác suất tại giá trị trung bình (atmeans):
  Không di cư (0)               : 0.9974981
  Di cư HN/HCM (1)              : 0.0010741
  Di cư tỉnh khác (2)           : 0.0013079
  Di cư nước ngoài (3)          : 0.0001200
# Tính marginal effects tại giá trị trung bình
margeff = result.get_margeff(at='mean')
print(margeff.summary())
Output
       MNLogit Marginal Effects      
=====================================
Dep. Variable:        migration_place
Method:                          dydx
At:                              mean
=====================================================================================
migration_place=0      dy/dx    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
gender               -0.0003      0.000     -1.081      0.280      -0.001       0.000
age                   0.0003   1.99e-05     13.810      0.000       0.000       0.000
HHsize                0.0009      0.000      6.370      0.000       0.001       0.001
genderhead            0.0008      0.000      2.147      0.032    7.04e-05       0.002
agehead              -0.0006      0.000     -4.929      0.000      -0.001      -0.000
agehead2           3.916e-06   1.01e-06      3.862      0.000    1.93e-06     5.9e-06
children_ratio       -0.0038      0.001     -3.522      0.000      -0.006      -0.002
elderly_ratio         0.0027      0.001      2.068      0.039       0.000       0.005
urban                 0.0011      0.000      2.740      0.006       0.000       0.002
ethnicity            -0.0010      0.000     -2.434      0.015      -0.002      -0.000
agrland              -0.0008      0.000     -2.129      0.033      -0.002   -6.51e-05
house_structure       0.0009      0.000      2.867      0.004       0.000       0.002
-------------------------------------------------------------------------------------
migration_place=1      dy/dx    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
gender                0.0002      0.000      1.391      0.164   -9.82e-05       0.001
age                  -0.0001   1.39e-05     -8.913      0.000      -0.000   -9.68e-05
HHsize               -0.0005      0.000     -4.681      0.000      -0.001      -0.000
genderhead           -0.0002      0.000     -1.064      0.288      -0.001       0.000
agehead               0.0004   9.11e-05      4.135      0.000       0.000       0.001
agehead2          -2.962e-06   8.24e-07     -3.596      0.000   -4.58e-06   -1.35e-06
children_ratio        0.0013      0.001      1.868      0.062   -6.39e-05       0.003
elderly_ratio        -0.0007      0.001     -0.847      0.397      -0.002       0.001
urban             -7.237e-05      0.000     -0.322      0.747      -0.001       0.000
ethnicity             0.0009      0.000      3.124      0.002       0.000       0.002
agrland               0.0007      0.000      2.873      0.004       0.000       0.001
house_structure      -0.0006      0.000     -2.893      0.004      -0.001      -0.000
-------------------------------------------------------------------------------------
migration_place=2      dy/dx    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
gender             2.635e-05      0.000      0.123      0.902      -0.000       0.000
age                  -0.0001   1.36e-05    -10.171      0.000      -0.000      -0.000
HHsize               -0.0004      0.000     -3.818      0.000      -0.001      -0.000
genderhead           -0.0006      0.000     -2.018      0.044      -0.001   -1.73e-05
agehead               0.0002    6.9e-05      3.099      0.002    7.85e-05       0.000
agehead2          -1.161e-06   5.77e-07     -2.014      0.044   -2.29e-06    -3.1e-08
children_ratio        0.0025      0.001      3.121      0.002       0.001       0.004
elderly_ratio        -0.0020      0.001     -1.958      0.050      -0.004    1.79e-06
urban                -0.0009      0.000     -2.756      0.006      -0.002      -0.000
ethnicity         -9.754e-05      0.000     -0.360      0.719      -0.001       0.000
agrland            -4.24e-05      0.000     -0.151      0.880      -0.001       0.001
house_structure      -0.0005      0.000     -1.824      0.068      -0.001    3.38e-05
-------------------------------------------------------------------------------------
migration_place=3      dy/dx    std err          z      P>|z|      [0.025      0.975]
-------------------------------------------------------------------------------------
gender             3.799e-05   4.95e-05      0.768      0.442   -5.89e-05       0.000
age               -1.167e-05   4.03e-06     -2.897      0.004   -1.96e-05   -3.77e-06
HHsize            -7.857e-05   3.36e-05     -2.338      0.019      -0.000   -1.27e-05
genderhead         2.624e-05   5.96e-05      0.441      0.660   -9.05e-05       0.000
agehead           -2.287e-05   1.27e-05     -1.802      0.072   -4.78e-05    2.01e-06
agehead2           2.071e-07   1.15e-07      1.800      0.072   -1.84e-08    4.33e-07
children_ratio    -7.905e-06      0.000     -0.046      0.964      -0.000       0.000
elderly_ratio     -4.265e-05      0.000     -0.194      0.846      -0.000       0.000
urban                -0.0001      0.000     -1.471      0.141      -0.000     4.9e-05
ethnicity             0.0002      0.000      1.692      0.091   -2.83e-05       0.000
agrland               0.0002   9.24e-05      1.729      0.084   -2.13e-05       0.000
house_structure       0.0001   6.04e-05      1.751      0.080   -1.26e-05       0.000
=====================================================================================
# Tổng hợp marginal effects theo từng outcome – tương đương Bảng 6.4
me_df = margeff.margeff
me_se = margeff.margeff_se
me_z  = margeff.tvalues
me_p  = margeff.pvalues

var_names = indep_vars
n_outcomes = me_df.shape[1] if me_df.ndim > 1 else 1

print("Bảng 6.4 – Hiệu ứng biên (Marginal Effects tại giá trị trung bình)")
print("=" * 80)

for j in range(me_df.shape[1]):
    print(f"\n  Kết quả {j} – {outcomes[j]}:")
    print(f"  {'Biến':20s}  {'dy/dx':>12s}  {'Std.Err':>10s}  {'z':>8s}  {'P>|z|':>8s}")
    print("  " + "-" * 65)
    for i, var in enumerate(var_names):
        print(f"  {var:20s}  {me_df[i,j]:12.7f}  {me_se[i,j]:10.7f}  {me_z[i,j]:8.2f}  {me_p[i,j]:8.4f}")
Output
Bảng 6.4 – Hiệu ứng biên (Marginal Effects tại giá trị trung bình)
================================================================================

  Kết quả 0 – Không di cư (0):
  Biến                         dy/dx     Std.Err         z     P>|z|
  -----------------------------------------------------------------
  gender                  -0.0003042   0.0002814     -1.08    0.2796
  age                      0.0002745   0.0000199     13.81    0.0000
  HHsize                   0.0009372   0.0001471      6.37    0.0000
  genderhead               0.0008066   0.0003756      2.15    0.0318
  agehead                 -0.0005676   0.0001152     -4.93    0.0000
  agehead2                 0.0000039   0.0000010      3.86    0.0001
  children_ratio          -0.0038406   0.0010906     -3.52    0.0004
  elderly_ratio            0.0027151   0.0013131      2.07    0.0387
  urban                    0.0011399   0.0004159      2.74    0.0061
  ethnicity               -0.0010203   0.0004193     -2.43    0.0149
  agrland                 -0.0008199   0.0003851     -2.13    0.0333
  house_structure          0.0009476   0.0003305      2.87    0.0041

  Kết quả 1 – Di cư HN/HCM (1):
  Biến                         dy/dx     Std.Err         z     P>|z|
  -----------------------------------------------------------------
  gender                   0.0002399   0.0001725      1.39    0.1644
  age                     -0.0001240   0.0000139     -8.91    0.0000
  HHsize                  -0.0004695   0.0001003     -4.68    0.0000
  genderhead              -0.0002324   0.0002185     -1.06    0.2875
  agehead                  0.0003768   0.0000911      4.13    0.0000
  agehead2                -0.0000030   0.0000008     -3.60    0.0003
  children_ratio           0.0012989   0.0006953      1.87    0.0618
  elderly_ratio           -0.0006554   0.0007737     -0.85    0.3969
  urban                   -0.0000724   0.0002247     -0.32    0.7474
  ethnicity                0.0009391   0.0003006      3.12    0.0018
  agrland                  0.0007026   0.0002446      2.87    0.0041
  house_structure         -0.0005988   0.0002070     -2.89    0.0038

  Kết quả 2 – Di cư tỉnh khác (2):
  Biến                         dy/dx     Std.Err         z     P>|z|
  -----------------------------------------------------------------
  gender                   0.0000264   0.0002149      0.12    0.9024
  age                     -0.0001388   0.0000136    -10.17    0.0000
  HHsize                  -0.0003892   0.0001019     -3.82    0.0001
  genderhead              -0.0006004   0.0002975     -2.02    0.0436
  agehead                  0.0002137   0.0000690      3.10    0.0019
  agehead2                -0.0000012   0.0000006     -2.01    0.0440
  children_ratio           0.0025496   0.0008169      3.12    0.0018
  elderly_ratio           -0.0020170   0.0010300     -1.96    0.0502
  urban                   -0.0009202   0.0003339     -2.76    0.0059
  ethnicity               -0.0000975   0.0002707     -0.36    0.7186
  agrland                 -0.0000424   0.0002810     -0.15    0.8801
  house_structure         -0.0004544   0.0002491     -1.82    0.0681

  Kết quả 3 – Di cư nước ngoài (3):
  Biến                         dy/dx     Std.Err         z     P>|z|
  -----------------------------------------------------------------
  gender                   0.0000380   0.0000495      0.77    0.4424
  age                     -0.0000117   0.0000040     -2.90    0.0038
  HHsize                  -0.0000786   0.0000336     -2.34    0.0194
  genderhead               0.0000262   0.0000596      0.44    0.6596
  agehead                 -0.0000229   0.0000127     -1.80    0.0716
  agehead2                 0.0000002   0.0000001      1.80    0.0719
  children_ratio          -0.0000079   0.0001735     -0.05    0.9637
  elderly_ratio           -0.0000427   0.0002202     -0.19    0.8464
  urban                   -0.0001474   0.0001002     -1.47    0.1413
  ethnicity                0.0001788   0.0001056      1.69    0.0906
  agrland                  0.0001597   0.0000924      1.73    0.0838
  house_structure          0.0001057   0.0000604      1.75    0.0799
# Trực quan hóa Marginal Effects – Outcome 1 (Di cư HN/HCM)
me_out1 = me_df[:, 0]
se_out1 = me_se[:, 0]
colors_me = [palette[0] if v >= 0 else palette[1] for v in me_out1]

fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.barh(var_names, me_out1, xerr=1.96*se_out1,
               color=colors_me, edgecolor='white',
               error_kw=dict(ecolor='gray', lw=1.2, capsize=3))
ax.axvline(x=0, color='black', linestyle='--', linewidth=1)
ax.set_xlabel('Hiệu ứng biên (dy/dx)')
ax.set_title('Hình 6.3 – Marginal Effects: Di cư HN/HCM (Outcome 1)', fontsize=12, fontweight='bold')
ax.spines[['top','right']].set_visible(False)
plt.tight_layout()
plt.show()
OutputOutput of chapter 6, cell 27
# So sánh Marginal Effects ba outcomes cùng lúc
fig, axes = plt.subplots(1, 3, figsize=(15, 6), sharey=True)

for j, ax in enumerate(axes):
    me_j  = me_df[:, j]
    se_j  = me_se[:, j]
    cols  = [palette[0] if v >= 0 else palette[1] for v in me_j]
    ax.barh(var_names, me_j, xerr=1.96*se_j,
            color=cols, edgecolor='white',
            error_kw=dict(ecolor='gray', lw=1, capsize=2))
    ax.axvline(0, color='black', linestyle='--', linewidth=0.8)
    ax.set_title(outcome_labels[j], fontsize=10, fontweight='bold')
    ax.set_xlabel('dy/dx')
    ax.spines[['top','right']].set_visible(False)

plt.suptitle('Hình 6.4 – So sánh Marginal Effects ba phương án di cư', fontsize=12, fontweight='bold', y=1.01)
plt.tight_layout()
plt.show()
OutputOutput of chapter 6, cell 28
def stars(p):
    if p < 0.001: return '***'
    elif p < 0.01: return '**'
    elif p < 0.05: return '*'
    else: return ''

rows = []
for i, var in enumerate(var_names):
    row = {'Biến': var}
    for j, label in enumerate(['Kết quả 1', 'Kết quả 2', 'Kết quả 3']):
        coef = me_df[i, j+1]   # j+1: outcomes 1,2,3 (bỏ qua cột 0 = outcome 0)
        pval = me_p[i, j+1]
        row[label] = f"{coef:.6f}{stars(pval)}"
    rows.append(row)

table = pd.DataFrame(rows).set_index('Biến')
print("Bảng 6.4 – Tổng hợp Hiệu ứng biên từ mô hình MLM")
print("(*** p<0.001, ** p<0.01, * p<0.05)")
print("=" * 65)
print(table.to_string())
Output
Bảng 6.4 – Tổng hợp Hiệu ứng biên từ mô hình MLM
(*** p<0.001, ** p<0.01, * p<0.05)
=================================================================
                    Kết quả 1     Kết quả 2    Kết quả 3
Biến                                                    
gender               0.000240      0.000026     0.000038
age              -0.000124***  -0.000139***  -0.000012**
HHsize           -0.000469***  -0.000389***   -0.000079*
genderhead          -0.000232    -0.000600*     0.000026
agehead           0.000377***    0.000214**    -0.000023
agehead2         -0.000003***    -0.000001*     0.000000
children_ratio       0.001299    0.002550**    -0.000008
elderly_ratio       -0.000655     -0.002017    -0.000043
urban               -0.000072   -0.000920**    -0.000147
ethnicity          0.000939**     -0.000098     0.000179
agrland            0.000703**     -0.000042     0.000160
house_structure   -0.000599**     -0.000454     0.000106
# Đọc dữ liệu CLM (TableF18-2.csv)
df_clm = pd.read_csv(
    "rawdata/TableF18-2.csv"
)
print(f"Shape: {df_clm.shape}")
print(df_clm.head(8))
Output
Shape: (840, 7)
   MODE  TTME  INVC  INVT  GC  HINC  PSIZE
0     0    69    59   100  70    35      1
1     0    34    31   372  71    35      1
2     0    35    25   417  70    35      1
3     1     0    10   180  30    35      1
4     0    64    58    68  68    30      2
5     0    44    31   354  84    30      2
6     0    53    25   399  85    30      2
7     1     0    11   255  50    30      2
# Tạo các biến cần thiết
# Mỗi cá nhân có 4 dòng (4 phương tiện)
df_clm['id']    = ((df_clm.index) // 4) + 1
df_clm['order'] = (df_clm.index % 4) + 1

# Biến giả phương tiện (ô tô = nhóm tham chiếu, order=4)
df_clm['air']   = (df_clm['order'] == 1).astype(int)
df_clm['train'] = (df_clm['order'] == 2).astype(int)
df_clm['bus']   = (df_clm['order'] == 3).astype(int)

print("Phân phối biến mode (lựa chọn thực tế):")
print(df_clm.groupby('order')['MODE'].sum().rename({1:'air',2:'train',3:'bus',4:'car'}))
print(f"\nTổng số quan sát: {len(df_clm)}, Số cá nhân: {df_clm['id'].nunique()}")
df_clm.head(8)
Output
Phân phối biến mode (lựa chọn thực tế):
order
air      58
train    63
bus      30
car      59
Name: MODE, dtype: int64

Tổng số quan sát: 840, Số cá nhân: 210
MODE TTME INVC INVT GC HINC PSIZE id order air train bus
0 0 69 59 100 70 35 1 1 1 1 0 0
1 0 34 31 372 71 35 1 1 2 0 1 0
2 0 35 25 417 70 35 1 1 3 0 0 1
3 1 0 10 180 30 35 1 1 4 0 0 0
4 0 64 58 68 68 30 2 2 1 1 0 0
5 0 44 31 354 84 30 2 2 2 0 1 0
6 0 53 25 399 85 30 2 2 3 0 0 1
7 1 0 11 255 50 30 2 2 4 0 0 0
from statsmodels.discrete.conditional_models import ConditionalLogit
import pandas as pd
import numpy as np

clm_vars = ['TTME', 'INVC', 'INVT', 'GC', 'air', 'train', 'bus']

X_clm   = df_clm[clm_vars].astype(float)
y_clm   = df_clm['MODE'].astype(int)
groups  = df_clm['id'].astype(int)

clm_model  = ConditionalLogit(y_clm, X_clm, groups=groups)
clm_result = clm_model.fit(method='newton', maxiter=300, disp=False)

# ── Pseudo R² via manual null log-likelihood ──────────────────────────
n_alts_per_obs = df_clm.groupby('id')['MODE'].count()   # alts per person
ll_null = np.sum(np.log(1.0 / n_alts_per_obs))          # one term per person

pseudo_r2 = 1 - (clm_result.llf / ll_null)              # McFadden Pseudo-R²

# ── Summary ───────────────────────────────────────────────────────────
params = clm_result.params
se     = clm_result.bse
z      = params / se
pvals  = clm_result.pvalues
lo     = params - 1.96 * se
hi     = params + 1.96 * se

summary_df = pd.DataFrame({
    'Coef.'   : params,
    'Std.Err.': se,
    'z'       : z,
    'P>|z|'   : pvals,
    '[0.025'  : lo,
    '0.975]'  : hi
}, index=clm_vars)

print("Bảng 6.5 – Hồi quy CLM: Lựa chọn phương tiện di chuyển")
print("=" * 65)
print(summary_df.round(4).to_string())
print(f"\nLog likelihood : {clm_result.llf:.4f}")
print(f"Null LL        : {ll_null:.4f}")
print(f"Pseudo R²      : {pseudo_r2:.4f}")

k_clm  = len(clm_result.params)
aic    = -2 * clm_result.llf + 2 * k_clm
print(f"AIC            : {aic:.4f}")
Output
Bảng 6.5 – Hồi quy CLM: Lựa chọn phương tiện di chuyển
=================================================================
        Coef.  Std.Err.       z   P>|z|  [0.025  0.975]
TTME  -0.1036    0.0109 -9.4760  0.0000 -0.1251 -0.0822
INVC  -0.0849    0.0194 -4.3819  0.0000 -0.1229 -0.0469
INVT  -0.0133    0.0025 -5.2969  0.0000 -0.0183 -0.0084
GC     0.0693    0.0174  3.9749  0.0001  0.0351  0.1035
air    5.2047    0.9052  5.7497  0.0000  3.4305  6.9790
train  4.3606    0.5107  8.5391  0.0000  3.3597  5.3615
bus    3.7632    0.5063  7.4334  0.0000  2.7710  4.7555

Log likelihood : -184.5067
Null LL        : -291.1218
Pseudo R²      : 0.3662
AIC            : 383.0134
# Bảng 6.6 – CLM với Odds Ratio
params_clm = clm_result.params
se_clm     = clm_result.bse
pvals_clm  = clm_result.pvalues

or_clm  = np.exp(params_clm)
or_lo   = np.exp(params_clm - 1.96 * se_clm)
or_hi   = np.exp(params_clm + 1.96 * se_clm)

or_df = pd.DataFrame({
    'Odds Ratio': or_clm.round(4),
    'Std.Err.'  : se_clm.round(4),
    'z'         : (params_clm / se_clm).round(2),
    'P>|z|'     : pvals_clm.round(3),
    '[0.025'    : or_lo.round(4),
    '0.975]'    : or_hi.round(4),
}, index=clm_vars)

print("Bảng 6.6 – CLM theo tỷ số Odds")
print("=" * 70)
print(or_df.to_string())
print()
print("Diễn giải ví dụ:")
print(f"  ttme (OR={or_clm['TTME']:.4f}): Mỗi phút chờ thêm → xác suất chọn phương tiện đó giảm {(1-or_clm['TTME'])*100:.2f}%")
print(f"  invc (OR={or_clm['INVC']:.4f}): Mỗi đơn vị chi phí thêm → xác suất giảm {(1-or_clm['INVC'])*100:.2f}%")
print(f"  gc   (OR={or_clm['GC']:.4f}): Mỗi đơn vị gc thêm → xác suất tăng {(or_clm['GC']-1)*100:.2f}%")
Output
Bảng 6.6 – CLM theo tỷ số Odds
======================================================================
       Odds Ratio  Std.Err.     z  P>|z|   [0.025     0.975]
TTME       0.9015    0.0109 -9.48    0.0   0.8824     0.9211
INVC       0.9186    0.0194 -4.38    0.0   0.8843     0.9541
INVT       0.9868    0.0025 -5.30    0.0   0.9819     0.9916
GC         1.0718    0.0174  3.97    0.0   1.0358     1.1090
air      182.1340    0.9052  5.75    0.0  30.8929  1073.8015
train     78.3045    0.5107  8.54    0.0  28.7806   213.0461
bus       43.0876    0.5063  7.43    0.0  15.9741   116.2221

Diễn giải ví dụ:
  ttme (OR=0.9015): Mỗi phút chờ thêm → xác suất chọn phương tiện đó giảm 9.85%
  invc (OR=0.9186): Mỗi đơn vị chi phí thêm → xác suất giảm 8.14%
  gc   (OR=1.0718): Mỗi đơn vị gc thêm → xác suất tăng 7.18%
params = clm_result.params
linear_predictor = np.dot(X_clm, params)
df_clm['utility'] = linear_predictor
df_clm['exp_utility'] = np.exp(df_clm['utility'])
sum_exp_utility_per_id = df_clm.groupby('id')['exp_utility'].transform('sum')
pred_clm = df_clm['exp_utility'] / sum_exp_utility_per_id
df_clm['pred'] = pred_clm
obs1 = df_clm[df_clm['id'] == 1][['id', 'order', 'MODE', 'pred']].copy()
obs1['phương tiện'] = obs1['order'].map({1:'Máy bay',2:'Tàu hỏa',3:'Xe buýt',4:'Ô tô'})
print("Xác suất dự đoán cho cá nhân 1:")
print(obs1[['phương tiện', 'MODE', 'pred']].to_string(index=False))
print()
print("→ Ô tô có xác suất cao nhất (0.545) và thực tế người này chọn ô tô (MODE=1).")
Output
Xác suất dự đoán cho cá nhân 1:
phương tiện  MODE     pred
    Máy bay     0 0.056297
    Tàu hỏa     0 0.280133
    Xe buýt     0 0.118462
       Ô tô     1 0.545108

→ Ô tô có xác suất cao nhất (0.545) và thực tế người này chọn ô tô (MODE=1).
# ======================
# 1. Tạo biến tương tác
# ======================
df_clm['AIRXHINC']   = df_clm['air']   * df_clm['HINC']
df_clm['TRAINXHINC'] = df_clm['train'] * df_clm['HINC']
df_clm['BUSXHINC']   = df_clm['bus']   * df_clm['HINC']

df_clm['AIRXPSIZE']   = df_clm['air']   * df_clm['PSIZE']
df_clm['TRAINXPSIZE'] = df_clm['train'] * df_clm['PSIZE']
df_clm['BUSXPSIZE']   = df_clm['bus']   * df_clm['PSIZE']

# ======================
# 2. Kiểm tra
# ======================
print("Tên cột sau khi xử lý:", df_clm.columns.tolist())
print("\nKiểm tra biến tương tác (8 dòng đầu):")
print(
    df_clm[
        ['id', 'order', 'air', 'HINC', 'AIRXHINC', 'PSIZE', 'AIRXPSIZE']
    ].head(8)
)
Output
Tên cột sau khi xử lý: ['MODE', 'TTME', 'INVC', 'INVT', 'GC', 'HINC', 'PSIZE', 'id', 'order', 'air', 'train', 'bus', 'utility', 'exp_utility', 'pred', 'AIRXHINC', 'TRAINXHINC', 'BUSXHINC', 'AIRXPSIZE', 'TRAINXPSIZE', 'BUSXPSIZE']

Kiểm tra biến tương tác (8 dòng đầu):
   id  order  air  HINC  AIRXHINC  PSIZE  AIRXPSIZE
0   1      1    1    35        35      1          1
1   1      2    0    35         0      1          0
2   1      3    0    35         0      1          0
3   1      4    0    35         0      1          0
4   2      1    1    30        30      2          2
5   2      2    0    30         0      2          0
6   2      3    0    30         0      2          0
7   2      4    0    30         0      2          0
# ── Ước lượng mô hình MXL ────────────────────────────────────────────
mxl_vars = ['TTME', 'INVC', 'INVT', 'GC', 'air', 'train', 'bus',
            'AIRXHINC', 'TRAINXHINC', 'BUSXHINC',
            'AIRXPSIZE', 'TRAINXPSIZE', 'BUSXPSIZE']

X_mxl = df_clm[mxl_vars].astype(float)

mxl_model  = ConditionalLogit(y_clm, X_mxl, groups=groups)
mxl_result = mxl_model.fit(method='newton', maxiter=300, disp=False)

# ── Pseudo R² (McFadden) dùng null LL đã tính ở trên ────────────────
# ll_null = Σ log(1/J_i) — tính từ cell CLM trước, dùng lại ở đây
n_alts_per_obs  = df_clm.groupby('id')['MODE'].count()
ll_null         = np.sum(np.log(1.0 / n_alts_per_obs))

pseudo_r2_clm = 1 - (clm_result.llf / ll_null)
pseudo_r2_mxl = 1 - (mxl_result.llf / ll_null)

# ── Bảng tóm tắt ─────────────────────────────────────────────────────
conf_int_mxl = mxl_result.conf_int()

mxl_summary_df = pd.DataFrame({
    'Coef.'   : mxl_result.params,
    'Std.Err.': mxl_result.bse,
    'z'       : mxl_result.tvalues,
    'P>|z|'   : mxl_result.pvalues,
    '[0.025'  : conf_int_mxl[0],
    '0.975]'  : conf_int_mxl[1]
}, index=mxl_vars)

print("Bảng 6.7 – Hồi quy MXL: Lựa chọn phương tiện di chuyển")
print("=" * 70)
print(mxl_summary_df.round(4).to_string())

# ── Thống kê mô hình ─────────────────────────────────────────────────
k_mxl   = len(mxl_result.params)
aic_mxl = -2 * mxl_result.llf + 2 * k_mxl

k_clm   = len(clm_result.params)
aic_clm = -2 * clm_result.llf + 2 * k_clm

lr_stat = 2 * (mxl_result.llf - clm_result.llf)
from scipy import stats
lr_pval = stats.chi2.sf(lr_stat, df=k_mxl - k_clm)   # 6 bậc tự do

print(f"""
{'':─<70}
Null log-likelihood  : {ll_null:.5f}
{'':─<70}
                       {'CLM':>12}   {'MXL':>12}
Log-likelihood       : {clm_result.llf:>12.5f}   {mxl_result.llf:>12.5f}
Pseudo R²            : {pseudo_r2_clm:>12.4f}   {pseudo_r2_mxl:>12.4f}
AIC                  : {aic_clm:>12.4f}   {aic_mxl:>12.4f}
{'':─<70}
LR test (MXL vs CLM) : stat = {lr_stat:.4f}, df = {k_mxl - k_clm}, p = {lr_pval:.4f}
""")
Output
Bảng 6.7 – Hồi quy MXL: Lựa chọn phương tiện di chuyển
======================================================================
              Coef.  Std.Err.       z   P>|z|  [0.025  0.975]
TTME        -0.1026    0.0114 -9.0154  0.0000 -0.1249 -0.0803
INVC        -0.0534    0.0253 -2.1103  0.0348 -0.1029 -0.0038
INVT        -0.0102    0.0034 -2.9988  0.0027 -0.0169 -0.0036
GC           0.0464    0.0249  1.8645  0.0623 -0.0024  0.0952
air          5.2865    1.2026  4.3958  0.0000  2.9294  7.6436
train        5.7083    0.7267  7.8556  0.0000  4.2841  7.1325
bus          4.7163    0.8239  5.7246  0.0000  3.1016  6.3311
AIRXHINC     0.0081    0.0134  0.6020  0.5472 -0.0182  0.0344
TRAINXHINC  -0.0595    0.0149 -3.9952  0.0001 -0.0887 -0.0303
BUSXHINC    -0.0199    0.0164 -1.2185  0.2230 -0.0520  0.0121
AIRXPSIZE   -0.5307    0.3210 -1.6531  0.0983 -1.1599  0.0985
TRAINXPSIZE  0.1628    0.2395  0.6800  0.4965 -0.3065  0.6322
BUSXPSIZE   -0.2399    0.3580 -0.6701  0.5028 -0.9416  0.4618

──────────────────────────────────────────────────────────────────────
Null log-likelihood  : -291.12182
──────────────────────────────────────────────────────────────────────
                                CLM            MXL
Log-likelihood       :   -184.50669     -170.68776
Pseudo R²            :       0.3662         0.4137
AIC                  :     383.0134       367.3755
──────────────────────────────────────────────────────────────────────
LR test (MXL vs CLM) : stat = 27.6379, df = 6, p = 0.0001

# Bảng 6.8 – MXL Odds Ratio
params_mxl = mxl_result.params
se_mxl     = mxl_result.bse
pvals_mxl  = mxl_result.pvalues

or_mxl = np.exp(params_mxl)
or_lo_mxl = np.exp(params_mxl - 1.96 * se_mxl)
or_hi_mxl = np.exp(params_mxl + 1.96 * se_mxl)

or_mxl_df = pd.DataFrame({
    'Odds Ratio': or_mxl.round(4),
    'Std.Err.'  : se_mxl.round(4),
    'z'         : (params_mxl / se_mxl).round(2),
    'P>|z|'     : pvals_mxl.round(3),
    '[0.025'    : or_lo_mxl.round(4),
    '0.975]'    : or_hi_mxl.round(4),
}, index=mxl_vars)

print("Bảng 6.8 – MXL theo tỷ số Odds")
print("=" * 72)
print(or_mxl_df.to_string())
Output
Bảng 6.8 – MXL theo tỷ số Odds
========================================================================
             Odds Ratio  Std.Err.     z  P>|z|   [0.025     0.975]
TTME             0.9025    0.0114 -9.02  0.000   0.8826     0.9229
INVC             0.9480    0.0253 -2.11  0.035   0.9022     0.9962
INVT             0.9898    0.0034 -3.00  0.003   0.9832     0.9965
GC               1.0475    0.0249  1.86  0.062   0.9976     1.0999
air            197.6504    1.2026  4.40  0.000  18.7154  2087.3589
train          301.3570    0.7267  7.86  0.000  72.5342  1252.0437
bus            111.7572    0.8239  5.72  0.000  22.2321   561.7848
AIRXHINC         1.0081    0.0134  0.60  0.547   0.9819     1.0350
TRAINXHINC       0.9422    0.0149 -4.00  0.000   0.9151     0.9701
BUSXHINC         0.9803    0.0164 -1.22  0.223   0.9493     1.0122
AIRXPSIZE        0.5882    0.3210 -1.65  0.098   0.3135     1.1035
TRAINXPSIZE      1.1768    0.2395  0.68  0.497   0.7360     1.8817
BUSXPSIZE        0.7867    0.3580 -0.67  0.503   0.3900     1.5870
# Chapter 6 - Multinomial Logit Models (MLM, CLM, MXL)
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(nnet); library(ggplot2); library(survival)  # survival ships with R

# Point data_dir at the repo's data folder (or set env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

dir.create('figures', showWarnings = FALSE)

palette <- c("#53b0ae", "#a31414", "#2b6999", "#e37000", "#b2c615", "#88837d", "#B3B3B3")

# --- Read data
df <- as.data.frame(read_dta(file.path(data_dir, 'migration.dta')))

print(head(df, 5))
Output
  tinh huyen xa diaban hoso m1ama HHsize gender genderhead age agehead agehead2
1    1     1  7      6    1     1      5      0          0  59      59     3481
2    1     1  7      6    1     2      5      1          0  45      59     3481
3    1     1  7      6    1     3      5      0          0  15      59     3481
4    1     1  7      6    2     1      3      0          0  50      50     2500
5    1     1  7      6    2     2      3      1          0  50      50     2500
  children_ratio elderly_ratio migration_place urban ethnicity agrland
1            0.4             0               0     1         1       0
2            0.4             0               0     1         1       0
3            0.4             0               0     1         1       0
4            0.0             0               0     1         1       0
5            0.0             0               0     1         1       0
  house_structure
1               1
2               1
3               1
4               1
5               1
# --- 6.1 / 6.2 Distribution of the dependent variable
counts <- table(df$migration_place)

print(counts)
Output
    0     1     2     3 
46697   167   154    26 
cdf <- data.frame(place = factor(names(counts),
        labels = c('No migration (0)', 'Hanoi/HCMC (1)', 'Other province (2)', 'Abroad (3)')),
        n = as.vector(counts))

p <- ggplot(cdf, aes(place, n, fill = place)) + geom_col(show.legend = FALSE) +
  geom_text(aes(label = format(n, big.mark = ',')), vjust = -0.3) +
  scale_fill_manual(values = palette[1:4]) +
  labs(title = 'Distribution of migration_place', x = NULL, y = 'Observations') + theme_minimal()

ggsave('figures/ch6_migration_place.png', p, width = 7, height = 4)
OutputR output: ch6_migration_place.png
# --- 6.2.1 MLM estimation (Table 6.1)
indep_vars <- c('gender','age','HHsize','genderhead','agehead','agehead2',
                'children_ratio','elderly_ratio','urban','ethnicity','agrland','house_structure')

df_model <- df[complete.cases(df[, c('migration_place', indep_vars)]), ]

df_model$migration_place <- factor(df_model$migration_place, levels = 0:3)

f <- as.formula(paste('migration_place ~', paste(indep_vars, collapse = ' + ')))

mlm <- multinom(f, data = df_model, maxit = 2000, reltol = 1e-14, trace = FALSE)

cat('N =', nrow(df_model), '\n')
Output
N = 47044 
coefs <- coef(mlm)   # 3 x K, rows = outcomes 1..3

# nnet's numerical Hessian is unreliable here (very wrong SEs), so compute the
# analytic observed information matrix of the multinomial logit at the estimates.
Xmat <- cbind(1, as.matrix(df_model[, indep_vars]))

eta <- Xmat %*% t(rbind(0, coefs))

P <- exp(eta - apply(eta, 1, max)); P <- P / rowSums(P)

K <- ncol(Xmat)

H <- matrix(0, 3 * K, 3 * K)

for (j in 1:3) for (k in 1:3) {
  w <- P[, j + 1] * ((j == k) - P[, k + 1])
  H[((j-1)*K+1):(j*K), ((k-1)*K+1):(k*K)] <- crossprod(Xmat * w, Xmat)
}

V <- solve(H)   # parameter order: outcome 1 (K coefs), outcome 2, outcome 3

ses <- matrix(sqrt(diag(V)), nrow = 3, byrow = TRUE, dimnames = dimnames(coefs))

for (j in 1:3) {
  cat('\nOutcome', j, '\n')
  print(round(cbind(coef = coefs[j, ], se = ses[j, ], z = coefs[j, ]/ses[j, ],
                    p = 2 * pnorm(-abs(coefs[j, ]/ses[j, ]))), 4))
}
Output
Outcome 1 
                    coef     se        z      p
(Intercept)     -12.0823 2.1518  -5.6150 0.0000
gender            0.2236 0.1586   1.4105 0.1584
age              -0.1158 0.0087 -13.2398 0.0000
HHsize           -0.4381 0.0796  -5.5012 0.0000
genderhead       -0.2172 0.2023  -1.0737 0.2829
agehead           0.3514 0.0794   4.4237 0.0000
agehead2         -0.0028 0.0007  -3.7689 0.0002
children_ratio    1.2131 0.6451   1.8805 0.0600
elderly_ratio    -0.6129 0.7156  -0.8566 0.3917
urban            -0.0685 0.2092  -0.3275 0.7433
ethnicity         0.8753 0.2648   3.3060 0.0009
agrland           0.6549 0.2160   3.0319 0.0024
house_structure  -0.5585 0.1814  -3.0786 0.0021

Outcome 2 
                   coef     se        z      p
(Intercept)     -6.9888 1.4525  -4.8115 0.0000
gender           0.0205 0.1645   0.1244 0.9010
age             -0.1064 0.0089 -11.9175 0.0000
HHsize          -0.2985 0.0730  -4.0917 0.0000
genderhead      -0.4599 0.2237  -2.0563 0.0397
agehead          0.1640 0.0509   3.2204 0.0013
agehead2        -0.0009 0.0004  -2.0440 0.0410
children_ratio   1.9533 0.6235   3.1330 0.0017
elderly_ratio   -1.5449 0.7688  -2.0097 0.0445
urban           -0.7047 0.2480  -2.8412 0.0045
ethnicity       -0.0736 0.2071  -0.3551 0.7225
agrland         -0.0316 0.2150  -0.1469 0.8832
house_structure -0.3484 0.1875  -1.8585 0.0631

Outcome 3 
                   coef     se       z      p
(Intercept)      0.2980 2.0482  0.1455 0.8843
gender           0.3170 0.4016  0.7893 0.4300
age             -0.0975 0.0202 -4.8215 0.0000
HHsize          -0.6559 0.2305 -2.8453 0.0044
genderhead       0.2179 0.4819  0.4522 0.6511
agehead         -0.1901 0.0744 -2.5551 0.0106
agehead2         0.0017 0.0007  2.5252 0.0116
children_ratio  -0.0620 1.4414 -0.0430 0.9657
elderly_ratio   -0.3583 1.8251 -0.1963 0.8444
urban           -1.2296 0.7931 -1.5502 0.1211
ethnicity        1.4912 0.7693  1.9382 0.0526
agrland          1.3321 0.6699  1.9886 0.0467
house_structure  0.8802 0.4040  2.1787 0.0294
# Fit statistics
ll <- as.numeric(logLik(mlm))

mlm0 <- multinom(migration_place ~ 1, data = df_model, trace = FALSE)

ll0 <- as.numeric(logLik(mlm0))

cat(sprintf('LogLik = %.1f, LL-null = %.1f, McFadden R2 = %.4f, LR chi2(36) = %.2f\n',
            ll, ll0, 1 - ll/ll0, 2 * (ll - ll0)))
Output
LogLik = -2033.1, LL-null = -2363.9, McFadden R2 = 0.1399, LR chi2(36) = 661.64
# --- 6.2.2 Relative risk ratios (Table 6.2)
rrr <- t(exp(coefs))

colnames(rrr) <- c('HN/HCM (1)', 'Other prov (2)', 'Abroad (3)')

cat('\nTable 6.2 - RRR\n'); print(round(rrr, 4))
Output
Table 6.2 - RRR
                HN/HCM (1) Other prov (2) Abroad (3)
(Intercept)         0.0000         0.0009     1.3472
gender              1.2506         1.0207     1.3730
age                 0.8907         0.8991     0.9071
HHsize              0.6453         0.7419     0.5190
genderhead          0.8048         0.6313     1.2435
agehead             1.4210         1.1782     0.8269
agehead2            0.9972         0.9991     1.0017
children_ratio      3.3640         7.0517     0.9398
elderly_ratio       0.5418         0.2133     0.6989
urban               0.9338         0.4943     0.2924
ethnicity           2.3997         0.9291     4.4422
agrland             1.9250         0.9689     3.7890
house_structure     0.5721         0.7058     2.4114
rr1 <- data.frame(var = names(rrr[-1, 1]), rrr = rrr[-1, 1])

p <- ggplot(rr1, aes(rrr, var, fill = rrr >= 1)) + geom_col(show.legend = FALSE) +
  geom_vline(xintercept = 1, linetype = 'dashed') +
  scale_fill_manual(values = c(palette[2], palette[1])) +
  labs(title = 'RRR: Migration to Hanoi/HCMC (outcome 1)', x = 'RRR', y = NULL) + theme_minimal()

ggsave('figures/ch6_rrr.png', p, width = 7, height = 4)
OutputR output: ch6_rrr.png
# --- 6.2.3 Predicted probabilities (Table 6.3), average over sample (Stata margins, at())
B <- rbind(0, coefs)   # 4 x K, base outcome has zero coefficients

predict_margins_at <- function(at, B = B_hat) {
  d <- df_model[, indep_vars]
  for (v in names(at)) d[[v]] <- at[[v]]
  X <- cbind(1, as.matrix(d))
  eta <- X %*% t(B)
  pr <- exp(eta - apply(eta, 1, max)); pr <- pr / rowSums(pr)
  colMeans(pr)
}

B_hat <- B

obs10_at <- list(gender = 1, age = 22, HHsize = 4, genderhead = 0, agehead = 52,
                 children_ratio = 0, elderly_ratio = 0.5, urban = 1, ethnicity = 1,
                 agrland = 0, house_structure = 1)

p10 <- predict_margins_at(obs10_at)

cat('\nObservation 10 predicted probabilities:\n'); print(setNames(round(p10, 7), 0:3))
Output
Observation 10 predicted probabilities:
        0         1         2         3 
0.9406088 0.0491225 0.0025345 0.0077341 
obs_custom_at <- list(gender = 1, age = 18, HHsize = 3, genderhead = 0, agehead = 60,
                      urban = 0, ethnicity = 1, agrland = 1, house_structure = 0)

p_custom <- predict_margins_at(obs_custom_at)

cat('\nTable 6.3 predicted probabilities:\n'); print(setNames(round(p_custom, 7), 0:3)); cat('Sum:', sum(p_custom), '\n')
Output
Table 6.3 predicted probabilities:
        0         1         2         3 
0.4019878 0.5516350 0.0315240 0.0148532 
Sum: 1 
pp <- data.frame(person = rep(c('Obs 10: female, 22, urban', 'Assumed: female, 18, rural'), each = 4),
                 outcome = rep(0:3, 2), prob = c(p10, p_custom))

p <- ggplot(pp, aes(factor(outcome), prob, fill = factor(outcome))) + geom_col(show.legend = FALSE) +
  facet_wrap(~person) + scale_fill_manual(values = palette[1:4]) +
  labs(x = 'migration_place', y = 'Predicted probability') + theme_minimal()

ggsave('figures/ch6_predicted_probs.png', p, width = 8, height = 4)
OutputR output: ch6_predicted_probs.png
# atmeans
means <- colMeans(df_model[, indep_vars])

print(round(means, 6))
Output
         gender             age          HHsize      genderhead         agehead 
       0.501127       37.860514        4.371354        0.200684       50.303864 
       agehead2  children_ratio   elderly_ratio           urban       ethnicity 
    2650.533989        0.201450        0.066368        0.285116        0.795000 
        agrland house_structure 
       0.682404        0.367677 
p_means <- predict_margins_at(as.list(means))

cat('\nProbabilities at means:\n'); print(setNames(round(p_means, 7), 0:3))
Output
Probabilities at means:
        0         1         2         3 
0.9974981 0.0010741 0.0013079 0.0001200 
# --- 6.2.4 Marginal effects at the mean (Table 6.4), delta-method SEs
xbar <- c(1, means)

me_fun <- function(theta) {
  Bm <- rbind(0, matrix(theta, nrow = 3, byrow = TRUE))
  eta <- as.vector(Bm %*% xbar); pr <- exp(eta - max(eta)); pr <- pr / sum(pr)
  bbar <- colSums(pr * Bm)
  sapply(1:4, function(j) pr[j] * (Bm[j, ] - bbar))   # K x 4
}

theta_hat <- as.vector(t(coefs))

me <- me_fun(theta_hat)

Jac <- sapply(seq_along(theta_hat), function(i) {
  h <- 1e-6 * max(1, abs(theta_hat[i])); t1 <- theta_hat; t2 <- theta_hat
  t1[i] <- t1[i] + h; t2[i] <- t2[i] - h
  (as.vector(me_fun(t1)) - as.vector(me_fun(t2))) / (2 * h)
})

me_se <- matrix(sqrt(diag(Jac %*% V %*% t(Jac))), nrow = length(xbar))

rownames(me) <- rownames(me_se) <- c('const', indep_vars)

me <- me[-1, ]; me_se <- me_se[-1, ]

me_z <- me / me_se; me_p <- 2 * pnorm(-abs(me_z))

for (j in 1:4) {
  cat('\nMarginal effects - outcome', j - 1, '\n')
  print(round(cbind(dydx = me[, j], se = me_se[, j], z = me_z[, j], p = me_p[, j]), 7))
}
Output
Marginal effects - outcome 0 
                      dydx        se         z         p
gender          -0.0003042 0.0002814 -1.081183 0.2796157
age              0.0002745 0.0000199 13.809460 0.0000000
HHsize           0.0009372 0.0001471  6.370245 0.0000000
genderhead       0.0008066 0.0003756  2.147460 0.0317567
agehead         -0.0005676 0.0001152 -4.928888 0.0000008
agehead2         0.0000039 0.0000010  3.862125 0.0001124
children_ratio  -0.0038406 0.0010906 -3.521562 0.0004290
elderly_ratio    0.0027151 0.0013131  2.067734 0.0386650
urban            0.0011399 0.0004159  2.740480 0.0061350
ethnicity       -0.0010203 0.0004193 -2.433612 0.0149490
agrland         -0.0008199 0.0003851 -2.128931 0.0332600
house_structure  0.0009476 0.0003305  2.867285 0.0041401

Marginal effects - outcome 1 
                      dydx        se          z         p
gender           0.0002399 0.0001725  1.3905182 0.1643716
age             -0.0001240 0.0000139 -8.9129081 0.0000000
HHsize          -0.0004695 0.0001003 -4.6808518 0.0000029
genderhead      -0.0002324 0.0002185 -1.0635968 0.2875114
agehead          0.0003768 0.0000911  4.1347749 0.0000355
agehead2        -0.0000030 0.0000008 -3.5960313 0.0003231
children_ratio   0.0012989 0.0006953  1.8680255 0.0617585
elderly_ratio   -0.0006554 0.0007737 -0.8470892 0.3969454
urban           -0.0000724 0.0002247 -0.3220569 0.7474096
ethnicity        0.0009391 0.0003006  3.1239725 0.0017843
agrland          0.0007026 0.0002446  2.8725435 0.0040718
house_structure -0.0005988 0.0002070 -2.8930090 0.0038157

Marginal effects - outcome 2 
                      dydx        se           z         p
gender           0.0000264 0.0002149   0.1226181 0.9024095
age             -0.0001388 0.0000136 -10.1709920 0.0000000
HHsize          -0.0003892 0.0001019  -3.8180557 0.0001345
genderhead      -0.0006004 0.0002975  -2.0180933 0.0435815
agehead          0.0002137 0.0000690   3.0990596 0.0019414
agehead2        -0.0000012 0.0000006  -2.0137231 0.0440386
children_ratio   0.0025496 0.0008169   3.1210867 0.0018018
elderly_ratio   -0.0020170 0.0010300  -1.9582205 0.0502041
urban           -0.0009202 0.0003339  -2.7555575 0.0058592
ethnicity       -0.0000975 0.0002707  -0.3603728 0.7185684
agrland         -0.0000424 0.0002810  -0.1508985 0.8800557
house_structure -0.0004544 0.0002491  -1.8243622 0.0680973

Marginal effects - outcome 3 
                      dydx        se          z         p
gender           0.0000380 0.0000495  0.7681815 0.4423794
age             -0.0000117 0.0000040 -2.8965419 0.0037730
HHsize          -0.0000786 0.0000336 -2.3383768 0.0193677
genderhead       0.0000262 0.0000596  0.4405092 0.6595684
agehead         -0.0000229 0.0000127 -1.8017608 0.0715830
agehead2         0.0000002 0.0000001  1.7996820 0.0719109
children_ratio  -0.0000079 0.0001735 -0.0455714 0.9636519
elderly_ratio   -0.0000427 0.0002202 -0.1937275 0.8463893
urban           -0.0001474 0.0001002 -1.4710435 0.1412793
ethnicity        0.0001788 0.0001056  1.6923187 0.0905852
agrland          0.0001597 0.0000924  1.7290625 0.0837979
house_structure  0.0001057 0.0000604  1.7512669 0.0798999
me1 <- data.frame(var = rownames(me), dydx = me[, 2], se = me_se[, 2])

p <- ggplot(me1, aes(dydx, var)) + geom_col(aes(fill = dydx >= 0), show.legend = FALSE) +
  geom_errorbar(aes(xmin = dydx - 1.96 * se, xmax = dydx + 1.96 * se), width = 0.3, orientation = 'y') +
  geom_vline(xintercept = 0, linetype = 'dashed') + scale_fill_manual(values = c(palette[2], palette[1])) +
  labs(title = 'Marginal effects: migration to Hanoi/HCMC', x = 'dy/dx', y = NULL) + theme_minimal()

ggsave('figures/ch6_me_outcome1.png', p, width = 7, height = 4, limitsize = FALSE)
OutputR output: ch6_me_outcome1.png
# --- 6.2.5 Summary table of marginal effects
stars <- function(p) ifelse(p < 0.001, '***', ifelse(p < 0.01, '**', ifelse(p < 0.05, '*', '')))

tab <- sapply(2:4, function(j) paste0(sprintf('%.6f', me[, j]), stars(me_p[, j])))

dimnames(tab) <- list(rownames(me), c('Outcome 1', 'Outcome 2', 'Outcome 3'))

cat('\nTable 6.4 - marginal effects summary\n'); print(noquote(tab))
Output
Table 6.4 - marginal effects summary
                Outcome 1    Outcome 2    Outcome 3  
gender          0.000240     0.000026     0.000038   
age             -0.000124*** -0.000139*** -0.000012**
HHsize          -0.000469*** -0.000389*** -0.000079* 
genderhead      -0.000232    -0.000600*   0.000026   
agehead         0.000377***  0.000214**   -0.000023  
agehead2        -0.000003*** -0.000001*   0.000000   
children_ratio  0.001299     0.002550**   -0.000008  
elderly_ratio   -0.000655    -0.002017    -0.000043  
urban           -0.000072    -0.000920**  -0.000147  
ethnicity       0.000939**   -0.000098    0.000179   
agrland         0.000703**   -0.000042    0.000160   
house_structure -0.000599**  -0.000454    0.000106   
# --- 6.3 Conditional logit (CLM)
df_clm <- read.csv(file.path(data_dir, 'TableF18-2.csv'))

cat('Shape:', dim(df_clm), '\n'); print(head(df_clm, 8))
Output
Shape: 840 7 
  MODE TTME INVC INVT GC HINC PSIZE
1    0   69   59  100 70   35     1
2    0   34   31  372 71   35     1
3    0   35   25  417 70   35     1
4    1    0   10  180 30   35     1
5    0   64   58   68 68   30     2
6    0   44   31  354 84   30     2
7    0   53   25  399 85   30     2
8    1    0   11  255 50   30     2
n <- nrow(df_clm)

df_clm$id <- (seq_len(n) - 1) %/% 4 + 1

df_clm$order <- (seq_len(n) - 1) %% 4 + 1

df_clm$air <- as.integer(df_clm$order == 1)

df_clm$train <- as.integer(df_clm$order == 2)

df_clm$bus <- as.integer(df_clm$order == 3)

print(tapply(df_clm$MODE, df_clm$order, sum))
Output
 1  2  3  4 
58 63 30 59 
# --- 6.3.1 CLM estimation (Table 6.5)
clm_fit <- clogit(MODE ~ TTME + INVC + INVT + GC + air + train + bus + strata(id),
                  data = df_clm, method = 'exact')

ll_null <- sum(log(1 / table(df_clm$id)))

ll_clm <- as.numeric(clm_fit$loglik[2])

cat('\nTable 6.5 - CLM\n'); print(round(summary(clm_fit)$coefficients[, c(1, 3, 4, 5)], 4))
Output
Table 6.5 - CLM
         coef se(coef)       z Pr(>|z|)
TTME  -0.1036   0.0109 -9.4760    0e+00
INVC  -0.0849   0.0194 -4.3819    0e+00
INVT  -0.0133   0.0025 -5.2969    0e+00
GC     0.0693   0.0174  3.9749    1e-04
air    5.2047   0.9052  5.7497    0e+00
train  4.3606   0.5107  8.5391    0e+00
bus    3.7632   0.5063  7.4334    0e+00
cat(sprintf('LogLik = %.4f, Null LL = %.4f, Pseudo R2 = %.4f, AIC = %.4f\n',
            ll_clm, ll_null, 1 - ll_clm/ll_null, -2 * ll_clm + 2 * length(coef(clm_fit))))
Output
LogLik = -184.5067, Null LL = -291.1218, Pseudo R2 = 0.3662, AIC = 383.0134
# --- 6.3.2 Odds ratios (Table 6.6)
b <- coef(clm_fit); se <- sqrt(diag(vcov(clm_fit)))

cat('\nTable 6.6 - CLM odds ratios\n')
Output
Table 6.6 - CLM odds ratios
print(round(cbind(OR = exp(b), se = se, z = b/se, lo = exp(b - 1.96 * se), hi = exp(b + 1.96 * se)), 4))
Output
            OR     se       z      lo        hi
TTME    0.9015 0.0109 -9.4760  0.8824    0.9211
INVC    0.9186 0.0194 -4.3819  0.8843    0.9541
INVT    0.9868 0.0025 -5.2969  0.9819    0.9916
GC      1.0718 0.0174  3.9749  1.0358    1.1090
air   182.1340 0.9052  5.7497 30.8929 1073.8015
train  78.3045 0.5107  8.5391 28.7806  213.0461
bus    43.0876 0.5063  7.4334 15.9741  116.2221
# --- 6.3.3 Predicted probabilities for individual 1
df_clm$utility <- as.vector(as.matrix(df_clm[, c('TTME','INVC','INVT','GC','air','train','bus')]) %*% b)

df_clm$exp_u <- exp(df_clm$utility)

df_clm$pred <- df_clm$exp_u / ave(df_clm$exp_u, df_clm$id, FUN = sum)

cat('\nPredicted probabilities, individual 1:\n')
Output
Predicted probabilities, individual 1:
print(df_clm[df_clm$id == 1, c('id', 'order', 'MODE', 'pred')])
Output
  id order MODE       pred
1  1     1    0 0.05629691
2  1     2    0 0.28013303
3  1     3    0 0.11846193
4  1     4    1 0.54510812
# --- 6.4 Mixed logit (MXL)
# --- 6.4.1 Estimation (Table 6.7)
df_clm$AIRXHINC <- df_clm$air * df_clm$HINC; df_clm$TRAINXHINC <- df_clm$train * df_clm$HINC

df_clm$BUSXHINC <- df_clm$bus * df_clm$HINC

df_clm$AIRXPSIZE <- df_clm$air * df_clm$PSIZE; df_clm$TRAINXPSIZE <- df_clm$train * df_clm$PSIZE

df_clm$BUSXPSIZE <- df_clm$bus * df_clm$PSIZE

mxl_fit <- clogit(MODE ~ TTME + INVC + INVT + GC + air + train + bus + AIRXHINC + TRAINXHINC +
                  BUSXHINC + AIRXPSIZE + TRAINXPSIZE + BUSXPSIZE + strata(id),
                  data = df_clm, method = 'exact')

ll_mxl <- as.numeric(mxl_fit$loglik[2])

cat('\nTable 6.7 - MXL\n'); print(round(summary(mxl_fit)$coefficients[, c(1, 3, 4, 5)], 4))
Output
Table 6.7 - MXL
               coef se(coef)       z Pr(>|z|)
TTME        -0.1026   0.0114 -9.0154   0.0000
INVC        -0.0534   0.0253 -2.1103   0.0348
INVT        -0.0102   0.0034 -2.9988   0.0027
GC           0.0464   0.0249  1.8645   0.0623
air          5.2865   1.2026  4.3958   0.0000
train        5.7083   0.7267  7.8556   0.0000
bus          4.7163   0.8239  5.7246   0.0000
AIRXHINC     0.0081   0.0134  0.6020   0.5472
TRAINXHINC  -0.0595   0.0149 -3.9952   0.0001
BUSXHINC    -0.0199   0.0164 -1.2185   0.2230
AIRXPSIZE   -0.5307   0.3210 -1.6531   0.0983
TRAINXPSIZE  0.1628   0.2395  0.6800   0.4965
BUSXPSIZE   -0.2399   0.3580 -0.6701   0.5028
lr <- 2 * (ll_mxl - ll_clm)

cat(sprintf('Null LL %.5f | CLM LL %.5f R2 %.4f AIC %.4f | MXL LL %.5f R2 %.4f AIC %.4f\n',
            ll_null, ll_clm, 1 - ll_clm/ll_null, -2*ll_clm + 14, ll_mxl, 1 - ll_mxl/ll_null, -2*ll_mxl + 26))
Output
Null LL -291.12182 | CLM LL -184.50669 R2 0.3662 AIC 383.0134 | MXL LL -170.68776 R2 0.4137 AIC 367.3755
cat(sprintf('LR test (MXL vs CLM): stat = %.4f, df = 6, p = %.4f\n', lr, pchisq(lr, 6, lower.tail = FALSE)))
Output
LR test (MXL vs CLM): stat = 27.6379, df = 6, p = 0.0001
# --- 6.4.2 MXL odds ratios (Table 6.8)
bm <- coef(mxl_fit); sem <- sqrt(diag(vcov(mxl_fit)))

cat('\nTable 6.8 - MXL odds ratios\n')
Output
Table 6.8 - MXL odds ratios
print(round(cbind(OR = exp(bm), se = sem, z = bm/sem, lo = exp(bm - 1.96 * sem), hi = exp(bm + 1.96 * sem)), 4))
Output
                  OR     se       z      lo        hi
TTME          0.9025 0.0114 -9.0154  0.8826    0.9229
INVC          0.9480 0.0253 -2.1103  0.9022    0.9962
INVT          0.9898 0.0034 -2.9988  0.9832    0.9965
GC            1.0475 0.0249  1.8645  0.9976    1.0999
air         197.6504 1.2026  4.3958 18.7154 2087.3583
train       301.3570 0.7267  7.8556 72.5342 1252.0440
bus         111.7572 0.8239  5.7246 22.2321  561.7848
AIRXHINC      1.0081 0.0134  0.6020  0.9819    1.0350
TRAINXHINC    0.9422 0.0149 -3.9952  0.9151    0.9701
BUSXHINC      0.9803 0.0164 -1.2185  0.9493    1.0122
AIRXPSIZE     0.5882 0.3210 -1.6531  0.3135    1.1035
TRAINXPSIZE   1.1768 0.2395  0.6800  0.7360    1.8817
BUSXPSIZE     0.7867 0.3580 -0.6701  0.3900    1.5870
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chương 6" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chương 6" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 6                                                 */
/*      File Name:  chapter6.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Multinominal regression models                */  
/*      Input File:     migration.dta                             */ 
/*                      TableF18-2.csv                            */  
/*      Output File:    chapter6.log                              */  
/******************************************************************/

log using chapter6.log, text replace

**# mô hình MLM 
use "$link\migration.dta",clear

mlogit migration_place gender age HHsize genderhead agehead agehead2 children_ratio elderly_ratio urban ethnicity agrland house_structure,base(0)

mlogit, rrr

margins, at (gender==1 age==22 HHsize==4 genderhead==0 agehead==52 children_ratio==0 elderly_ratio==0.5 urban==1 ethnicity==1 agrland==0 house_structure==1)
margins, at ( gender=1 age=18 HHsize=3 genderhead=0 agehead=60 urban=0 ethnicity=1 agrland=1 house_structure=0)

margins, atmeans

//Tác động biên

quietly mlogit migration_place gender age HHsize genderhead agehead agehead2 children_ratio elderly_ratio urban ethnicity agrland house_structure,base(0)

mfx, predict(p outcome(1)) 

mfx, predict(p outcome(2)) 

mfx, predict(p outcome(3)) 

**# mô hình MPM

mprobit migration_place gender age HHsize genderhead agehead agehead2 children_ratio elderly_ratio urban ethnicity agrland house_structure,base(0)

//Tác động biên

mfx, predict(p outcome(1))

mfx, predict(p outcome(2))

mfx, predict(p outcome(3))

**# Mô hình CLM

clear

import delimited "$link\TableF18-2.csv", delimiter("", collapse) 

gen id = ceil(_n / 4)

gen order = mod(_n-1, 4) + 1

gen air =(order==1)

gen train =(order==2)

gen bus =(order==3)

//CLM 

clogit mode ttme invc invt gc air train bus , group(id)

//CLM với tỷ số odds

clogit mode ttme invc invt gc air train bus , group(id) or

//Dự đoán cho cá nhân

predict predict

list id mode predict in 1/4

//Tác động biên 

asclogit mode ttme invc invt gc, case(id) alternatives(order) basealternative(4) nolog

**# Mô hình MXL

gen airXhinc = air* hinc

gen trainXhinc = train *hinc

gen busXhinc = bus * hinc

gen airXpsize= air* psize

gen trainXpsize= train * psize

gen busXpsize= bus * psize

//MXL

clogit mode ttme invc invt gc air train bus airXhinc trainXhinc busXhinc airXpsize trainXpsize busXpsize , group(id) nolog

///hay

asclogit mode ttme invc invt gc, case(id) alternatives(order) basealternative(4) casevars(hinc psize)  nolog

//MXL với tỷ số odds

clogit mode ttme invc invt gc air train bus airXhinc trainXhinc busXhinc airXpsize trainXpsize busXpsize , group(id) or nolog

///hay

asclogit mode ttme invc invt gc, case(id) alternatives(order) basealternative(4) casevars(hinc psize)  nolog or

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: migration.dta · TableF18-2.csv

Chapter 7 Panel data models

Pooled OLS, fixed and random effects, clustered SEs, F, Breusch-Pagan LM and Hausman tests.

df, meta = pyreadstat.read_dta(
    "rawdata/panel121416.dta",
    encoding="latin1",
)
df.head()
Output
year hhid HHsize agehead genderhead female_ratio migration remittances num_eduhead per_expenditure children_ratio elderly_ratio ln_per_expenditure agehead2
0 2012.0 32.0 5.0 59.0 1.0 0.4 0.0 10000.0 12 66575.000000 0.4 0.0 11.106085 3481.0
1 2014.0 32.0 2.0 61.0 1.0 0.5 1.0 19000.0 12 51281.000000 0.0 0.5 10.845076 3721.0
2 2016.0 32.0 2.0 63.0 1.0 0.5 0.0 60000.0 12 57732.000000 0.0 0.5 10.963567 3969.0
3 2012.0 33.0 5.0 33.0 0.0 0.8 0.0 130000.0 12 59666.199219 0.4 0.0 10.996521 1089.0
4 2014.0 33.0 5.0 35.0 0.0 0.6 0.0 253000.0 12 85886.601562 0.4 0.0 11.360784 1225.0
# Tạo biến agehead2 và id nếu chưa có
df["agehead2"] = df["agehead"] ** 2

# Tạo biến giả năm
df["_2012"] = (df["year"] == 2012).astype(int)
df["_2014"] = (df["year"] == 2014).astype(int)

# Tạo id nhóm từ hhid
df["id"] = df.groupby("hhid").ngroup() + 1

xvar = ["HHsize", "agehead", "children_ratio", "elderly_ratio",
        "genderhead", "female_ratio", "agehead2", "num_eduhead", "migration"]

print(f"Số quan sát: {len(df):,}")
print(f"Số hộ (N): {df['id'].nunique():,}")
print(f"Số năm (T): {df['year'].nunique()}")
print(f"Năm: {sorted(df['year'].unique())}")
print("\nThống kê mô tả:")
df[["ln_per_expenditure"] + xvar].describe().round(4)
Output
Số quan sát: 5,736
Số hộ (N): 1,912
Số năm (T): 3
Năm: [np.float64(2012.0), np.float64(2014.0), np.float64(2016.0)]

Thống kê mô tả:
ln_per_expenditure HHsize agehead children_ratio elderly_ratio genderhead female_ratio agehead2 num_eduhead migration
count 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000 5736.0000
mean 9.8442 3.8161 51.5938 0.1944 0.1598 0.2422 0.5255 2854.0631 7.1979 0.1219
std 0.6296 1.5540 13.8628 0.2026 0.2958 0.4284 0.2087 1544.2790 3.7114 0.3272
min 7.8021 1.0000 16.0000 0.0000 0.0000 0.0000 0.0000 256.0000 0.0000 0.0000
25% 9.4252 3.0000 42.0000 0.0000 0.0000 0.0000 0.4000 1764.0000 4.0000 0.0000
50% 9.8447 4.0000 50.0000 0.2000 0.0000 0.0000 0.5000 2500.0000 8.0000 0.0000
75% 10.2448 5.0000 60.0000 0.3333 0.2000 0.0000 0.6667 3600.0000 10.0000 0.0000
max 14.0620 13.0000 99.0000 0.7500 1.0000 1.0000 1.0000 9801.0000 12.0000 1.0000
X = sm.add_constant(df[xvar])
y = df["ln_per_expenditure"]

model_pooled = sm.OLS(y, X).fit()
print("=== Mô hình Pooled OLS (Bảng 7.1) ===")
print(model_pooled.summary())
Output
=== Mô hình Pooled OLS (Bảng 7.1) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.281
Model:                            OLS   Adj. R-squared:                  0.280
Method:                 Least Squares   F-statistic:                     249.1
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        16:58:00   Log-Likelihood:                -4537.1
No. Observations:                5736   AIC:                             9094.
Df Residuals:                    5726   BIC:                             9161.
Df Model:                           9                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const              8.7771      0.101     86.934      0.000       8.579       8.975
HHsize            -0.0727      0.006    -12.826      0.000      -0.084      -0.062
agehead            0.0342      0.004      9.355      0.000       0.027       0.041
children_ratio    -0.3040      0.047     -6.432      0.000      -0.397      -0.211
elderly_ratio     -0.2715      0.037     -7.289      0.000      -0.345      -0.198
genderhead         0.1301      0.019      6.829      0.000       0.093       0.167
female_ratio      -0.1880      0.038     -4.968      0.000      -0.262      -0.114
agehead2          -0.0003   3.34e-05     -8.002      0.000      -0.000      -0.000
num_eduhead        0.0698      0.002     34.833      0.000       0.066       0.074
migration          0.0958      0.022      4.365      0.000       0.053       0.139
==============================================================================
Omnibus:                      258.717   Durbin-Watson:                   1.138
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              480.417
Skew:                           0.347   Prob(JB):                    4.77e-105
Kurtosis:                       4.237   Cond. No.                     4.79e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.79e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
xvar_year = xvar + ["_2012", "_2014"]
X_year = sm.add_constant(df[xvar_year])

model_pooled_year = sm.OLS(y, X_year).fit()
print("=== Mô hình Pooled OLS với biến giả năm (Bảng 7.2) ===")
print(model_pooled_year.summary())
Output
=== Mô hình Pooled OLS với biến giả năm (Bảng 7.2) ===
                            OLS Regression Results                            
==============================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                       0.306
Model:                            OLS   Adj. R-squared:                  0.305
Method:                 Least Squares   F-statistic:                     229.3
Date:                Wed, 08 Apr 2026   Prob (F-statistic):               0.00
Time:                        16:58:00   Log-Likelihood:                -4437.5
No. Observations:                5736   AIC:                             8899.
Df Residuals:                    5724   BIC:                             8979.
Df Model:                          11                                         
Covariance Type:            nonrobust                                         
==================================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------
const              8.9886      0.101     89.434      0.000       8.792       9.186
HHsize            -0.0704      0.006    -12.622      0.000      -0.081      -0.059
agehead            0.0319      0.004      8.861      0.000       0.025       0.039
children_ratio    -0.3382      0.047     -7.269      0.000      -0.429      -0.247
elderly_ratio     -0.2756      0.037     -7.527      0.000      -0.347      -0.204
genderhead         0.1298      0.019      6.933      0.000       0.093       0.167
female_ratio      -0.1940      0.037     -5.213      0.000      -0.267      -0.121
agehead2          -0.0003   3.29e-05     -7.687      0.000      -0.000      -0.000
num_eduhead        0.0688      0.002     34.945      0.000       0.065       0.073
migration          0.0267      0.022      1.194      0.233      -0.017       0.071
_2012             -0.2481      0.017    -14.194      0.000      -0.282      -0.214
_2014             -0.1031      0.017     -6.060      0.000      -0.136      -0.070
==============================================================================
Omnibus:                      281.358   Durbin-Watson:                   1.073
Prob(Omnibus):                  0.000   Jarque-Bera (JB):              531.469
Skew:                           0.368   Prob(JB):                    3.92e-116
Kurtosis:                       4.297   Cond. No.                     4.85e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 4.85e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
# Chuẩn bị dữ liệu dạng panel (MultiIndex: entity, time)
df_panel = df.set_index(["id", "year"])

y_panel = df_panel["ln_per_expenditure"]
X_panel = df_panel[xvar]

# FEM – Fixed Effects (Within-group)
fem = PanelOLS(y_panel, X_panel, entity_effects=True, drop_absorbed=True)
fem_res = fem.fit(cov_type='unadjusted')
print("=== Mô hình FEM – Fixed Effects (Bảng 7.3) ===")
print(fem_res)

# ── sigma_u, sigma_e, rho – khớp Stata xtreg,fe ─────────────────────────────
resid   = fem_res.resids.copy()
N       = df_panel.index.get_level_values("id").nunique()
T_total = len(df_panel)
K       = len(xvar)
T_bar   = T_total / N

# sigma_e: RSS_within / (T_total - N - K)
rss_within = (resid**2).sum()
sigma_e2   = rss_within / (T_total - N - K)
sigma_e    = np.sqrt(sigma_e2)

# alpha_i = entity fixed effects: y_bar_i - X_bar_i @ beta_FEM
y_bar_i = df_panel[y_panel.name].groupby(level=0).mean()
X_bar_i = df_panel[xvar].groupby(level=0).mean()
alpha_i = y_bar_i - X_bar_i @ fem_res.params

# sigma_u: phương sai mẫu của alpha_i (khớp Stata)
sigma_u2 = (alpha_i - alpha_i.mean()).pow(2).sum() / (N - 1)
sigma_u2 = max(sigma_u2, 0)
sigma_u  = np.sqrt(sigma_u2)
rho      = sigma_u2 / (sigma_u2 + sigma_e2)

print(f"sigma_u = {sigma_u:.8f}")
print(f"sigma_e = {sigma_e:.8f}")
print(f"rho     = {rho:.8f}")

# ── _cons của FEM = grand mean của entity effects (khớp Stata _cons) ──────────
# Stata báo _cons = y_dbar - X_dbar @ beta, SE tính bằng delta method
const_fem   = alpha_i.mean()
X_dbar      = df_panel[xvar].mean()                           # grand means của X
se_const_fem = np.sqrt(X_dbar.values @ fem_res.cov.values @ X_dbar.values)
t_const_fem  = const_fem / se_const_fem

print(f"_cons   = {const_fem:.7f}  SE = {se_const_fem:.7f}  t = {t_const_fem:.3f}")
Output
=== Mô hình FEM – Fixed Effects (Bảng 7.3) ===
                          PanelOLS Estimation Summary                           
================================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                        0.0912
Estimator:                   PanelOLS   R-squared (Between):              0.2130
No. Observations:                5736   R-squared (Within):               0.0912
Date:                Wed, Apr 08 2026   R-squared (Overall):              0.2129
Time:                        16:58:00   Log-likelihood                   -1140.4
Cov. Estimator:            Unadjusted                                           
                                        F-statistic:                      42.541
Entities:                        1912   P-value                           0.0000
Avg Obs:                       3.0000   Distribution:                  F(9,3815)
Min Obs:                       3.0000                                           
Max Obs:                       3.0000   F-statistic (robust):             42.541
                                        P-value                           0.0000
Time periods:                       3   Distribution:                  F(9,3815)
Avg Obs:                       1912.0                                           
Min Obs:                       1912.0                                           
Max Obs:                       1912.0                                           
                                                                                
                               Parameter Estimates                                
==================================================================================
                Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
----------------------------------------------------------------------------------
HHsize            -0.0546     0.0085    -6.3930     0.0000     -0.0714     -0.0379
agehead            0.0360     0.0070     5.1542     0.0000      0.0223      0.0498
children_ratio    -0.3739     0.0642    -5.8274     0.0000     -0.4998     -0.2481
elderly_ratio     -0.0710     0.0513    -1.3856     0.1659     -0.1715      0.0295
genderhead         0.1424     0.0438     3.2531     0.0012      0.0566      0.2282
female_ratio      -0.0577     0.0611    -0.9438     0.3454     -0.1775      0.0621
agehead2          -0.0002  6.304e-05    -3.8448     0.0001     -0.0004     -0.0001
num_eduhead        0.0299     0.0046     6.5513     0.0000      0.0210      0.0389
migration          0.1370     0.0195     7.0238     0.0000      0.0988      0.1752
==================================================================================

F-test for Poolability: 4.5288
P-value: 0.0000
Distribution: F(1911,3815)

Included effects: Entity
sigma_u = 0.49347037
sigma_e = 0.36196155
rho     = 0.65018435
_cons   = 8.7324686  SE = 0.1999724  t = 43.668
fem_robust = PanelOLS(y_panel, X_panel, entity_effects=True, drop_absorbed=True)
fem_robust_res = fem_robust.fit(cov_type='clustered', cluster_entity=True)
print("=== FEM với Sai số chuẩn mạnh (Bảng 7.4) ===")
print(fem_robust_res)

# sigma_u, sigma_e, rho giống FEM (chỉ khác std.err) – dùng lại từ Bảng 7.3
print(f"sigma_u = {sigma_u:.8f}")
print(f"sigma_e = {sigma_e:.8f}")
print(f"rho     = {rho:.8f}")
Output
=== FEM với Sai số chuẩn mạnh (Bảng 7.4) ===
                          PanelOLS Estimation Summary                           
================================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                        0.0912
Estimator:                   PanelOLS   R-squared (Between):              0.2130
No. Observations:                5736   R-squared (Within):               0.0912
Date:                Wed, Apr 08 2026   R-squared (Overall):              0.2129
Time:                        16:58:00   Log-likelihood                   -1140.4
Cov. Estimator:             Clustered                                           
                                        F-statistic:                      42.541
Entities:                        1912   P-value                           0.0000
Avg Obs:                       3.0000   Distribution:                  F(9,3815)
Min Obs:                       3.0000                                           
Max Obs:                       3.0000   F-statistic (robust):             36.502
                                        P-value                           0.0000
Time periods:                       3   Distribution:                  F(9,3815)
Avg Obs:                       1912.0                                           
Min Obs:                       1912.0                                           
Max Obs:                       1912.0                                           
                                                                                
                               Parameter Estimates                                
==================================================================================
                Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
----------------------------------------------------------------------------------
HHsize            -0.0546     0.0101    -5.4136     0.0000     -0.0744     -0.0348
agehead            0.0360     0.0099     3.6442     0.0003      0.0167      0.0554
children_ratio    -0.3739     0.0632    -5.9180     0.0000     -0.4978     -0.2501
elderly_ratio     -0.0710     0.0574    -1.2381     0.2158     -0.1835      0.0414
genderhead         0.1424     0.0502     2.8343     0.0046      0.0439      0.2409
female_ratio      -0.0577     0.0710    -0.8128     0.4164     -0.1968      0.0814
agehead2          -0.0002  8.814e-05    -2.7501     0.0060     -0.0004  -6.958e-05
num_eduhead        0.0299     0.0053     5.6891     0.0000      0.0196      0.0403
migration          0.1370     0.0199     6.8979     0.0000      0.0981      0.1759
==================================================================================

F-test for Poolability: 4.5288
P-value: 0.0000
Distribution: F(1911,3815)

Included effects: Entity
sigma_u = 0.49347037
sigma_e = 0.36196155
rho     = 0.65018435
# REM yêu cầu thêm hằng số (const) vào X – Stata tự thêm, linearmodels thì không
X_panel_rem = sm.add_constant(df_panel[xvar])

rem = RandomEffects(y_panel, X_panel_rem)
rem_res = rem.fit(cov_type='unadjusted')
print("=== Mô hình REM – Random Effects (Bảng 7.5) ===")
print(rem_res)

# ── sigma_u, sigma_e, rho – khớp Stata xtreg (REM) ─────────────────────────
# linearmodels lưu variance components trong variance_decomposition:
#   Effects  = sigma_u^2  (between variance)
#   Residual = sigma_e^2  (within/idiosyncratic variance)
var_decomp   = rem_res.variance_decomposition
sigma_u2_rem = float(var_decomp.loc["Effects"])
sigma_e2_rem = float(var_decomp.loc["Residual"])
sigma_u_rem  = np.sqrt(sigma_u2_rem)
sigma_e_rem  = np.sqrt(sigma_e2_rem)
rho_rem      = sigma_u2_rem / (sigma_u2_rem + sigma_e2_rem)

print(f"sigma_u = {sigma_u_rem:.8f}")
print(f"sigma_e = {sigma_e_rem:.8f}")
print(f"rho     = {rho_rem:.8f}")
Output
=== Mô hình REM – Random Effects (Bảng 7.5) ===
                        RandomEffects Estimation Summary                        
================================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                        0.1815
Estimator:              RandomEffects   R-squared (Between):              0.3419
No. Observations:                5736   R-squared (Within):               0.0686
Date:                Wed, Apr 08 2026   R-squared (Overall):              0.2758
Time:                        16:58:01   Log-likelihood                   -2368.6
Cov. Estimator:            Unadjusted                                           
                                        F-statistic:                      141.06
Entities:                        1912   P-value                           0.0000
Avg Obs:                       3.0000   Distribution:                  F(9,5726)
Min Obs:                       3.0000                                           
Max Obs:                       3.0000   F-statistic (robust):             141.06
                                        P-value                           0.0000
Time periods:                       3   Distribution:                  F(9,5726)
Avg Obs:                       1912.0                                           
Min Obs:                       1912.0                                           
Max Obs:                       1912.0                                           
                                                                                
                               Parameter Estimates                                
==================================================================================
                Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
----------------------------------------------------------------------------------
const              8.7458     0.1196     73.125     0.0000      8.5113      8.9803
HHsize            -0.0667     0.0062    -10.708     0.0000     -0.0789     -0.0545
agehead            0.0360     0.0043     8.3697     0.0000      0.0276      0.0444
children_ratio    -0.3196     0.0495    -6.4530     0.0000     -0.4167     -0.2225
elderly_ratio     -0.2067     0.0394    -5.2488     0.0000     -0.2839     -0.1295
genderhead         0.1316     0.0239     5.5045     0.0000      0.0847      0.1784
female_ratio      -0.1504     0.0431    -3.4888     0.0005     -0.2350     -0.0659
agehead2          -0.0003  3.924e-05    -7.2159     0.0000     -0.0004     -0.0002
num_eduhead        0.0598     0.0025     23.711     0.0000      0.0549      0.0648
migration          0.1238     0.0177     6.9783     0.0000      0.0890      0.1586
==================================================================================
sigma_u = 0.38826470
sigma_e = 0.36196155
rho     = 0.53501724
rem_robust_res = rem.fit(cov_type='clustered', cluster_entity=True)
print("=== REM với Sai số chuẩn mạnh (Bảng 7.6) ===")
print(rem_robust_res)

# sigma_u, sigma_e, rho giống REM (chỉ khác std.err) – dùng lại từ Bảng 7.5
print(f"sigma_u = {sigma_u_rem:.8f}")
print(f"sigma_e = {sigma_e_rem:.8f}")
print(f"rho     = {rho_rem:.8f}")
Output
=== REM với Sai số chuẩn mạnh (Bảng 7.6) ===
                        RandomEffects Estimation Summary                        
================================================================================
Dep. Variable:     ln_per_expenditure   R-squared:                        0.1815
Estimator:              RandomEffects   R-squared (Between):              0.3419
No. Observations:                5736   R-squared (Within):               0.0686
Date:                Wed, Apr 08 2026   R-squared (Overall):              0.2758
Time:                        16:58:01   Log-likelihood                   -2368.6
Cov. Estimator:             Clustered                                           
                                        F-statistic:                      141.06
Entities:                        1912   P-value                           0.0000
Avg Obs:                       3.0000   Distribution:                  F(9,5726)
Min Obs:                       3.0000                                           
Max Obs:                       3.0000   F-statistic (robust):             122.69
                                        P-value                           0.0000
Time periods:                       3   Distribution:                  F(9,5726)
Avg Obs:                       1912.0                                           
Min Obs:                       1912.0                                           
Max Obs:                       1912.0                                           
                                                                                
                               Parameter Estimates                                
==================================================================================
                Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
----------------------------------------------------------------------------------
const              8.7458     0.1260     69.412     0.0000      8.4988      8.9928
HHsize            -0.0667     0.0070    -9.5432     0.0000     -0.0804     -0.0530
agehead            0.0360     0.0048     7.4977     0.0000      0.0266      0.0454
children_ratio    -0.3196     0.0513    -6.2294     0.0000     -0.4202     -0.2190
elderly_ratio     -0.2067     0.0440    -4.6934     0.0000     -0.2930     -0.1204
genderhead         0.1316     0.0250     5.2690     0.0000      0.0826      0.1805
female_ratio      -0.1504     0.0474    -3.1728     0.0015     -0.2434     -0.0575
agehead2          -0.0003  4.432e-05    -6.3885     0.0000     -0.0004     -0.0002
num_eduhead        0.0598     0.0027     21.790     0.0000      0.0544      0.0652
migration          0.1238     0.0175     7.0762     0.0000      0.0895      0.1581
==================================================================================
sigma_u = 0.38826470
sigma_e = 0.36196155
rho     = 0.53501724
# Kiểm định Breusch-Pagan LM (tương đương xttest0 trong Stata)
# Dùng statsmodels với mô hình RE từ linearmodels

# Tính LM test thủ công
# residuals từ Pooled OLS, kiểm định tương quan nội nhóm
df_panel_copy = df.copy()
df_panel_copy["resid_pooled"] = model_pooled.resid.values

# Tính tổng bình phương phần dư trong nhóm (between) và tổng thể
group_mean_resid = df_panel_copy.groupby("id")["resid_pooled"].mean()
df_panel_copy["group_mean_resid"] = df_panel_copy["id"].map(group_mean_resid)

n = len(df_panel_copy)
N = df_panel_copy["id"].nunique()   # số nhóm
T = df_panel_copy.groupby("id").size().mean()  # số quan sát trung bình mỗi nhóm

sum_group_sq = (df_panel_copy.groupby("id")["resid_pooled"].sum() ** 2).sum()
sum_total_sq = (df_panel_copy["resid_pooled"] ** 2).sum()

LM = (n / (2 * (T - 1))) * (sum_group_sq / sum_total_sq - 1) ** 2
p_lm = 1 - chi2.cdf(LM, df=1)

print("=== Kiểm định Breusch-Pagan LM (tương đương xttest0) ===")
print(f"LM statistic (chibar2):  {LM:.4f}")
print(f"P-value (Prob > chibar2): {p_lm:.4f}")
if p_lm < 0.05:
    print("→ Bác bỏ H₀: REM phù hợp hơn Pooled OLS")
else:
    print("→ Không bác bỏ H₀: Pooled OLS phù hợp")
Output
=== Kiểm định Breusch-Pagan LM (tương đương xttest0) ===
LM statistic (chibar2):  1560.6864
P-value (Prob > chibar2): 0.0000
→ Bác bỏ H₀: REM phù hợp hơn Pooled OLS
# Kiểm định Hausman – FEM vs REM
# FEM không có const; REM có const → chỉ so sánh các biến chung

b_fem = fem_res.params          # Hệ số FEM (nhất quán)
b_rem = rem_res.params          # Hệ số REM (hiệu quả dưới H0)

# Chỉ lấy các biến xuất hiện trong cả hai (loại bỏ const)
common_vars = b_fem.index.intersection(b_rem.index)
b_diff = b_fem[common_vars] - b_rem[common_vars]

V_fem = fem_res.cov.loc[common_vars, common_vars]
V_rem = rem_res.cov.loc[common_vars, common_vars]
V_diff = V_fem - V_rem

# Thống kê kiểm định Hausman
try:
    chi2_stat = float(b_diff.values @ np.linalg.pinv(V_diff.values) @ b_diff.values)
    df_hausman = len(common_vars)
    p_hausman = 1 - chi2.cdf(chi2_stat, df=df_hausman)

    print("=== Kiểm định Hausman – FEM vs REM (Bảng 7.7) ===")
    print(f"\n{'Biến':20s} {'FEM (b)':>12s} {'REM (B)':>12s} {'Difference':>12s}")
    print("-" * 60)
    for var in common_vars:
        print(f"{var:20s} {b_fem[var]:12.7f} {b_rem[var]:12.7f} {b_diff[var]:12.7f}")
    print("-" * 60)
    print(f"\nchi2({df_hausman}) = {chi2_stat:.2f}")
    print(f"Prob > chi2 = {p_hausman:.4f}")
    if p_hausman < 0.05:
        print("→ Bác bỏ H₀: FEM phù hợp hơn REM")
    else:
        print("→ Không bác bỏ H₀: REM phù hợp")
except Exception as e:
    print(f"Lỗi tính Hausman: {e}")
Output
=== Kiểm định Hausman – FEM vs REM (Bảng 7.7) ===

Biến                      FEM (b)      REM (B)   Difference
------------------------------------------------------------
HHsize                 -0.0546127   -0.0666961    0.0120834
agehead                 0.0360423    0.0360040    0.0000383
children_ratio         -0.3739499   -0.3196301   -0.0543198
elderly_ratio          -0.0710151   -0.2066921    0.1356770
genderhead              0.1423765    0.1315705    0.0108061
female_ratio           -0.0576705   -0.1504372    0.0927667
agehead2               -0.0002424   -0.0002831    0.0000408
num_eduhead             0.0299362    0.0598276   -0.0298915
migration               0.1370016    0.1237871    0.0132145
------------------------------------------------------------

chi2(9) = 140.12
Prob > chi2 = 0.0000
→ Bác bỏ H₀: FEM phù hợp hơn REM
# Bảng so sánh Pooled OLS, FEM, REM
pooled_params = model_pooled.params
fem_params    = fem_res.params.copy()
rem_params    = rem_res.params

# Thêm _cons vào FEM (grand mean của entity effects)
fem_params["const"] = const_fem

all_vars = pooled_params.index.tolist()   # const + 9 biến
comparison = pd.DataFrame(index=all_vars)
comparison["Pooled OLS"] = pooled_params
comparison["FEM"]        = fem_params.reindex(all_vars)
comparison["REM"]        = rem_params.reindex(all_vars)

# t/z statistics
pooled_t = model_pooled.tvalues
fem_t    = fem_res.tstats.copy()
fem_t["const"] = t_const_fem
rem_z    = rem_res.tstats

tstat = pd.DataFrame(index=all_vars)
tstat["Pooled OLS (t)"] = pooled_t
tstat["FEM (t)"]        = fem_t.reindex(all_vars)
tstat["REM (z)"]        = rem_z.reindex(all_vars)

# P-values for significance stars
pooled_pvalues = model_pooled.pvalues
fem_pvalues    = fem_res.pvalues.copy()
rem_pvalues    = rem_res.pvalues

# Calculate p-value for FEM 'const'
# T-distribution with df_resid degrees of freedom for two-tailed test
p_const_fem = 2 * (1 - scipy.stats.t.cdf(abs(t_const_fem), df=fem_res.df_resid))
fem_pvalues["const"] = p_const_fem

# Helper function to add stars
def add_stars(p_value):
    if p_value < 0.001:
        return '***'
    elif p_value < 0.01:
        return '**'
    elif p_value < 0.05:
        return '*'
    else:
        return ''

# Apply stars to coefficients
comparison_starred = comparison.copy()
for var in all_vars:
    p_pooled = pooled_pvalues.get(var, 1)  # Default to 1 if not found
    p_fem = fem_pvalues.get(var, 1)
    p_rem = rem_pvalues.get(var, 1)

    comparison_starred.loc[var, 'Pooled OLS'] = f"{comparison.loc[var, 'Pooled OLS']:.6f}{add_stars(p_pooled)}"
    comparison_starred.loc[var, 'FEM']        = f"{comparison.loc[var, 'FEM']:.6f}{add_stars(p_fem)}"
    comparison_starred.loc[var, 'REM']        = f"{comparison.loc[var, 'REM']:.6f}{add_stars(p_rem)}"

print("=== Hệ số ước lượng ===")
print(comparison_starred.to_string())
print("\n=== Thống kê t/z ===")
print(tstat.round(3).to_string())

# ── R-squared ────────────────────────────────────────────────────────────────
print("\n=== R-squared ===")
rsq = pd.DataFrame({
    "Pooled OLS": {
        "R²":            round(model_pooled.rsquared, 4),
        "Adj R²":        round(model_pooled.rsquared_adj, 4),
        "Within":        "-",
        "Between":       "-",
        "Overall":       "-",
    },
    "FEM": {
        "R²":            "-",
        "Adj R²":        "-",
        "Within":        round(float(fem_res.rsquared), 4),
        "Between":       round(float(fem_res.rsquared_between), 4),
        "Overall":       round(float(fem_res.rsquared_overall), 4),
    },
    "REM": {
        "R²":            "-",
        "Adj R²":        "-",
        "Within":        round(float(rem_res.rsquared), 4),
        "Between":       round(float(rem_res.rsquared_between), 4),
        "Overall":       round(float(rem_res.rsquared_overall), 4),
    },
})
print(rsq.to_string())
Output
=== Hệ số ước lượng ===
                  Pooled OLS           FEM           REM
const            8.777095***   8.732469***   8.745807***
HHsize          -0.072745***  -0.054613***  -0.066696***
agehead          0.034190***   0.036042***   0.036004***
children_ratio  -0.303980***  -0.373950***  -0.319630***
elderly_ratio   -0.271504***     -0.071015  -0.206692***
genderhead       0.130080***    0.142377**   0.131570***
female_ratio    -0.188046***     -0.057670  -0.150437***
agehead2        -0.000267***  -0.000242***  -0.000283***
num_eduhead      0.069775***   0.029936***   0.059828***
migration        0.095824***   0.137002***   0.123787***

=== Thống kê t/z ===
                Pooled OLS (t)  FEM (t)  REM (z)
const                   86.934   43.668   73.125
HHsize                 -12.826   -6.393  -10.708
agehead                  9.355    5.154    8.370
children_ratio          -6.432   -5.827   -6.453
elderly_ratio           -7.289   -1.386   -5.249
genderhead               6.829    3.253    5.505
female_ratio            -4.968   -0.944   -3.489
agehead2                -8.002   -3.845   -7.216
num_eduhead             34.833    6.551   23.711
migration                4.365    7.024    6.978

=== R-squared ===
        Pooled OLS     FEM     REM
R²          0.2814       -       -
Adj R²      0.2802       -       -
Within           -  0.0912  0.1815
Between          -   0.213  0.3419
Overall          -  0.2129  0.2758
# Chapter 7 - Panel Data
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(plm); library(lmtest); library(sandwich)

# Point data_dir at the repo's data folder (or set env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

# --- Read data
df <- as.data.frame(read_dta(file.path(data_dir, 'panel121416.dta')))

head(df)
Output
  year hhid HHsize agehead genderhead female_ratio migration remittances
1 2012   32      5      59          1          0.4         0       10000
2 2014   32      2      61          1          0.5         1       19000
3 2016   32      2      63          1          0.5         0       60000
4 2012   33      5      33          0          0.8         0      130000
5 2014   33      5      35          0          0.6         0      253000
6 2016   33      5      37          0          0.8         0       65000
  num_eduhead per_expenditure children_ratio elderly_ratio ln_per_expenditure
1          12         66575.0            0.4           0.0           11.10608
2          12         51281.0            0.0           0.5           10.84508
3          12         57732.0            0.0           0.5           10.96357
4          12         59666.2            0.4           0.0           10.99652
5          12         85886.6            0.4           0.0           11.36078
6          12        119605.6            0.4           0.2           11.69195
  agehead2
1     3481
2     3721
3     3969
4     1089
5     1225
6     1369
# --- 7.7 Data preparation
df$agehead2 <- df$agehead^2

df$`_2012` <- as.integer(df$year == 2012)

df$`_2014` <- as.integer(df$year == 2014)

df$id <- as.integer(factor(df$hhid))

xvar <- c('HHsize','agehead','children_ratio','elderly_ratio','genderhead',
          'female_ratio','agehead2','num_eduhead','migration')

cat('Observations:', nrow(df), '\nHouseholds (N):', length(unique(df$id)),
    '\nYears (T):', length(unique(df$year)), '\nYears:', sort(unique(df$year)), '\n')
Output
Observations: 5736 
Households (N): 1912 
Years (T): 3 
Years: 2012 2014 2016 
print(round(t(sapply(df[c('ln_per_expenditure', xvar)], function(x)
  c(mean = mean(x), sd = sd(x), min = min(x), max = max(x)))), 4))
Output
                        mean        sd      min      max
ln_per_expenditure    9.8442    0.6296   7.8021   14.062
HHsize                3.8161    1.5540   1.0000   13.000
agehead              51.5938   13.8628  16.0000   99.000
children_ratio        0.1944    0.2026   0.0000    0.750
elderly_ratio         0.1598    0.2958   0.0000    1.000
genderhead            0.2422    0.4284   0.0000    1.000
female_ratio          0.5255    0.2087   0.0000    1.000
agehead2           2854.0631 1544.2790 256.0000 9801.000
num_eduhead           7.1979    3.7114   0.0000   12.000
migration             0.1219    0.3272   0.0000    1.000
# --- Table 7.1 Pooled OLS
f1 <- reformulate(xvar, 'ln_per_expenditure')

pooled <- lm(f1, data = df)

print(summary(pooled))
Output
Call:
lm(formula = f1, data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.8028 -0.3459 -0.0130  0.3274  3.4491 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)     8.777e+00  1.010e-01  86.934  < 2e-16 ***
HHsize         -7.274e-02  5.672e-03 -12.826  < 2e-16 ***
agehead         3.419e-02  3.655e-03   9.355  < 2e-16 ***
children_ratio -3.040e-01  4.726e-02  -6.432 1.36e-10 ***
elderly_ratio  -2.715e-01  3.725e-02  -7.289 3.54e-13 ***
genderhead      1.301e-01  1.905e-02   6.829 9.44e-12 ***
female_ratio   -1.880e-01  3.785e-02  -4.968 6.97e-07 ***
agehead2       -2.675e-04  3.343e-05  -8.002 1.47e-15 ***
num_eduhead     6.977e-02  2.003e-03  34.833  < 2e-16 ***
migration       9.582e-02  2.195e-02   4.365 1.30e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5341 on 5726 degrees of freedom
Multiple R-squared:  0.2814,	Adjusted R-squared:  0.2802 
F-statistic: 249.1 on 9 and 5726 DF,  p-value: < 2.2e-16
# --- Table 7.2 Pooled OLS with year dummies (2016 = reference)
df$y2012 <- df$`_2012`; df$y2014 <- df$`_2014`

pooled_year <- lm(reformulate(c(xvar, 'y2012', 'y2014'), 'ln_per_expenditure'), data = df)

print(summary(pooled_year))
Output
Call:
lm(formula = reformulate(c(xvar, "y2012", "y2014"), "ln_per_expenditure"), 
    data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-1.9195 -0.3439 -0.0147  0.3194  3.4327 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)     8.989e+00  1.005e-01  89.434  < 2e-16 ***
HHsize         -7.041e-02  5.578e-03 -12.622  < 2e-16 ***
agehead         3.187e-02  3.596e-03   8.861  < 2e-16 ***
children_ratio -3.382e-01  4.652e-02  -7.269 4.10e-13 ***
elderly_ratio  -2.756e-01  3.661e-02  -7.527 5.98e-14 ***
genderhead      1.298e-01  1.872e-02   6.933 4.59e-12 ***
female_ratio   -1.940e-01  3.721e-02  -5.213 1.92e-07 ***
agehead2       -2.527e-04  3.288e-05  -7.687 1.76e-14 ***
num_eduhead     6.884e-02  1.970e-03  34.945  < 2e-16 ***
migration       2.669e-02  2.235e-02   1.194    0.233    
y2012          -2.481e-01  1.748e-02 -14.194  < 2e-16 ***
y2014          -1.031e-01  1.702e-02  -6.060 1.44e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.525 on 5724 degrees of freedom
Multiple R-squared:  0.3059,	Adjusted R-squared:  0.3046 
F-statistic: 229.3 on 11 and 5724 DF,  p-value: < 2.2e-16
# --- Table 7.3 FEM (within)
pdat <- pdata.frame(df, index = c('id', 'year'))

fem <- plm(f1, data = pdat, model = 'within')

print(summary(fem))
Output
Oneway (individual) effect Within Model

Call:
plm(formula = f1, data = pdat, model = "within")

Balanced Panel: n = 1912, T = 3, N = 5736

Residuals:
    Min.  1st Qu.   Median  3rd Qu.     Max. 
-1.40108 -0.17845 -0.00189  0.16833  1.86875 

Coefficients:
                  Estimate  Std. Error t-value  Pr(>|t|)    
HHsize         -5.4613e-02  8.5426e-03 -6.3930 1.823e-10 ***
agehead         3.6042e-02  6.9928e-03  5.1542 2.676e-07 ***
children_ratio -3.7395e-01  6.4171e-02 -5.8274 6.097e-09 ***
elderly_ratio  -7.1015e-02  5.1251e-02 -1.3856 0.1659388    
genderhead      1.4238e-01  4.3766e-02  3.2531 0.0011515 ** 
female_ratio   -5.7670e-02  6.1107e-02 -0.9438 0.3453538    
agehead2       -2.4238e-04  6.3041e-05 -3.8448 0.0001226 ***
num_eduhead     2.9936e-02  4.5695e-03  6.5513 6.467e-11 ***
migration       1.3700e-01  1.9505e-02  7.0238 2.545e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Total Sum of Squares:    549.99
Residual Sum of Squares: 499.83
R-Squared:      0.091205
Adj. R-Squared: -0.36617
F-statistic: 42.5407 on 9 and 3815 DF, p-value: < 2.22e-16
N <- length(unique(df$id)); Tn <- nrow(df); K <- length(xvar)

sigma_e2 <- sum(residuals(fem)^2) / (Tn - N - K)

fe <- fixef(fem)                       # alpha_i = ybar_i - xbar_i b

sigma_u2 <- max(var(as.numeric(fe)), 0)

rho <- sigma_u2 / (sigma_u2 + sigma_e2)

cat(sprintf('sigma_u = %.8f\nsigma_e = %.8f\nrho     = %.8f\n', sqrt(sigma_u2), sqrt(sigma_e2), rho))
Output
sigma_u = 0.49347037
sigma_e = 0.36196155
rho     = 0.65018435
const_fem <- mean(as.numeric(fe))

xbar <- colMeans(df[xvar])

se_const <- sqrt(as.numeric(t(xbar) %*% vcov(fem) %*% xbar))

cat(sprintf('_cons = %.7f  SE = %.7f  t = %.3f\n', const_fem, se_const, const_fem / se_const))
Output
_cons = 8.7324686  SE = 0.1999724  t = 43.668
# --- Table 7.4 FEM with cluster-robust SE
fem_rob <- coeftest(fem, vcov = vcovHC(fem, type = 'HC1', cluster = 'group'))

print(fem_rob)
Output
t test of coefficients:

                  Estimate  Std. Error t value  Pr(>|t|)    
HHsize         -5.4613e-02  1.0088e-02 -5.4136 6.559e-08 ***
agehead         3.6042e-02  9.8902e-03  3.6442 0.0002718 ***
children_ratio -3.7395e-01  6.3189e-02 -5.9180 3.546e-09 ***
elderly_ratio  -7.1015e-02  5.7360e-02 -1.2381 0.2157726    
genderhead      1.4238e-01  5.0234e-02  2.8343 0.0046174 ** 
female_ratio   -5.7670e-02  7.0950e-02 -0.8128 0.4163658    
agehead2       -2.4238e-04  8.8136e-05 -2.7501 0.0059862 ** 
num_eduhead     2.9936e-02  5.2620e-03  5.6891 1.373e-08 ***
migration       1.3700e-01  1.9861e-02  6.8979 6.154e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# --- Table 7.5 REM
rem <- plm(f1, data = pdat, model = 'random')

print(summary(rem))
Output
Oneway (individual) effect Random Effect Model 
   (Swamy-Arora's transformation)

Call:
plm(formula = f1, data = pdat, model = "random")

Balanced Panel: n = 1912, T = 3, N = 5736

Effects:
                 var std.dev share
idiosyncratic 0.1310  0.3620 0.465
individual    0.1507  0.3883 0.535
theta: 0.5261

Residuals:
   Min. 1st Qu.  Median 3rd Qu.    Max. 
-1.5636 -0.2317 -0.0092  0.2170  2.5243 

Coefficients:
                  Estimate  Std. Error  z-value  Pr(>|z|)    
(Intercept)     8.7458e+00  1.1960e-01  73.1247 < 2.2e-16 ***
HHsize         -6.6696e-02  6.2284e-03 -10.7084 < 2.2e-16 ***
agehead         3.6004e-02  4.3017e-03   8.3697 < 2.2e-16 ***
children_ratio -3.1963e-01  4.9532e-02  -6.4530 1.096e-10 ***
elderly_ratio  -2.0669e-01  3.9379e-02  -5.2488 1.531e-07 ***
genderhead      1.3157e-01  2.3902e-02   5.5045 3.702e-08 ***
female_ratio   -1.5044e-01  4.3119e-02  -3.4888 0.0004851 ***
agehead2       -2.8313e-04  3.9237e-05  -7.2159 5.358e-13 ***
num_eduhead     5.9828e-02  2.5232e-03  23.7113 < 2.2e-16 ***
migration       1.2379e-01  1.7739e-02   6.9783 2.989e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Total Sum of Squares:    937.09
Residual Sum of Squares: 767.03
R-Squared:      0.18148
Adj. R-Squared: 0.18019
Chisq: 1269.54 on 9 DF, p-value: < 2.22e-16
ei <- ercomp(rem)$sigma2

sigma_u2_rem <- ei['id']; sigma_e2_rem <- ei['idios']

cat(sprintf('sigma_u = %.8f\nsigma_e = %.8f\nrho     = %.8f\n', sqrt(sigma_u2_rem),
            sqrt(sigma_e2_rem), sigma_u2_rem / (sigma_u2_rem + sigma_e2_rem)))
Output
sigma_u = 0.38826470
sigma_e = 0.36196155
rho     = 0.53501724
# --- Table 7.6 REM with cluster-robust SE
print(coeftest(rem, vcov = vcovHC(rem, type = 'HC1', cluster = 'group')))
Output
t test of coefficients:

                  Estimate  Std. Error t value  Pr(>|t|)    
(Intercept)     8.7458e+00  1.2600e-01 69.4122 < 2.2e-16 ***
HHsize         -6.6696e-02  6.9889e-03 -9.5432 < 2.2e-16 ***
agehead         3.6004e-02  4.8020e-03  7.4977 7.486e-14 ***
children_ratio -3.1963e-01  5.1310e-02 -6.2294 5.017e-10 ***
elderly_ratio  -2.0669e-01  4.4039e-02 -4.6934 2.749e-06 ***
genderhead      1.3157e-01  2.4971e-02  5.2690 1.422e-07 ***
female_ratio   -1.5044e-01  4.7415e-02 -3.1728  0.001518 ** 
agehead2       -2.8313e-04  4.4319e-05 -6.3885 1.807e-10 ***
num_eduhead     5.9828e-02  2.7456e-03 21.7903 < 2.2e-16 ***
migration       1.2379e-01  1.7494e-02  7.0762 1.659e-12 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# --- Table 7.8 Model selection tests
# F test for fixed effects (pooled vs FE)
print(pFtest(fem, plm(f1, data = pdat, model = 'pooling')))
Output
	F test for individual effects

data:  f1
F = 4.5288, df1 = 1911, df2 = 3815, p-value < 2.2e-16
alternative hypothesis: significant effects
# Breusch-Pagan LM (manual, as in notebook)
e <- residuals(pooled)

n <- nrow(df); Tbar <- n / N

sum_group_sq <- sum(tapply(e, df$id, sum)^2); sum_total_sq <- sum(e^2)

LM <- n / (2 * (Tbar - 1)) * (sum_group_sq / sum_total_sq - 1)^2

cat(sprintf('LM (chibar2) = %.4f, p = %.4f\n', LM, 1 - pchisq(LM, 1)))
Output
LM (chibar2) = 1560.6864, p = 0.0000
# Hausman (pinv of V_diff as in notebook)
b_diff <- coef(fem) - coef(rem)[names(coef(fem))]

V_diff <- vcov(fem) - vcov(rem)[names(coef(fem)), names(coef(fem))]

sv <- svd(V_diff); pos <- sv$d > max(dim(V_diff)) * max(sv$d) * .Machine$double.eps

Vinv <- sv$v[, pos, drop = FALSE] %*% diag(1 / sv$d[pos], sum(pos)) %*% t(sv$u[, pos, drop = FALSE])

chi2 <- as.numeric(t(b_diff) %*% Vinv %*% b_diff)

cat(sprintf('Hausman chi2(%d) = %.2f, p = %.4f\n', length(b_diff), chi2, 1 - pchisq(chi2, length(b_diff))))
Output
Hausman chi2(9) = 140.12, p = 0.0000
print(phtest(fem, rem))   # plm's built-in version for reference
Output
	Hausman Test

data:  f1
chisq = 140.12, df = 9, p-value < 2.2e-16
alternative hypothesis: one model is inconsistent
# --- Comparison table
cmp <- data.frame(Pooled = coef(pooled),
                  FEM = c(const_fem, coef(fem))[match(names(coef(pooled)), c('(Intercept)', names(coef(fem))))],
                  REM = coef(rem)[names(coef(pooled))])

print(round(cmp, 6))
Output
                  Pooled       FEM       REM
(Intercept)     8.777095  8.732469  8.745807
HHsize         -0.072745 -0.054613 -0.066696
agehead         0.034190  0.036042  0.036004
children_ratio -0.303980 -0.373950 -0.319630
elderly_ratio  -0.271504 -0.071015 -0.206692
genderhead      0.130080  0.142377  0.131570
female_ratio   -0.188046 -0.057670 -0.150437
agehead2       -0.000267 -0.000242 -0.000283
num_eduhead     0.069775  0.029936  0.059828
migration       0.095824  0.137002  0.123787
cat(sprintf('R2 pooled = %.4f, adjR2 = %.4f\nFEM within R2 = %.4f\n',
            summary(pooled)$r.squared, summary(pooled)$adj.r.squared, summary(fem)$r.squared['rsq']))
Output
R2 pooled = 0.2814, adjR2 = 0.2802
FEM within R2 = 0.0912
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chương 7" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chương 7" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 7                                                 */
/*      File Name:  chapter7.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Panel data                                    */  
/*      Input File:     panel121416                               */  
/*      Output File:    chapter7.log                              */  
/******************************************************************/ 

log using chapter7.log, text replace

use "$link\panel121416.dta",clear

global xvarpanel "HHsize agehead children_ratio elderly_ratio genderhead female_ratio agehead2 num_eduhead migration"

**# Mô hình Pooled OLS

reg ln_per_expenditure $xvarpanel

**# Mô hình Pooled OLS với biến giả năm

gen _2012 =(year==2012)

gen _2014 =(year==2014)

reg ln_per_expenditure $xvarpanel _2012 _2014

**# Mô hình FEM

xtset hhid year

xtreg ln_per_expenditure $xvarpanel, fe

xtreg ln_per_expenditure $xvarpanel, fe robust

**# Mô hình REM

xtreg ln_per_expenditure $xvarpanel

xtreg ln_per_expenditure $xvarpanel, robust

**# Sự phù hợp của mô hình FEM và REM

quietly xtreg ln_per_expenditure $xvarpanel

xttest0

quietly xtreg ln_per_expenditure $xvarpanel ,fe

est store FEM

quietly xtreg ln_per_expenditure $xvarpanel

est store REM

hausman FEM REM

log close

Files: Notebook · Open in Colab · R script · Stata do-file

Data: panel121416.dta

Chapter 8 Count data

Poisson, overdispersion, negative binomial, incidence-rate ratios, marginal effects.

df, meta = pyreadstat.read_dta(
    "rawdata/remittances_adolescents.dta",
    encoding="latin1",
)
df.head()
Output
tinh huyen xa diaban hoso adolescent_gender m1ama1 HHsize adolescent6_18_ratio adolescent0_15_ratio outpatient inpatient domestic_remittances overseas_remittances remittances crop_land
0 1 1 22 39 14 1 5 5.0 0.200000 0.200000 1.0 0.0 1.0 0.0 5000.0 0.0
1 1 1 34 10 19 0 3 4.0 0.250000 0.500000 3.0 0.0 1.0 0.0 15000.0 0.0
2 1 2 55 14 19 1 4 4.0 0.500000 0.500000 1.0 0.0 1.0 0.0 4500.0 0.0
3 1 2 67 16 14 1 3 4.0 0.250000 0.500000 3.0 0.0 1.0 0.0 8000.0 0.0
4 1 2 67 16 15 1 3 3.0 0.333333 0.333333 1.0 0.0 1.0 0.0 2000.0 0.0
# Tạo biến tương tác
df["overseas_adolescent_gender"] = df["overseas_remittances"] * df["adolescent_gender"]
df["domestic_adolescent_gender"] = df["domestic_remittances"] * df["adolescent_gender"]

# Danh sách biến độc lập
xvars = [
    "adolescent6_18_ratio",
    "adolescent0_15_ratio",
    "HHsize",
    "overseas_remittances",
    "domestic_remittances",
    "overseas_adolescent_gender",
    "domestic_adolescent_gender",
    "crop_land",
]

y = df["outpatient"]
X = sm.add_constant(df[xvars])

print("Số quan sát:", len(df))
print("Biến phụ thuộc: outpatient")
print("Biến độc lập:", xvars)
Output
Số quan sát: 1731
Biến phụ thuộc: outpatient
Biến độc lập: ['adolescent6_18_ratio', 'adolescent0_15_ratio', 'HHsize', 'overseas_remittances', 'domestic_remittances', 'overseas_adolescent_gender', 'domestic_adolescent_gender', 'crop_land']
# Hồi quy OLS
ols_model = sm.OLS(y, X).fit()
print(ols_model.summary())
Output
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             outpatient   R-squared:                       0.012
Model:                            OLS   Adj. R-squared:                  0.007
Method:                 Least Squares   F-statistic:                     2.582
Date:                Wed, 08 Apr 2026   Prob (F-statistic):            0.00839
Time:                        18:17:44   Log-Likelihood:                -4114.5
No. Observations:                1731   AIC:                             8247.
Df Residuals:                    1722   BIC:                             8296.
Df Model:                           8                                         
Covariance Type:            nonrobust                                         
==============================================================================================
                                 coef    std err          t      P>|t|      [0.025      0.975]
----------------------------------------------------------------------------------------------
const                          3.0686      0.358      8.561      0.000       2.366       3.772
adolescent6_18_ratio          -0.8773      0.498     -1.761      0.078      -1.854       0.100
adolescent0_15_ratio          -0.1077      0.425     -0.254      0.800      -0.940       0.725
HHsize                         0.0034      0.051      0.068      0.946      -0.096       0.103
overseas_remittances          -0.0444      0.521     -0.085      0.932      -1.066       0.977
domestic_remittances          -0.2402      0.183     -1.315      0.189      -0.598       0.118
overseas_adolescent_gender     0.9585      0.703      1.364      0.173      -0.420       2.337
domestic_adolescent_gender    -0.1931      0.140     -1.382      0.167      -0.467       0.081
crop_land                     -0.3621      0.131     -2.774      0.006      -0.618      -0.106
==============================================================================
Omnibus:                     2185.251   Durbin-Watson:                   1.766
Prob(Omnibus):                  0.000   Jarque-Bera (JB):           470481.294
Skew:                           6.575   Prob(JB):                         0.00
Kurtosis:                      82.688   Cond. No.                         64.8
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
# Histogram phân phối outpatient
plt.figure(figsize=(10, 6))
counts = df["outpatient"].value_counts().sort_index()
plt.bar(counts.index, counts.values, color=palette[1], edgecolor="white", linewidth=0.5)
plt.xlabel(" ", fontsize=12)
plt.ylabel("Số lần sử dụng dịch vụ ngoại trú của trẻ", fontsize=12)
plt.title("Hình 8.1 – Biểu đồ phân phối số lần sử dụng dịch vụ ngoại trú\ncủa trẻ em và thanh thiếu niên năm 2016", fontsize=13)
plt.tight_layout()
plt.show()
OutputOutput of chapter 8, cell 13
# Thống kê mô tả chi tiết
from scipy import stats
print(df["outpatient"].describe(percentiles=[0.01, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99]).round(1))

skew = stats.skew(df["outpatient"].dropna())
kurt = stats.kurtosis(df["outpatient"].dropna(), fisher=False)

print(f"Skewness : {skew:.6f}")
print(f"Kurtosis : {kurt:.6f}")

# Kiểm định Jarque-Bera
jb_stat, jb_p = stats.jarque_bera(df["outpatient"].dropna())
print(f"\nJarque-Bera statistic : {jb_stat:.2f}")
print(f"P-value               : {jb_p:.4f}")
print("→ Bác bỏ H₀ (phân phối chuẩn): biến outpatient KHÔNG tuân theo phân phối chuẩn")
Output
count    1731.0
mean        2.3
std         2.6
min         0.0
1%          0.0
5%          0.0
10%         1.0
25%         1.0
50%         2.0
75%         3.0
90%         4.0
95%         6.0
99%        10.0
max        45.0
Name: outpatient, dtype: float64
Skewness : 6.605876
Kurtosis : 83.074724

Jarque-Bera statistic : 475052.16
P-value               : 0.0000
→ Bác bỏ H₀ (phân phối chuẩn): biến outpatient KHÔNG tuân theo phân phối chuẩn
# Hồi quy Poisson
poisson_model = sm.GLM(y, X, family=sm.families.Poisson()).fit()
print(poisson_model.summary())
Output
                 Generalized Linear Model Regression Results                  
==============================================================================
Dep. Variable:             outpatient   No. Observations:                 1731
Model:                            GLM   Df Residuals:                     1722
Model Family:                 Poisson   Df Model:                            8
Link Function:                    Log   Scale:                          1.0000
Method:                          IRLS   Log-Likelihood:                -3619.1
Date:                Wed, 08 Apr 2026   Deviance:                       3155.7
Time:                        18:17:47   Pearson chi2:                 4.94e+03
No. Iterations:                     5   Pseudo R-squ. (CS):            0.03421
Covariance Type:            nonrobust                                         
==============================================================================================
                                 coef    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------------------
const                          1.1597      0.090     12.935      0.000       0.984       1.335
adolescent6_18_ratio          -0.3802      0.126     -3.007      0.003      -0.628      -0.132
adolescent0_15_ratio          -0.0486      0.107     -0.452      0.651      -0.259       0.162
HHsize                         0.0014      0.013      0.111      0.911      -0.024       0.027
overseas_remittances          -0.0175      0.128     -0.137      0.891      -0.269       0.233
domestic_remittances          -0.1000      0.045     -2.233      0.026      -0.188      -0.012
overseas_adolescent_gender     0.3440      0.163      2.115      0.034       0.025       0.663
domestic_adolescent_gender    -0.0855      0.036     -2.380      0.017      -0.156      -0.015
crop_land                     -0.1612      0.034     -4.782      0.000      -0.227      -0.095
==============================================================================================
# Incidence Rate Ratios (IRR) – tương đương lệnh ,irr trong Stata
print("=" * 65)
print("Incidence Rate Ratios (IRR) – Mô hình Poisson")
print("=" * 65)
irr    = np.exp(poisson_model.params)
ci     = np.exp(poisson_model.conf_int())
pvals  = poisson_model.pvalues

irr_df = pd.DataFrame({
    "IRR"   : irr,
    "CI 2.5%" : ci[0],
    "CI 97.5%": ci[1],
    "P>|z|" : pvals,
})
print(irr_df.to_string(float_format="{:.6f}".format))
Output
=================================================================
Incidence Rate Ratios (IRR) – Mô hình Poisson
=================================================================
                                IRR  CI 2.5%  CI 97.5%    P>|z|
const                      3.189064 2.675124  3.801739 0.000000
adolescent6_18_ratio       0.683723 0.533627  0.876037 0.002643
adolescent0_15_ratio       0.952607 0.771705  1.175915 0.651369
HHsize                     1.001434 0.976493  1.027012 0.911326
overseas_remittances       0.982647 0.764520  1.263008 0.891275
domestic_remittances       0.904871 0.828853  0.987860 0.025563
overseas_adolescent_gender 1.410636 1.025590  1.940244 0.034403
domestic_adolescent_gender 0.918084 0.855678  0.985040 0.017330
crop_land                  0.851112 0.796693  0.909247 0.000002
# Marginal Effects giống Stata
mfx = poisson_model.get_margeff(at='mean', dummy=True)

# In bảng kết quả
print("\nBảng 8.3 – Marginal Effects after Poisson (Stata-style)")
print(mfx.summary())
Output
Bảng 8.3 – Marginal Effects after Poisson (Stata-style)
         GLM Marginal Effects        
=====================================
Dep. Variable:             outpatient
Method:                          dydx
At:                              mean
==============================================================================================
                                dy/dx    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------------------
adolescent6_18_ratio          -0.8594      0.286     -3.010      0.003      -1.419      -0.300
adolescent0_15_ratio          -0.1097      0.243     -0.452      0.651      -0.586       0.366
HHsize                         0.0032      0.029      0.111      0.911      -0.054       0.060
overseas_remittances          -0.0392      0.285     -0.138      0.890      -0.597       0.519
domestic_remittances          -0.2336      0.108     -2.161      0.031      -0.446      -0.022
overseas_adolescent_gender     0.9225      0.513      1.800      0.072      -0.082       1.927
domestic_adolescent_gender    -0.1918      0.080     -2.398      0.016      -0.349      -0.035
crop_land                     -0.3591      0.074     -4.862      0.000      -0.504      -0.214
==============================================================================================
# Kiểm định quá phân tán (overdispersion test)
yhat  = poisson_model.predict()
yhat2 = yhat ** 2
e     = y - yhat
e2    = e ** 2
diff  = e2 - y

# Hồi quy diff ~ yhat2, không có hằng số
disp_model = sm.OLS(diff, yhat2).fit()
print("Bảng 8.4 – Kiểm định giả thuyết phân tán bằng nhau")
print(disp_model.summary())

alpha_hat = disp_model.params.iloc[0]
p_val     = disp_model.pvalues.iloc[0]
print(f"\nHệ số alpha = {alpha_hat:.4f}  |  P-value = {p_val:.4f}")
if p_val < 0.05:
    print("→ Có overdispersion: bác bỏ H₀ → Mô hình Poisson KHÔNG phù hợp")
else:
    print("→ Không có overdispersion: chấp nhận H₀ → Mô hình Poisson phù hợp")
Output
Bảng 8.4 – Kiểm định giả thuyết phân tán bằng nhau
                                 OLS Regression Results                                
=======================================================================================
Dep. Variable:             outpatient   R-squared (uncentered):                   0.007
Model:                            OLS   Adj. R-squared (uncentered):              0.007
Method:                 Least Squares   F-statistic:                              12.35
Date:                Wed, 08 Apr 2026   Prob (F-statistic):                    0.000451
Time:                        18:17:47   Log-Likelihood:                         -9528.4
No. Observations:                1731   AIC:                                  1.906e+04
Df Residuals:                    1730   BIC:                                  1.906e+04
Df Model:                           1                                                  
Covariance Type:            nonrobust                                                  
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
x1             0.9214      0.262      3.515      0.000       0.407       1.436
==============================================================================
Omnibus:                     4118.406   Durbin-Watson:                   2.006
Prob(Omnibus):                  0.000   Jarque-Bera (JB):         26346324.153
Skew:                          23.316   Prob(JB):                         0.00
Kurtosis:                     605.588   Cond. No.                         1.00
==============================================================================

Notes:
[1] R² is computed without centering (uncentered) since the model does not contain a constant.
[2] Standard Errors assume that the covariance matrix of the errors is correctly specified.

Hệ số alpha = 0.9214  |  P-value = 0.0005
→ Có overdispersion: bác bỏ H₀ → Mô hình Poisson KHÔNG phù hợp
# Hồi quy Negative Binomial – dùng sm.NegativeBinomial (ước lượng alpha từ dữ liệu)
nbreg_model = sm.NegativeBinomial(y, X).fit(disp=False)
print("Bảng 8.5 – Hồi quy nhị phân âm (NBREG)")
print(nbreg_model.summary())
# In thêm alpha – alpha trong statsmodels = alpha trong Stata
alpha_val = nbreg_model.params['alpha']
print(f"\nalpha (overdispersion) = {alpha_val:.7f}")
print(f"LR test alpha=0: LR chi2(1) = {2*(nbreg_model.llf - (sm.Poisson(y, X).fit(disp=False).llf)):.2f}")
Output
Bảng 8.5 – Hồi quy nhị phân âm (NBREG)
                     NegativeBinomial Regression Results                      
==============================================================================
Dep. Variable:             outpatient   No. Observations:                 1731
Model:               NegativeBinomial   Df Residuals:                     1722
Method:                           MLE   Df Model:                            8
Date:                Wed, 08 Apr 2026   Pseudo R-squ.:                0.005037
Time:                        18:17:48   Log-Likelihood:                -3326.3
converged:                       True   LL-Null:                       -3343.1
Covariance Type:            nonrobust   LLR p-value:                 4.647e-05
==============================================================================================
                                 coef    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------------------
const                          1.1612      0.121      9.568      0.000       0.923       1.399
adolescent6_18_ratio          -0.3862      0.170     -2.268      0.023      -0.720      -0.052
adolescent0_15_ratio          -0.0443      0.146     -0.303      0.762      -0.331       0.242
HHsize                         0.0028      0.017      0.161      0.872      -0.031       0.036
overseas_remittances          -0.0225      0.173     -0.130      0.897      -0.362       0.317
domestic_remittances          -0.1055      0.061     -1.732      0.083      -0.225       0.014
overseas_adolescent_gender     0.3392      0.226      1.499      0.134      -0.104       0.783
domestic_adolescent_gender    -0.0869      0.048     -1.822      0.069      -0.180       0.007
crop_land                     -0.1649      0.045     -3.680      0.000      -0.253      -0.077
alpha                          0.3404      0.024     14.034      0.000       0.293       0.388
==============================================================================================

alpha (overdispersion) = 0.3404156
LR test alpha=0: LR chi2(1) = 585.61
# IRR của mô hình Negative Binomial
print("=" * 65)
print("Incidence Rate Ratios (IRR) – Mô hình Negative Binomial")
print("=" * 65)

# Lấy params không bao gồm alpha (param cuối)
params_nb_main = nbreg_model.params[:-1]   # bỏ 'alpha'
ci_nb    = nbreg_model.conf_int().iloc[:-1]
pvals_nb = nbreg_model.pvalues[:-1]

irr_nb   = np.exp(params_nb_main)
ci_nb_exp = np.exp(ci_nb)

irr_nb_df = pd.DataFrame({
    "IRR"     : irr_nb,
    "CI 2.5%" : ci_nb_exp.iloc[:, 0],
    "CI 97.5%": ci_nb_exp.iloc[:, 1],
    "P>|z|"   : pvals_nb,
})
print(irr_nb_df.to_string(float_format="{:.6f}".format))
Output
=================================================================
Incidence Rate Ratios (IRR) – Mô hình Negative Binomial
=================================================================
                                IRR  CI 2.5%  CI 97.5%    P>|z|
const                      3.193738 2.517621  4.051429 0.000000
adolescent6_18_ratio       0.679627 0.486781  0.948873 0.023318
adolescent0_15_ratio       0.956650 0.718420  1.273878 0.761659
HHsize                     1.002768 0.969663  1.037003 0.871811
overseas_remittances       0.977762 0.696410  1.372780 0.896646
domestic_remittances       0.899885 0.798621  1.013989 0.083295
overseas_adolescent_gender 1.403793 0.901001  2.187162 0.133827
domestic_adolescent_gender 0.916807 0.835004  1.006623 0.068526
crop_land                  0.847954 0.776654  0.925801 0.000233
# Marginal effects – Negative Binomial
from scipy import stats
mfx1 = nbreg_model.get_margeff(at='mean', method='dydx', dummy=True)
print("\nBảng 8.6 – Marginal Effects after Negative Binomial")
print(mfx1.summary())
Output
Bảng 8.6 – Marginal Effects after Negative Binomial
  NegativeBinomial Marginal Effects  
=====================================
Dep. Variable:             outpatient
Method:                          dydx
At:                              mean
==============================================================================================
                                dy/dx    std err          z      P>|z|      [0.025      0.975]
----------------------------------------------------------------------------------------------
adolescent6_18_ratio          -0.8729      0.385     -2.268      0.023      -1.627      -0.119
adolescent0_15_ratio          -0.1002      0.330     -0.303      0.762      -0.747       0.547
HHsize                         0.0062      0.039      0.161      0.872      -0.070       0.082
overseas_remittances          -0.0503      0.383     -0.131      0.896      -0.801       0.701
domestic_remittances          -0.2470      0.148     -1.672      0.094      -0.536       0.042
overseas_adolescent_gender     0.9071      0.710      1.278      0.201      -0.484       2.298
domestic_adolescent_gender    -0.1949      0.106     -1.835      0.067      -0.403       0.013
crop_land                     -0.3672      0.098     -3.733      0.000      -0.560      -0.174
==============================================================================================
# Likelihood Ratio Test: Poisson vs Negative Binomial
from scipy.stats import chi2

ll_poisson = poisson_model.llf
ll_nbreg   = nbreg_model.llf

LR_stat = 2 * (ll_nbreg - ll_poisson)
p_lr    = 1 - chi2.cdf(LR_stat, df=1)

print("Likelihood-Ratio Test: Poisson nested within Negative Binomial")
print("-" * 55)
print(f"Log-likelihood Poisson      : {ll_poisson:.4f}")
print(f"Log-likelihood Neg. Binomial: {ll_nbreg:.4f}")
print(f"LR chi2(1)                  : {LR_stat:.2f}")
print(f"Prob > chi2                 : {p_lr:.4f}")

if p_lr < 0.05:
    print("\n→ Bác bỏ H₀: Mô hình Negative Binomial PHÙ HỢP HƠN Poisson")
else:
    print("\n→ Không bác bỏ H₀: Mô hình Poisson phù hợp")
Output
Likelihood-Ratio Test: Poisson nested within Negative Binomial
-------------------------------------------------------
Log-likelihood Poisson      : -3619.0688
Log-likelihood Neg. Binomial: -3326.2636
LR chi2(1)                  : 585.61
Prob > chi2                 : 0.0000

→ Bác bỏ H₀: Mô hình Negative Binomial PHÙ HỢP HƠN Poisson
# Bảng tóm tắt so sánh ba mô hình
params_ols  = ols_model.params
se_ols      = ols_model.bse
params_pois = poisson_model.params
se_pois     = poisson_model.bse

vars_to_show = xvars  # bỏ const

comparison = pd.DataFrame(index=vars_to_show)
comparison["OLS Coef"]    = params_ols[vars_to_show]
comparison["OLS SE"]      = se_ols[vars_to_show]
comparison["Poisson Coef"]= params_pois[vars_to_show]
comparison["Poisson SE"]  = se_pois[vars_to_show]
comparison["NBREG Coef"]  = params_nb_main[vars_to_show]
comparison["NBREG SE"]    = nbreg_model.bse[:-1][vars_to_show]

print("Bảng so sánh hệ số hồi quy: OLS | Poisson | Negative Binomial")
print("=" * 85)
print(comparison.to_string(float_format="{:.4f}".format))

print("\n--- Thống kê mô hình ---")
print(f"OLS   : R² = {ols_model.rsquared:.4f}")
print(f"Poisson: Log-Lik = {poisson_model.llf:.2f}, Pseudo R² = {1 - poisson_model.llf/poisson_model.llnull:.4f}")
# NBREG pseudo R² = McFadden
print(f"NBREG  : Log-Lik = {nbreg_model.llf:.2f}, Pseudo R² = {nbreg_model.prsquared:.4f}")
Output
Bảng so sánh hệ số hồi quy: OLS | Poisson | Negative Binomial
=====================================================================================
                            OLS Coef  OLS SE  Poisson Coef  Poisson SE  NBREG Coef  NBREG SE
adolescent6_18_ratio         -0.8773  0.4981       -0.3802      0.1265     -0.3862    0.1703
adolescent0_15_ratio         -0.1077  0.4246       -0.0486      0.1075     -0.0443    0.1461
HHsize                        0.0034  0.0506        0.0014      0.0129      0.0028    0.0171
overseas_remittances         -0.0444  0.5209       -0.0175      0.1281     -0.0225    0.1731
domestic_remittances         -0.2402  0.1827       -0.1000      0.0448     -0.1055    0.0609
overseas_adolescent_gender    0.9585  0.7027        0.3440      0.1626      0.3392    0.2262
domestic_adolescent_gender   -0.1931  0.1397       -0.0855      0.0359     -0.0869    0.0477
crop_land                    -0.3621  0.1305       -0.1612      0.0337     -0.1649    0.0448

--- Thống kê mô hình ---
OLS   : R² = 0.0119
Poisson: Log-Lik = -3619.07, Pseudo R² = 0.0083
NBREG  : Log-Lik = -3326.26, Pseudo R² = 0.0050
# Chapter 8 - Count Data Models
# Install once: install.packages(c('haven','readxl','lmtest','sandwich','plm','nnet','MASS','car','ggplot2','broom','AER'))
lib <- Sys.getenv('R_LIBS_USER')

if (nzchar(lib)) .libPaths(c(lib, .libPaths()))

library(haven); library(MASS); library(ggplot2)

# Point data_dir at the repo's data folder (or set env var DATA_DIR)
data_dir <- Sys.getenv('DATA_DIR', 'rawdata')

dir.create('figures', showWarnings = FALSE)

# --- Read data
df <- as.data.frame(read_dta(file.path(data_dir, 'remittances_adolescents.dta')))

head(df)
Output
  tinh huyen  xa diaban hoso adolescent_gender m1ama1 HHsize
1    1     1  22     39   14                 1      5      5
2    1     1  34     10   19                 0      3      4
3    1     2  55     14   19                 1      4      4
4    1     2  67     16   14                 1      3      4
5    1     2  67     16   15                 1      3      3
6    1     6 190     60   13                 0      5      6
  adolescent6_18_ratio adolescent0_15_ratio outpatient inpatient
1            0.2000000            0.2000000          1         0
2            0.2500000            0.5000000          3         0
3            0.5000000            0.5000000          1         0
4            0.2500000            0.5000000          3         0
5            0.3333333            0.3333333          1         0
6            0.1666667            0.3333333          1         0
  domestic_remittances overseas_remittances remittances crop_land
1                    1                    0        5000         0
2                    1                    0       15000         0
3                    1                    0        4500         0
4                    1                    0        8000         0
5                    1                    0        2000         0
6                    1                    0       15000         0
# --- 8.2 Interaction variables
df$overseas_adolescent_gender <- df$overseas_remittances * df$adolescent_gender

df$domestic_adolescent_gender <- df$domestic_remittances * df$adolescent_gender

xvars <- c('adolescent6_18_ratio','adolescent0_15_ratio','HHsize','overseas_remittances',
           'domestic_remittances','overseas_adolescent_gender','domestic_adolescent_gender','crop_land')

fml <- reformulate(xvars, 'outpatient')

cat('Observations:', nrow(df), '\n')
Output
Observations: 1731 
# --- 8.3 OLS (Table 8.1)
ols <- lm(fml, data = df)

print(summary(ols))
Output
Call:
lm(formula = fml, data = df)

Residuals:
   Min     1Q Median     3Q    Max 
-3.504 -1.339 -0.569  0.650 42.410 

Coefficients:
                            Estimate Std. Error t value Pr(>|t|)    
(Intercept)                 3.068628   0.358454   8.561   <2e-16 ***
adolescent6_18_ratio       -0.877266   0.498140  -1.761   0.0784 .  
adolescent0_15_ratio       -0.107689   0.424604  -0.254   0.7998    
HHsize                      0.003431   0.050578   0.068   0.9459    
overseas_remittances       -0.044360   0.520882  -0.085   0.9321    
domestic_remittances       -0.240169   0.182668  -1.315   0.1888    
overseas_adolescent_gender  0.958497   0.702694   1.364   0.1727    
domestic_adolescent_gender -0.193109   0.139722  -1.382   0.1671    
crop_land                  -0.362146   0.130549  -2.774   0.0056 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.613 on 1722 degrees of freedom
Multiple R-squared:  0.01185,	Adjusted R-squared:  0.007262 
F-statistic: 2.582 on 8 and 1722 DF,  p-value: 0.008388
# Figure 8.1
p <- ggplot(df, aes(outpatient)) + geom_bar(fill = '#a31414') +
  labs(x = NULL, y = 'Outpatient visits', title = 'Figure 8.1 - Distribution of outpatient visits')

ggsave('figures/fig8_1.png', p, width = 8, height = 5)
OutputR output: fig8_1.png
y <- df$outpatient

print(round(quantile(y, c(.01,.05,.1,.25,.5,.75,.9,.95,.99)), 1))
Output
 1%  5% 10% 25% 50% 75% 90% 95% 99% 
  0   0   1   1   2   3   4   6  10 
m <- mean(y); n <- length(y)

skew <- mean((y - m)^3) / mean((y - m)^2)^1.5

kurt <- mean((y - m)^4) / mean((y - m)^2)^2

cat(sprintf('Skewness: %.6f\nKurtosis: %.6f\n', skew, kurt))
Output
Skewness: 6.605876
Kurtosis: 83.074724
jb <- n / 6 * (skew^2 + (kurt - 3)^2 / 4)

cat(sprintf('Jarque-Bera: %.2f, p = %.4f\n', jb, 1 - pchisq(jb, 2)))
Output
Jarque-Bera: 475052.16, p = 0.0000
# --- 8.4 Poisson (Table 8.2)
pois <- glm(fml, data = df, family = poisson())

print(summary(pois))
Output
Call:
glm(formula = fml, family = poisson(), data = df)

Coefficients:
                            Estimate Std. Error z value Pr(>|z|)    
(Intercept)                 1.159727   0.089660  12.935  < 2e-16 ***
adolescent6_18_ratio       -0.380203   0.126459  -3.007  0.00264 ** 
adolescent0_15_ratio       -0.048553   0.107451  -0.452  0.65137    
HHsize                      0.001433   0.012868   0.111  0.91133    
overseas_remittances       -0.017505   0.128064  -0.137  0.89127    
domestic_remittances       -0.099963   0.044771  -2.233  0.02556 *  
overseas_adolescent_gender  0.344041   0.162642   2.115  0.03440 *  
domestic_adolescent_gender -0.085467   0.035916  -2.380  0.01733 *  
crop_land                  -0.161212   0.033712  -4.782 1.73e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 3215.9  on 1730  degrees of freedom
Residual deviance: 3155.7  on 1722  degrees of freedom
AIC: 7256.1

Number of Fisher Scoring iterations: 5
irr <- exp(cbind(IRR = coef(pois), confint.default(pois)))

print(round(cbind(irr, p = summary(pois)$coefficients[, 4]), 6))
Output
                                IRR    2.5 %   97.5 %        p
(Intercept)                3.189064 2.675125 3.801738 0.000000
adolescent6_18_ratio       0.683723 0.533627 0.876036 0.002642
adolescent0_15_ratio       0.952607 0.771706 1.175915 0.651368
HHsize                     1.001434 0.976493 1.027012 0.911326
overseas_remittances       0.982647 0.764521 1.263007 0.891275
domestic_remittances       0.904871 0.828854 0.987860 0.025563
overseas_adolescent_gender 1.410636 1.025590 1.940244 0.034402
domestic_adolescent_gender 0.918084 0.855678 0.985040 0.017330
crop_land                  0.851112 0.796693 0.909247 0.000002
# Marginal effects at the mean (Table 8.3): beta_k * exp(xbar'b); continuous approximation.
# NOT VERIFIED: Python get_margeff(dummy=True) uses discrete change for 0/1 variables; here derivative is used for all.
me_at_mean <- function(mod) {
  b <- coef(mod)[c('(Intercept)', xvars)]
  xb <- sum(b * c(1, colMeans(df[xvars])))
  b[-1] * exp(xb)
}

print(me_at_mean(pois))
Output
      adolescent6_18_ratio       adolescent0_15_ratio 
              -0.859394084               -0.109746783 
                    HHsize       overseas_remittances 
               0.003239218               -0.039568108 
      domestic_remittances overseas_adolescent_gender 
              -0.225952710                0.777655474 
domestic_adolescent_gender                  crop_land 
              -0.193185679               -0.364397097 
# --- 8.5 Overdispersion test (Table 8.4)
yhat <- fitted(pois)

disp <- lm(I((y - yhat)^2 - y) ~ 0 + I(yhat^2))

print(summary(disp))
Output
Call:
lm(formula = I((y - yhat)^2 - y) ~ 0 + I(yhat^2))

Residuals:
    Min      1Q  Median      3Q     Max 
 -18.34   -6.50   -4.44   -3.67 1747.56 

Coefficients:
          Estimate Std. Error t value Pr(>|t|)    
I(yhat^2)   0.9214     0.2621   3.515 0.000451 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 59.5 on 1730 degrees of freedom
Multiple R-squared:  0.007091,	Adjusted R-squared:  0.006517 
F-statistic: 12.35 on 1 and 1730 DF,  p-value: 0.0004513
# --- 8.6 Negative binomial (Table 8.5)
nb <- glm.nb(fml, data = df)

print(summary(nb))
Output
Call:
glm.nb(formula = fml, data = df, init.theta = 2.937585334, link = log)

Coefficients:
                            Estimate Std. Error z value Pr(>|z|)    
(Intercept)                 1.161202   0.120399   9.645  < 2e-16 ***
adolescent6_18_ratio       -0.386195   0.168715  -2.289 0.022078 *  
adolescent0_15_ratio       -0.044392   0.143572  -0.309 0.757173    
HHsize                      0.002766   0.017145   0.161 0.871834    
overseas_remittances       -0.022230   0.173172  -0.128 0.897856    
domestic_remittances       -0.105495   0.060611  -1.741 0.081767 .  
overseas_adolescent_gender  0.338792   0.226517   1.496 0.134742    
domestic_adolescent_gender -0.086841   0.047643  -1.823 0.068341 .  
crop_land                  -0.164925   0.044625  -3.696 0.000219 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for Negative Binomial(2.9376) family taken to be 1)

    Null deviance: 1694.3  on 1730  degrees of freedom
Residual deviance: 1660.4  on 1722  degrees of freedom
AIC: 6672.5

Number of Fisher Scoring iterations: 1


              Theta:  2.938 
          Std. Err.:  0.209 

 2 x log-likelihood:  -6652.527 
cat(sprintf('alpha = 1/theta = %.7f\n', 1 / nb$theta))
Output
alpha = 1/theta = 0.3404156
irr_nb <- exp(cbind(IRR = coef(nb), confint.default(nb)))

print(round(irr_nb, 6))
Output
                                IRR    2.5 %   97.5 %
(Intercept)                3.193770 2.522432 4.043783
adolescent6_18_ratio       0.679638 0.488278 0.945994
adolescent0_15_ratio       0.956579 0.721959 1.267446
HHsize                     1.002770 0.969634 1.037038
overseas_remittances       0.978015 0.696532 1.373251
domestic_remittances       0.899879 0.799082 1.013389
overseas_adolescent_gender 1.403251 0.900169 2.187493
domestic_adolescent_gender 0.916823 0.835087 1.006558
crop_land                  0.847957 0.776943 0.925462
# Table 8.6
print(me_at_mean(nb))
Output
      adolescent6_18_ratio       adolescent0_15_ratio 
              -0.872846635               -0.100330316 
                    HHsize       overseas_remittances 
               0.006251332               -0.050242841 
      domestic_remittances overseas_adolescent_gender 
              -0.238432339                0.765709572 
domestic_adolescent_gender                  crop_land 
              -0.196271682               -0.372750154 
# --- 8.7 LR test Poisson vs NB
ll_p <- as.numeric(logLik(pois)); ll_nb <- as.numeric(logLik(nb))

LR <- 2 * (ll_nb - ll_p)

cat(sprintf('LL Poisson = %.4f\nLL NB = %.4f\nLR chi2(1) = %.2f, p = %.4f\n', ll_p, ll_nb, LR, 1 - pchisq(LR, 1)))
Output
LL Poisson = -3619.0688
LL NB = -3326.2636
LR chi2(1) = 585.61, p = 0.0000
# --- 8.8 Comparison
cmp <- data.frame(OLS = coef(ols)[xvars], OLS_SE = summary(ols)$coefficients[xvars, 2],
                  Pois = coef(pois)[xvars], Pois_SE = summary(pois)$coefficients[xvars, 2],
                  NB = coef(nb)[xvars], NB_SE = summary(nb)$coefficients[xvars, 2])

print(round(cmp, 4))
Output
                               OLS OLS_SE    Pois Pois_SE      NB  NB_SE
adolescent6_18_ratio       -0.8773 0.4981 -0.3802  0.1265 -0.3862 0.1687
adolescent0_15_ratio       -0.1077 0.4246 -0.0486  0.1075 -0.0444 0.1436
HHsize                      0.0034 0.0506  0.0014  0.0129  0.0028 0.0171
overseas_remittances       -0.0444 0.5209 -0.0175  0.1281 -0.0222 0.1732
domestic_remittances       -0.2402 0.1827 -0.1000  0.0448 -0.1055 0.0606
overseas_adolescent_gender  0.9585 0.7027  0.3440  0.1626  0.3388 0.2265
domestic_adolescent_gender -0.1931 0.1397 -0.0855  0.0359 -0.0868 0.0476
crop_land                  -0.3621 0.1305 -0.1612  0.0337 -0.1649 0.0446
cat(sprintf('OLS R2 = %.4f\nPoisson LL = %.2f, pseudo R2 = %.4f\n', summary(ols)$r.squared, ll_p,
            1 - ll_p / as.numeric(logLik(glm(outpatient ~ 1, data = df, family = poisson())))))
Output
OLS R2 = 0.0119
Poisson LL = -3619.07, pseudo R2 = 0.0083
ll_nb0 <- as.numeric(logLik(glm.nb(outpatient ~ 1, data = df)))

cat(sprintf('NB LL = %.2f, pseudo R2 (McFadden) = %.4f\n', ll_nb, 1 - ll_nb / ll_nb0))
Output
NB LL = -3326.26, pseudo R2 (McFadden) = 0.0050
clear
global link "~" 
/* Điều địa chỉ dẫn đến thư mục làm việc vào ~. 
Ví dụ thư phục làm việc là "C:\Downloads\data_dofile\1.data\chương 8" thì cú pháp là:
global link "C:\Downloads\data_dofile\1.data\chương 8" 

Trong trường hợp không thể tải file về bạn có thể dùng online với cú pháp:
use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/[chapter name]/[file name]",clear

   Ví dụ cần file GDP_population.dta.dta trong chương 1:
   use "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter1/GDP_population.dta", clear

   Đối với các tệp excel, bạn có thể sử dụng các lệnh sau: 
   import excel "https://raw.githubusercontent.com/Kieunhungtruong/Econometrics/main/data_dofile/1.data/chapter5/sales.xlsx", sheet("car") firstrow
*/
capture log close
set more off
/******************************************************************/  
/*      Chapter 8                                                 */
/*      File Name:  chapter8.do                                   */  
/*      Date:       October 31, 2024                              */  
/*      Authors:    Nhung                                         */  
/*      Purpose:    Modeling count data                           */  
/*      Input File:     remittances_adolescents.dta               */  
/*      Output File:    chapter8.log                              */  
/******************************************************************/ 

log using chapter8.log, text replace

use "$link\remittances_adolescents.dta",clear

gen overseas_adolescent_gender=overseas_remittances*adolescent_gender

gen domestic_adolescent_gender=domestic_remittances*adolescent_gender

global xvarpoisson "adolescent6_18_ratio adolescent0_15_ratio HHsize overseas_remittances domestic_remittances overseas_adolescent_gender  domestic_adolescent_gender crop_land"

regress outpatient $xvarpoisson

histogram outpatient, discrete frequency
 
graph export Chapter8.png, as(png) name("Graph") replace

sum outpatient,detail

jb outpatient

**# Mô hình hồi quy Poisson

poisson outpatient $xvarpoisson, nolog

mfx

poisson outpatient $xvarpoisson, irr nolog

**# Những hạn chế của mô hình hồi quy Poisson

quietly poisson outpatient $xvarpoisson

predict yhat

gen yhat2 = yhat^2

gen e =outpatient - yhat

gen e2 =e^2

gen diff = e2 - outpatient 

reg diff yhat2,nocons

**# Mô hình hồi quy nhị phân âm

nbreg outpatient $xvarpoisson, nolog

mfx

nbreg,irr

**# Kiểm định sự phù hợp 2 mô hình
quietly poisson outpatient $xvarpoisson, nolog

est sto poisson

quietly nbreg outpatient $xvarpoisson, nolog

est sto nbreg

lrtest nbreg poisson,force

log close

R, not checked against Python: R marginal-effects tables use derivatives for every variable. Python uses discrete changes for 0/1 variables, so values can differ.

Files: Notebook · Open in Colab · R script · Stata do-file

Data: remittances_adolescents.dta