Logo Causal Inference Analysis

Causal Inference Analysis

Cộng đồng
HaipingXu
causal-inference-analysis

Use when the user asks to "implement DID", "run difference-in-differences", "set up IV regression", "instrumental variables", "run RDD", "regression discontinuity", "synthetic control", "staggered treatment", "Callaway-Sant'Anna", "Sun-Abraham", "event study", "parallel trends test", "first stage", "Bartik instrument", "shift-share IV", "write Stata regression code", "convert Stata to Python", "use statsmodels", "use linearmodels", "use econml", "panel data regression", "fixed effects", "two-way fixed effects", "cluster standard errors", or any causal inference methodology in Python or Stata.

Tổng quan

Nhà phát hànhHaipingXu
Kho mãsocial-science-claude-scholar
Tên kỹ năngcausal-inference-analysis
Sao
26
Bản fork
5
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được HaipingXu công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Causal Inference Analysis trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/HaipingXu/social-science-claude-scholar/tree/main/skills/causal-inference-analysis
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HaipingXu/social-science-claude-scholar.git /tmp/social-science-claude-scholar
mkdir -p .claude/skills
cp -r /tmp/social-science-claude-scholar/skills/causal-inference-analysis .claude/skills/causal-inference-analysis
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Causal Inference Analysis trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Causal Inference Analysis ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Causal Inference Analysis với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Causal Inference Analysis

Practical implementation guide for DID, IV, RDD, and Synthetic Control in Python and Stata. Covers setup, estimation, assumption testing, and output generation.

Quick Reference

MethodPython LibraryStata Command
Two-way FE / DIDlinearmodels.PanelOLSreghdfe
Staggered DID (CS)csdid / pyfixestcsdid (ado)
Staggered DID (SA)pyfixesteventstudyinteract
IV / 2SLSlinearmodels.IV2SLSivregress 2sls / ivreg2
Shift-share IVmanual + linearmodelsssiv (ado)
RDDrdd / rdrobust (Python)rdrobust, rddensity
Synthetic Controlsynth_runner / pysynthsynth
Double-LASSOdoublemlpdslasso

Method 1: Difference-in-Differences

Standard 2×2 DID (Python)

python
import pandas as pd
from linearmodels import PanelOLS
import statsmodels.formula.api as smf

# Panel setup
df = df.set_index(['unit_id', 'year'])

# Two-way FE (unit + time)
mod = PanelOLS.from_formula(
    'outcome ~ treat_post + EntityEffects + TimeEffects',
    data=df,
    drop_absorbed=True
)
res = mod.fit(cov_type='clustered', cluster_entity=True)
print(res.summary)

Event Study / Dynamic DID (Python)

python
import pyfixest as pf

# Staggered DID — Sun-Abraham (2021)
fit = pf.feols(
    'outcome ~ i(rel_time, treated, ref=-1) | unit + year',
    data=df,
    vcov={'CRV1': 'state'}  # cluster at state level
)
pf.iplot(fit)  # coefficient plot with 95% CI

Callaway-Sant'Anna (staggered, Python)

python
from csdid import att_gt, aggte

# Estimate group-time ATTs
att = att_gt(
    yname='outcome',
    tname='year',
    idname='unit_id',
    gname='first_treat',  # 0 for never-treated
    data=df,
    control_group='nevertreated',
    est_method='dr'  # doubly robust
)
agg = aggte(att, type='dynamic')  # event-study aggregation

Pre-trend Test Interpretation

  • Coefficients at t = −1, −2, ..., −k should be near zero and statistically insignificant
  • Report the joint F-test for pre-period coefficients
  • If pre-trends detected: consider controlling for unit-specific linear trends or using CS/SA estimators

Method 2: Instrumental Variables

Basic 2SLS (Python)

python
from linearmodels import IV2SLS

mod = IV2SLS.from_formula(
    'outcome ~ 1 + controls [endog ~ instrument]',
    data=df
)
res = mod.fit(cov_type='robust')  # or 'clustered', cluster='state'
print(res.summary)

# Key diagnostics
print(f"First-stage F: {res.first_stage.diagnostics}")
print(f"Wu-Hausman: {res.wu_hausman()}")

Shift-Share (Bartik) IV

python
# Bartik instrument = Σ_k (local_share_k × national_growth_k)
df['bartik'] = (
    df[share_cols]
    .multiply(national_growth, axis=1)
    .sum(axis=1)
)

# Use as standard IV
mod = IV2SLS.from_formula(
    'outcome ~ controls [endog ~ bartik]',
    data=df
)

Key diagnostics to report:

  • Kleibergen-Paap F (for clustered SE) — not Cragg-Donald
  • Stock-Yogo critical values for size distortion
  • First-stage coefficient on instrument with SE

Method 3: Regression Discontinuity

Sharp RDD (Python)

python
from rdrobust import rdrobust, rdplot, rdbwselect

# Main estimate
result = rdrobust(y=df['outcome'], x=df['running_var'], c=0)
print(result.coef)   # LATE at cutoff
print(result.se)     # SE (conventional, robust, bias-corrected)
print(result.bws)    # Optimal bandwidth (IK/CCT)

# RD plot
rdplot(y=df['outcome'], x=df['running_var'], c=0)

# Density test (McCrary)
from rddensity import rddensity
dens = rddensity(X=df['running_var'], c=0)
print(dens.test)

RDD Robustness Checklist

python
# 1. Multiple bandwidths
for bw_mult in [0.5, 0.75, 1.0, 1.25, 1.5]:
    bw = optimal_bw * bw_mult
    r = rdrobust(y, x, c=0, h=bw)
    print(f"BW×{bw_mult}: {r.coef[0]:.3f} ({r.se[0]:.3f})")

# 2. Covariate balance (run RDD on predetermined controls)
for cov in ['age', 'income_baseline', 'education']:
    r = rdrobust(y=df[cov], x=df['running_var'], c=0)
    print(f"{cov}: {r.coef[0]:.3f} (p={r.pv[0]:.3f})")

# 3. Donut hole (exclude ±ε of cutoff)
for donut in [0.1, 0.2, 0.5]:
    df_donut = df[abs(df['running_var']) > donut]
    r = rdrobust(y=df_donut['outcome'], x=df_donut['running_var'], c=0)
    print(f"Donut ±{donut}: {r.coef[0]:.3f}")

Method 4: Synthetic Control

Basic Synthetic Control (Python)

python
# Option 1: pysynth
from pysynth import Synth

synth = Synth()
synth.fit(
    dataprep_dict={
        'foo': 'bar'  # see references/synth-workflow.md for full setup
    }
)
synth.plot(periods_pre_treatment=15, periods_post_treatment=10)
synth.weights()  # donor unit weights

# Option 2: Manual (more transparent)
# See references/synth-manual.md

Placebo tests:

python
# In-space: run SC for each donor unit
for donor in donor_pool:
    df_placebo = df[df['unit'] != treated_unit]
    df_placebo['treated'] = (df_placebo['unit'] == donor)
    # Run SC, record post-period MSPE
    # If treated MSPE >> median donor MSPE → significant effect

Stata → Python Translation

Common Stata patterns and their Python equivalents:

StataPython
reghdfe y x, absorb(unit year) cluster(state)PanelOLS + cov_type='clustered'
ivregress 2sls y x (endog = iv), cluster(state)IV2SLS with clustered SE
rdrobust y x, c(0) kernel(triangular)rdrobust(y, x, c=0, kernel='triangular')
estout / esttabstargazer or modelsummary (Python)
coefplotpyfixest.iplot() or manual matplotlib

See references/stata-to-python.md for detailed translation guide.


Output Generation

Regression Table (LaTeX)

python
import stargazer
from stargazer.stargazer import Stargazer

# statsmodels results
sg = Stargazer([res1, res2, res3])
sg.title('Main Results: Effect of X on Y')
sg.custom_columns(['OLS', 'DID', 'DID + Controls'], [1, 1, 1])
sg.covariate_order(['treat_post', 'control1', 'control2'])
sg.add_line('Unit FE', ['No', 'Yes', 'Yes'])
sg.add_line('Year FE', ['No', 'Yes', 'Yes'])
sg.significant_digits(3)
print(sg.render_latex())

Event Study Plot

python
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

# Assumes: coefs (array), ses (array), periods (array, e.g. -5 to 5)
fig, ax = plt.subplots(figsize=(8, 4))
ax.errorbar(periods, coefs, yerr=1.96*ses,
            fmt='o-', color='steelblue', capsize=4, linewidth=1.5)
ax.axhline(0, color='black', linewidth=0.8, linestyle='--')
ax.axvline(-0.5, color='red', linewidth=0.8, linestyle=':', label='Treatment')
ax.set_xlabel('Years Relative to Treatment')
ax.set_ylabel('Estimated Effect (95% CI)')
ax.set_title('Event Study: Dynamic Treatment Effects')
ax.legend()
plt.tight_layout()
plt.savefig('figures/event_study.pdf', bbox_inches='tight')

Package Installation

bash
# Install all causal inference tools at once
uv pip install linearmodels pyfixest econml doubleml rdrobust rddensity stargazer

# For synthetic control
uv pip install pysynth  # or: pip install synth_runner

# Stata bridge (if needed)
uv pip install pystata pyreadstat

Reference Resources

  • references/stata-to-python.md — Comprehensive Stata→Python translation with code
  • references/identification-tests.md — Detailed assumption test protocols (pre-trends, density, first stage)
  • references/output-templates.md — LaTeX table templates, event study plot templates

Câu hỏi thường gặp

Kỹ năng AI Causal Inference Analysis làm được gì?

Use when the user asks to "implement DID", "run difference-in-differences", "set up IV regression", "instrumental variables", "run RDD", "regression discontinuity", "synthetic control", "staggered treatment", "Callaway-Sant'Anna", "Sun-Abraham", "event study", "parallel trends test", "first stage", "Bartik instrument", "shift-share IV", "write Stata regression code", "convert Stata to Python", "use statsmodels", "use linearmodels", "use econml", "panel data regression", "fixed effects", "two-way fixed effects", "cluster standard errors", or any causal inference methodology in Python or Stata.

Vì sao nên dùng Causal Inference Analysis trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Causal Inference Analysis là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Causal Inference Analysis trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/HaipingXu/social-science-claude-scholar/tree/main/skills/causal-inference-analysis. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Causal Inference Analysis?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Causal Inference Analysis với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Causal Inference Analysis với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Causal Inference Analysis có miễn phí không?

Kỹ năng này được HaipingXu phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇