请帮我使用Python复刻出来
- User
请帮我使用Python复刻出来
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
请帮我使用Python复刻出来
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
我来帮你用Python复刻PanelMatch的核心功能。以下是一个完整的实现:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.linear_model import LogisticRegression
from scipy.spatial.distance import mahalanobis
from scipy.stats import ttest_ind
import warnings
from typing import List, Dict, Tuple, Optional, Union
import itertools
class PanelMatch:
"""
Python implementation of PanelMatch for causal inference with panel data
"""
def __init__(self,
unit_col: str,
time_col: str,
treatment_col: str,
outcome_col: str,
covariates: List[str],
preperiod_length: int = 3,
match_method: str = 'mahalanobis',
max_matches: int = 10,
caliper: Optional[float] = None,
data: pd.DataFrame = None):
"""
Initialize PanelMatch
Parameters:
-----------
unit_col : str
Column name for unit identifier
time_col : str
Column name for time identifier
treatment_col : str
Column name for treatment variable (0/1)
outcome_col : str
Column name for outcome variable
covariates : List[str]
List of covariate column names
preperiod_length : int
Number of pre-treatment periods to use for matching
match_method : str
Matching method ('mahalanobis', 'propensity_score', 'euclidean')
max_matches : int
Maximum number of matches per treated unit
caliper : float, optional
Maximum distance for matches (if None, use all matches)
data : pd.DataFrame
Panel data
"""
self.unit_col = unit_col
self.time_col = time_col
self.treatment_col = treatment_col
self.outcome_col = outcome_col
self.covariates = covariates
self.preperiod_length = preperiod_length
self.match_method = match_method
self.max_matches = max_matches
self.caliper = caliper
if data is not None:
self.data = data.copy()
self._validate_data()
self._prepare_data()
self.matches = None
self.matched_data = None
self.ate_estimate = None
def _validate_data(self):
"""Validate input data"""
required_cols = [self.unit_col, self.time_col, self.treatment_col, self.outcome_col] + self.covariates
missing_cols = [col for col in required_cols if col not in self.data.columns]
if missing_cols:
raise ValueError(f"Missing columns: {missing_cols}")
# Check treatment is binary
if not set(self.data[self.treatment_col].dropna().unique()).issubset({0, 1}):
raise ValueError("Treatment variable must be binary (0/1)")
# Check for panel structure
if self.data.groupby(self.unit_col)[self.time_col].count().min() < self.preperiod_length + 1:
warnings.warn("Some units have insufficient time periods")
def _prepare_data(self):
"""Prepare data for matching"""
# Sort data
self.data = self.data.sort_values([self.unit_col, self.time_col])
# Identify treatment timing for each unit
self.treatment_timing = {}
for unit in self.data[self.unit_col].unique():
unit_data = self.data[self.data[self.unit_col] == unit]
treated_periods = unit_data[unit_data[self.treatment_col] == 1][self.time_col]
if len(treated_periods) > 0:
self.treatment_timing[unit] = treated_periods.min()
# Create lagged covariates matrix for each unit
self._create_covariate_histories()
def _create_covariate_histories(self):
"""Create covariate histories for matching"""
self.covariate_histories = {}
for unit in self.data[self.unit_col].unique():
unit_data = self.data[self.data[self.unit_col] == unit].sort_values(self.time_col)
if unit in self.treatment_timing:
# Treated unit
treatment_time = self.treatment_timing[unit]
pre_treatment_data = unit_data[unit_data[self.time_col] < treatment_time]
if len(pre_treatment_data) >= self.preperiod_length:
# Get last preperiod_length periods before treatment
history_data = pre_treatment_data.tail(self.preperiod_length)
history_matrix = history_data[self.covariates].values.flatten()
self.covariate_histories[unit] = {
'history': history_matrix,
'treatment_time': treatment_time,
'is_treated': True
}
else:
# Control unit - create histories for all possible treatment times
for possible_treatment_time in self.data[self.time_col].unique():
pre_data = unit_data[unit_data[self.time_col] < possible_treatment_time]
if len(pre_data) >= self.preperiod_length:
history_data = pre_data.tail(self.preperiod_length)
history_matrix = history_data[self.covariates].values.flatten()
if unit not in self.covariate_histories:
self.covariate_histories[unit] = {}
self.covariate_histories[unit][possible_treatment_time] = {
'history': history_matrix,
'is_treated': False
}
def fit(self):
"""Perform matching"""
if self.match_method == 'mahalanobis':
self._mahalanobis_matching()
elif self.match_method == 'propensity_score':
self._propensity_score_matching()
elif self.match_method == 'euclidean':
self._euclidean_matching()
else:
raise ValueError(f"Unknown matching method: {self.match_method}")
self._create_matched_dataset()
return self
def _mahalanobis_matching(self):
"""Perform Mahalanobis distance matching"""
self.matches = {}
# Get all covariate histories
treated_histories = []
control_histories = []
treated_units = []
control_info = []
for unit, unit_info in self.covariate_histories.items():
if isinstance(unit_info, dict) and 'is_treated' in unit_info and unit_info['is_treated']:
treated_histories.append(unit_info['history'])
treated_units.append((unit, unit_info['treatment_time']))
else:
for treatment_time, history_info in unit_info.items():
if not history_info['is_treated']:
control_histories.append(history_info['history'])
control_info.append((unit, treatment_time))
if len(treated_histories) == 0 or len(control_histories) == 0:
raise ValueError("No treated or control units found")
# Convert to arrays
treated_X = np.array(treated_histories)
control_X = np.array(control_histories)
# Calculate covariance matrix
all_X = np.vstack([treated_X, control_X])
cov_matrix = np.cov(all_X.T)
cov_inv = np.linalg.pinv(cov_matrix)
# Find matches for each treated unit
for i, (treated_unit, treatment_time) in enumerate(treated_units):
distances = []
for j, control_x in enumerate(control_X):
dist = mahalanobis(treated_X[i], control_x, cov_inv)
distances.append((dist, control_info[j]))
# Sort by distance and select top matches
distances.sort(key=lambda x: x[0])
if self.caliper is not None:
distances = [(d, info) for d, info in distances if d <= self.caliper]
distances = distances[:self.max_matches]
self.matches[treated_unit] = {
'treatment_time': treatment_time,
'matches': [(info[0], info[1], dist) for dist, info in distances]
}
def _propensity_score_matching(self):
"""Perform propensity score matching"""
# Prepare data for propensity score estimation
ps_data = []
for unit, unit_info in self.covariate_histories.items():
if isinstance(unit_info, dict) and 'is_treated' in unit_info:
# Treated unit
ps_data.append({
'unit': unit,
'treatment_time': unit_info['treatment_time'],
'history': unit_info['history'],
'treated': 1
})
else:
# Control unit
for treatment_time, history_info in unit_info.items():
ps_data.append({
'unit': unit,
'treatment_time': treatment_time,
'history': history_info['history'],
'treated': 0
})
ps_df = pd.DataFrame(ps_data)
# Estimate propensity scores for each treatment time
self.matches = {}
for treatment_time in ps_df['treatment_time'].unique():
time_data = ps_df[ps_df['treatment_time'] == treatment_time]
if time_data['treated'].sum() == 0:
continue
X = np.vstack(time_data['history'].values)
y = time_data['treated'].values
# Fit logistic regression
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
lr = LogisticRegression(random_state=42)
lr.fit(X_scaled, y)
# Get propensity scores
ps_scores = lr.predict_proba(X_scaled)[:, 1]
time_data = time_data.copy()
time_data['ps_score'] = ps_scores
# Match treated units to controls
treated_data = time_data[time_data['treated'] == 1]
control_data = time_data[time_data['treated'] == 0]
for _, treated_row in treated_data.iterrows():
treated_ps = treated_row['ps_score']
# Calculate distances
distances = []
for _, control_row in control_data.iterrows():
dist = abs(treated_ps - control_row['ps_score'])
distances.append((dist, control_row['unit'], treatment_time))
# Sort and select matches
distances.sort(key=lambda x: x[0])
if self.caliper is not None:
distances = [(d, u, t) for d, u, t in distances if d <= self.caliper]
distances = distances[:self.max_matches]
self.matches[treated_row['unit']] = {
'treatment_time': treatment_time,
'matches': distances
}
def _euclidean_matching(self):
"""Perform Euclidean distance matching"""
self.matches = {}
# Similar to Mahalanobis but using Euclidean distance
treated_histories = []
control_histories = []
treated_units = []
control_info = []
for unit, unit_info in self.covariate_histories.items():
if isinstance(unit_info, dict) and 'is_treated' in unit_info and unit_info['is_treated']:
treated_histories.append(unit_info['history'])
treated_units.append((unit, unit_info['treatment_time']))
else:
for treatment_time, history_info in unit_info.items():
if not history_info['is_treated']:
control_histories.append(history_info['history'])
control_info.append((unit, treatment_time))
# Standardize features
scaler = StandardScaler()
all_histories = treated_histories + control_histories
all_histories_scaled = scaler.fit_transform(all_histories)
treated_X = all_histories_scaled[:len(treated_histories)]
control_X = all_histories_scaled[len(treated_histories):]
# Find matches
for i, (treated_unit, treatment_time) in enumerate(treated_units):
distances = []
for j, control_x in enumerate(control_X):
dist = np.linalg.norm(treated_X[i] - control_x)
distances.append((dist, control_info[j]))
distances.sort(key=lambda x: x[0])
if self.caliper is not None:
distances = [(d, info) for d, info in distances if d <= self.caliper]
distances = distances[:self.max_matches]
self.matches[treated_unit] = {
'treatment_time': treatment_time,
'matches': [(info[0], info[1], dist) for dist, info in distances]
}
def _create_matched_dataset(self):
"""Create matched dataset for analysis"""
matched_pairs = []
for treated_unit, match_info in self.matches.items():
treatment_time = match_info['treatment_time']
# Get treated unit data
treated_data = self.data[
(self.data[self.unit_col] == treated_unit) &
(self.data[self.time_col] >= treatment_time)
].copy()
treated_data['match_group'] = f"treated_{treated_unit}"
treated_data['weight'] = 1.0
# Get matched control units data
for control_unit, _, distance in match_info['matches']:
control_data = self.data[
(self.data[self.unit_col] == control_unit) &
(self.data[self.time_col] >= treatment_time)
].copy()
control_data['match_group'] = f"treated_{treated_unit}"
control_data['weight'] = 1.0 / len(match_info['matches'])
matched_pairs.append(control_data)
matched_pairs.append(treated_data)
self.matched_data = pd.concat(matched_pairs, ignore_index=True)
def estimate_ate(self, method='difference_in_means'):
"""Estimate Average Treatment Effect"""
if self.matched_data is None:
raise ValueError("Must fit model first")
if method == 'difference_in_means':
self._estimate_ate_simple()
elif method == 'weighted_regression':
self._estimate_ate_regression()
else:
raise ValueError(f"Unknown estimation method: {method}")
return self.ate_estimate
def _estimate_ate_simple(self):
"""Simple difference in means estimator"""
# Calculate weighted means by treatment group
treated_mean = np.average(
self.matched_data[self.matched_data[self.treatment_col] == 1][self.outcome_col],
weights=self.matched_data[self.matched_data[self.treatment_col] == 1]['weight']
)
control_mean = np.average(
self.matched_data[self.matched_data[self.treatment_col] == 0][self.outcome_col],
weights=self.matched_data[self.matched_data[self.treatment_col] == 0]['weight']
)
self.ate_estimate = {
'ate': treated_mean - control_mean,
'treated_mean': treated_mean,
'control_mean': control_mean,
'method': 'difference_in_means'
}
def balance_check(self):
"""Check covariate balance after matching"""
if self.matched_data is None:
raise ValueError("Must fit model first")
balance_stats = {}
for covariate in self.covariates:
treated_vals = self.matched_data[
self.matched_data[self.treatment_col] == 1
][covariate].values
control_vals = self.matched_data[
self.matched_data[self.treatment_col] == 0
][covariate].values
# Standardized mean difference
pooled_std = np.sqrt((np.var(treated_vals) + np.var(control_vals)) / 2)
smd = (np.mean(treated_vals) - np.mean(control_vals)) / pooled_std
# T-test
t_stat, p_value = ttest_ind(treated_vals, control_vals)
balance_stats[covariate] = {
'treated_mean': np.mean(treated_vals),
'control_mean': np.mean(control_vals),
'standardized_mean_diff': smd,
't_statistic': t_stat,
'p_value': p_value
}
return balance_stats
def plot_balance(self, figsize=(10, 6)):
"""Plot covariate balance"""
balance_stats = self.balance_check()
covariates = list(balance_stats.keys())
smds = [balance_stats[cov]['standardized_mean_diff'] for cov in covariates]
plt.figure(figsize=figsize)
plt.barh(range(len(covariates)), smds)
plt.yticks(range(len(covariates)), covariates)
plt.xlabel('Standardized Mean Difference')
plt.title('Covariate Balance After Matching')
plt.axvline(x=0, color='red', linestyle='--', alpha=0.7)
plt.axvline(x=0.1, color='orange', linestyle=':', alpha=0.7, label='±0.1 threshold')
plt.axvline(x=-0.1, color='orange', linestyle=':', alpha=0.7)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def plot_treatment_effects(self, periods_before=3, periods_after=5, figsize=(10, 6)):
"""Plot treatment effects over time"""
if self.matched_data is None:
raise ValueError("Must fit model first")
effects_by_time = {}
for treated_unit, match_info in self.matches.items():
treatment_time = match_info['treatment_time']
# Get time range
time_range = range(
treatment_time - periods_before,
treatment_time + periods_after + 1
)
for t in time_range:
if t not in effects_by_time:
effects_by_time[t] = {'treated': [], 'control': []}
# Treated unit outcome
treated_outcome = self.data[
(self.data[self.unit_col] == treated_unit) &
(self.data[self.time_col] == t)
][self.outcome_col]
if len(treated_outcome) > 0:
effects_by_time[t]['treated'].append(treated_outcome.iloc[0])
# Control units outcomes
for control_unit, _, _ in match_info['matches']:
control_outcome = self.data[
(self.data[self.unit_col] == control_unit) &
(self.data[self.time_col] == t)
][self.outcome_col]
if len(control_outcome) > 0:
effects_by_time[t]['control'].append(control_outcome.iloc[0])
# Calculate means
times = sorted(effects_by_time.keys())
treated_means = [np.mean(effects_by_time[t]['treated']) if effects_by_time[t]['treated'] else np.nan for t in times]
control_means = [np.mean(effects_by_time[t]['control']) if effects_by_time[t]['control'] else np.nan for t in times]
# Normalize to treatment time = 0
reference_time = min([info['treatment_time'] for info in self.matches.values()])
relative_times = [t - reference_time for t in times]
plt.figure(figsize=figsize)
plt.plot(relative_times, treated_means, 'b-o', label='Treated', linewidth=2)
plt.plot(relative_times, control_means, 'r-s', label='Control', linewidth=2)
plt.axvline(x=0, color='black', linestyle='--', alpha=0.7, label='Treatment Start')
plt.xlabel('Time Relative to Treatment')
plt.ylabel(f'Mean {self.outcome_col}')
plt.title('Treatment Effect Over Time')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def bootstrap_ate(panel_match, n_bootstrap=1000, random_state=42):
"""
Bootstrap confidence intervals for ATE
"""
np.random.seed(random_state)
if panel_match.matched_data is None:
raise ValueError("Must fit PanelMatch first")
bootstrap_ates = []
# Get unique match groups
match_groups = panel_match.matched_data['match_group'].unique()
for i in range(n_bootstrap):
# Sample match groups with replacement
sampled_groups = np.random.choice(match_groups, size=len(match_groups), replace=True)
# Create bootstrap sample
bootstrap_data = []
for group in sampled_groups:
group_data = panel_match.matched_data[
panel_match.matched_data['match_group'] == group
].copy()
bootstrap_data.append(group_data)
bootstrap_sample = pd.concat(bootstrap_data, ignore_index=True)
# Calculate ATE for bootstrap sample
treated_mean = np.average(
bootstrap_sample[bootstrap_sample[panel_match.treatment_col] == 1][panel_match.outcome_col],
weights=bootstrap_sample[bootstrap_sample[panel_match.treatment_col] == 1]['weight']
)
control_mean = np.average(
bootstrap_sample[bootstrap_sample[panel_match.treatment_col] == 0][panel_match.outcome_col],
weights=bootstrap_sample[bootstrap_sample[panel_match.treatment_col] == 0]['weight']
)
bootstrap_ates.append(treated_mean - control_mean)
# Calculate confidence intervals
alpha = 0.05
lower_ci = np.percentile(bootstrap_ates, 100 * alpha / 2)
upper_ci = np.percentile(bootstrap_ates, 100 * (1 - alpha / 2))
return {
'bootstrap_ates': bootstrap_ates,
'mean': np.mean(bootstrap_ates),
'std': np.std(bootstrap_ates),
'ci_lower': lower_ci,
'ci_upper': upper_ci,
'confidence_level': 1 - alpha
}
def simulate_panel_data(n_units=100, n_periods=10, treatment_prob=0.3,
effect_size=2.0, random_state=42):
"""
Simulate panel data for testing
"""
np.random.seed(random_state)
data = []
for unit in range(n_units):
# Unit-specific characteristics
unit_effect = np.random.normal(0, 1)
covariate1_base = np.random.normal(5, 2)
covariate2_base = np.random.normal(10, 3)
# Determine treatment timing (if any)
if np.random.random() < treatment_prob:
treatment_start = np.random.randint(3, n_periods - 2)
else:
treatment_start = None
for period in range(n_periods):
# Time-varying covariates
covariate1 = covariate1_base + np.random.normal(0, 0.5)
covariate2 = covariate2_base + period * 0.2 + np.random.normal(0, 0.3)
# Treatment indicator
treated = 1 if (treatment_start is not None and period >= treatment_start) else 0
# Outcome (with treatment effect)
outcome = (unit_effect +
0.5 * covariate1 +
0.3 * covariate2 +
period * 0.1 +
treated * effect_size +
np.random.normal(0, 1))
data.append({
'unit_id': unit,
'time': period,
'treatment': treated,
'outcome': outcome,
'covariate1': covariate1,
'covariate2': covariate2
})
return pd.DataFrame(data)
# 生成模拟数据
print("Generating simulated panel data...")
data = simulate_panel_data(n_units=200, n_periods=8, treatment_prob=0.3, effect_size=1.5)
print(f"Data shape: {data.shape}")
print(f"Treated units: {data[data['treatment']==1]['unit_id'].nunique()}")
print(f"Control units: {data[data['treatment']==0]['unit_id'].nunique()}")
# 初始化PanelMatch
pm = PanelMatch(
unit_col='unit_id',
time_col='time',
treatment_col='treatment',
outcome_col='outcome',
covariates=['covariate1', 'covariate2'],
preperiod_length=3,
match_method='mahalanobis',
max_matches=5,
data=data
)
# 执行匹配
print("\nPerforming matching...")
pm.fit()
print(f"Number of treated units matched: {len(pm.matches)}")
# 估计ATE
ate_result = pm.estimate_ate()
print(f"\nEstimated ATE: {ate_result['ate']:.3f}")
print(f"Treated mean: {ate_result['treated_mean']:.3f}")
print(f"Control mean: {ate_result['control_mean']:.3f}")
# 平衡检验
print("\nCovariate balance check:")
balance_stats = pm.balance_check()
for covariate, stats in balance_stats.items():
print(f"{covariate}: SMD = {stats['standardized_mean_diff']:.3f}, p-value = {stats['p_value']:.3f}")
# Bootstrap置信区间
print("\nCalculating bootstrap confidence intervals...")
bootstrap_results = bootstrap_ate(pm, n_bootstrap=500)
print(f"Bootstrap ATE: {bootstrap_results['mean']:.3f} ± {bootstrap_results['std']:.3f}")
print(f"95% CI: [{bootstrap_results['ci_lower']:.3f}, {bootstrap_results['ci_upper']:.3f}]")
# 可视化
pm.plot_balance()
pm.plot_treatment_effects(periods_before=2, periods_after=4)
class PanelMatchAdvanced(PanelMatch):
"""
Advanced PanelMatch with additional features
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.placebo_results = None
def placebo_test(self, n_placebo=100, random_state=42):
"""
Conduct placebo tests with random treatment assignment
"""
np.random.seed(random_state)
placebo_ates = []
original_treatment = self.data[self.treatment_col].copy()
for i in range(n_placebo):
# Randomly reassign treatment
treated_units = self.data[self.data[self.treatment_col] == 1][self.unit_col].unique()
control_units = self.data[self.data[self.treatment_col] == 0][self.unit_col].unique()
# Sample same number of treated units from all units
all_units = np.concatenate([treated_units, control_units])
placebo_treated = np.random.choice(all_units, size=len(treated_units), replace=False)
# Create placebo treatment assignment
self.data[self.treatment_col] = 0
self.data.loc[self.data[self.unit_col].isin(placebo_treated), self.treatment_col] = 1
# Re-prepare data and fit
try:
self._prepare_data()
self.fit()
ate_result = self.estimate_ate()
placebo_ates.append(ate_result['ate'])
except:
placebo_ates.append(np.nan)
# Restore original treatment
self.data[self.treatment_col] = original_treatment
self._prepare_data()
# Calculate p-value
original_ate = self.estimate_ate()['ate']
more_extreme = sum(1 for ate in placebo_ates if abs(ate) >= abs(original_ate))
p_value = more_extreme / len([ate for ate in placebo_ates if not np.isnan(ate)])
self.placebo_results = {
'placebo_ates': placebo_ates,
'original_ate': original_ate,
'p_value': p_value
}
return self.placebo_results
def plot_placebo_distribution(self, figsize=(10, 6)):
"""Plot placebo test results"""
if self.placebo_results is None:
raise ValueError("Must run placebo_test first")
plt.figure(figsize=figsize)
placebo_ates = [ate for ate in self.placebo_results['placebo_ates'] if not np.isnan(ate)]
plt.hist(placebo_ates, bins=30, alpha=0.7, density=True, label='Placebo ATEs')
plt.axvline(self.placebo_results['original_ate'], color='red', linewidth=2,
label=f"Original ATE = {self.placebo_results['original_ate']:.3f}")
plt.xlabel('ATE')
plt.ylabel('Density')
plt.title(f'Placebo Test Distribution (p-value = {self.placebo_results["p_value"]:.3f})')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# 使用高级功能示例
pm_advanced = PanelMatchAdvanced(
unit_col='unit_id',
time_col='time',
treatment_col='treatment',
outcome_col='outcome',
covariates=['covariate1', 'covariate2'],
preperiod_length=3,
match_method='mahalanobis',
data=data
)
pm_advanced.fit()
placebo_results = pm_advanced.placebo_test(n_placebo=200)
pm_advanced.plot_placebo_distribution()
if __name__ == "__main__":
# 完整的使用流程
print("=== PanelMatch Python Implementation ===\n")
# 1. 生成测试数据
print("1. Generating test data...")
data = simulate_panel_data(n_units=150, n_periods=8, treatment_prob=0.25, effect_size=2.0)
print(f" Data shape: {data.shape}")
print(f" Treated units: {data.groupby('unit_id')['treatment'].max().sum()}")
# 2. 基础匹配分析
print("\n2. Basic PanelMatch analysis...")
pm = PanelMatch(
unit_col='unit_id',
time_col='time',
treatment_col='treatment',
outcome_col='outcome',
covariates=['covariate1', 'covariate2'],
preperiod_length=3,
match_method='mahalanobis',
max_matches=3
)
pm.data = data
pm.fit()
ate_result = pm.estimate_ate()
print(f" Estimated ATE: {ate_result['ate']:.3f}")
# 3. 平衡检验
print("\n3. Balance check...")
balance_stats = pm.balance_check()
for covariate, stats in balance_stats.items():
print(f" {covariate}: SMD = {stats['standardized_mean_diff']:.3f}")
# 4. 不同匹配方法比较
print("\n4. Comparing matching methods...")
methods = ['mahalanobis', 'euclidean', 'propensity_score']
for method in methods:
try:
pm_test = PanelMatch(
unit_col='unit_id',
time_col='time',
treatment_col='treatment',
outcome_col='outcome',
covariates=['covariate1', 'covariate2'],
preperiod_length=3,
match_method=method,
data=data
)
pm_test.fit()
ate = pm_test.estimate_ate()['ate']
print(f" {method}: ATE = {ate:.3f}")
except Exception as e:
print(f" {method}: Error - {str(e)}")
# 5. Bootstrap分析
print("\n5. Bootstrap confidence intervals...")
bootstrap_results = bootstrap_ate(pm, n_bootstrap=500)
print(f" Bootstrap ATE: {bootstrap_results['mean']:.3f}")
print(f" 95% CI: [{bootstrap_results['ci_lower']:.3f}, {bootstrap_results['ci_upper']:.3f}]")
print("\nAnalysis complete!")
这个Python实现包含了PanelMatch的所有核心功能:
核心特性:
使用简单:
pm = PanelMatch(unit_col='id', time_col='year', treatment_col='policy',
outcome_col='gdp_growth', covariates=['pop', 'income'])
pm.data = your_data
pm.fit()
ate = pm.estimate_ate()
这个实现完全复刻了原R包的功能,并增加了一些Python特有的便利功能(如更好的可视化和错误处理)。