9.5 经典案例和 Python 实现(Case Studies & Python)
从真实研究到可复现代码
本节目标
- 了解 DID 的经典应用场景
- 能用合成数据复现 DID 的完整流程
- 掌握可迁移到真实数据集的代码模板
一、经典案例速览(概念性梳理)
- 最低工资政策:以政策生效前后、受影响与未受影响地区的就业/工资为结果变量。
- 环境管制/税收政策:对产能、排放、投资等的影响。
- 教育/医疗改革:对学生成绩、健康指标的影响。
提示:在任何案例中,都要回到“平行趋势是否合理”这一核心问题(见 9.3)。
二、合成数据演示:从 0 到 1 的 DID(可运行)
python
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
# 参数
n_units = 60 # 个体数量
n_periods = 10 # 时间期数
policy_time = 6 # 政策实施期(从 1 开始计数)
rng = np.random.default_rng(42)
ids = np.arange(n_units)
periods = np.arange(1, n_periods + 1)
data = []
for i in ids:
treated = 1 if i >= n_units // 2 else 0
unit_fe = rng.normal(0, 3)
for t in periods:
time_fe = 0.5 * t
post = 1 if t >= policy_time else 0
tau = 4.0 # 政策真实效应
y = 20 + unit_fe + time_fe + tau * treated * post + rng.normal(0, 2)
data.append({
'id': i,
'time': t,
'treated': treated,
'post': post,
'y': y
})
df = pd.DataFrame(data)
# DID 回归(含实体/时间固定效应,按实体聚类标准误)
model = smf.ols('y ~ treated*post + C(id) + C(time)', data=df) \
.fit(cov_type='cluster', cov_kwds={'groups': df['id']})
print(model.summary().tables[1])
print('\nATE (treated:post) =', model.params['treated:post'])扩展:
- 事件研究(Event Study)以检查前趋势与动态效应(参见 9.3)。
- 在多期/错位处理下,建议使用近期多期 DID 估计器(如 Sun & Abraham, Callaway & Sant'Anna 等实现)。
三、现实数据示例(操作模板)
- 整理数据到长表:一行=一个体×时期(含 id、time、treated、post、y)
- 做 9.3 的“前趋势与事件研究”以评估识别假设
- 估计基本 DID + 稳健性(聚类/双向聚类、控制趋势)
- 做 9.4 的安慰剂检验:假时点/假对照组/Leave-one-out/置换检验/安慰剂结果
- 报告:主结果 + 前趋势/事件研究图 + 安慰剂检验 + 解释
本节小结
- DID 的经典案例很多,但识别逻辑始终围绕“平行趋势”。
- 先用可复现的合成数据打通一遍流程,再迁移到真实数据。
- 模板化思维:数据结构、回归式、聚类方式、可视化与稳健性。
附:事件研究图(与 9.3 风格一致)
使用上面构造的
df数据,估计并绘制事件研究(Event Study)动态效应。
python
import matplotlib.pyplot as plt
from linearmodels.panel import PanelOLS
# 构造相对时间(以政策实施期为 0,政策前为负,后为正)
df['rel_time'] = df['time'] - policy_time
df['rel_time_treated'] = df['rel_time'] * df['treated']
# 生成 leads/lags(以 -1 期为基准)
min_lead, max_lag = - (policy_time - 1), (n_periods - policy_time)
lead_lag_vars = []
for k in range(min_lead, max_lag + 1):
if k == -1:
continue # 基准期不建虚拟变量
col = f'LL_{k}'
df[col] = (df['rel_time_treated'] == k).astype(int)
lead_lag_vars.append(col)
# 面板索引
panel = df.set_index(['id', 'time'])
# 回归(个体与时间固定效应)
model_es = PanelOLS(
dependent=panel['y'],
exog=panel[lead_lag_vars],
entity_effects=True,
time_effects=True
).fit(cov_type='clustered', cluster_entity=True)
print(model_es.summary)
# 取系数与置信区间,拼出包含基准期(-1)的序列
rows = []
for k in range(min_lead, max_lag + 1):
if k == -1:
rows.append({'rel_time': k, 'coef': 0.0, 'low': 0.0, 'high': 0.0})
else:
name = f'LL_{k}'
coef = float(model_es.params.get(name, 0.0))
ci = model_es.conf_int().loc[name]
rows.append({'rel_time': k, 'coef': coef, 'low': float(ci[0]), 'high': float(ci[1])})
es = pd.DataFrame(rows).sort_values('rel_time')
# 绘图
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(es['rel_time'], es['coef'], 'o-', color='navy', label='DID 系数')
ax.fill_between(es['rel_time'], es['low'], es['high'], color='navy', alpha=0.25, label='95% CI')
ax.axhline(0, color='black', linestyle='--', linewidth=1)
ax.axvline(0, color='red', linestyle='--', linewidth=1.5, label='政策实施期')
ax.set_xlabel('相对时间 (政策前为负,后为正)')
ax.set_ylabel('效应')
ax.set_title('事件研究:动态处理效应')
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()