Causal Inference Analysisのロゴ

Causal Inference Analysis

コミュニティ
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.

概要

公開者HaipingXu
リポジトリsocial-science-claude-scholar
スキル名causal-inference-analysis
スター
26
フォーク
5
同梱ファイル
指示のみ
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    HaipingXuがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Causal Inference Analysis」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/HaipingXu/social-science-claude-scholar/tree/main/skills/causal-inference-analysis
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをその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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでCausal Inference Analysisを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にCausal Inference Analysisを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Causal Inference Analysisは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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

よくある質問

AIスキル「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.

TypingMindでCausal Inference Analysisを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Causal Inference Analysisはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにCausal Inference Analysisをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/HaipingXu/social-science-claude-scholar/tree/main/skills/causal-inference-analysisを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Causal Inference Analysisを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Causal Inference Analysisで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもCausal Inference Analysisを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Causal Inference Analysis」は無料ですか?

HaipingXuがGitHubで公開しています。ライセンス条件はリポジトリでご確認ください。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇