krl-causal-policy-toolkit 1.0.0
Comprehensive Python library for policy evaluation and causal inference
License: MIT
Requires Python: >=3.9
Keywords: causal-inference, policy-evaluation, treatment-effects, difference-in-differences, synthetic-control, regression-discontinuity, instrumental-variables, propensity-score-matching, cost-benefit-analysis, econometrics

# KRL Causal Policy Toolkit

[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://img.shields.io/badge/tests-293%20passing-brightgreen.svg)](https://github.com/KR-Labs/krl-causal-policy-toolkit)
[![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://github.com/KR-Labs/krl-causal-policy-toolkit)
[![Documentation](https://img.shields.io/badge/docs-sphinx-blue.svg)](https://krl-causal-policy-toolkit.readthedocs.io)

> **Comprehensive Python library for policy evaluation and causal inference**

KRL Causal Policy Toolkit provides state-of-the-art methods for estimating treatment effects, conducting policy analysis, and generating publication-ready reports. Built for policy analysts, economists, and researchers who need rigorous causal inference tools with practical usability.

## ✨ Key Features

### 🎯 **Treatment Effect Estimation**
- **Basic Methods**: Difference-in-Means, Regression Adjustment, IPW, Doubly Robust
- **Panel Methods**: Difference-in-Differences with TWFE and event studies
- **Matching**: Propensity Score Matching with multiple algorithms
- **Advanced**: Synthetic Control, Regression Discontinuity, Instrumental Variables

### 📊 **Policy Evaluation**
- **Unified Interface**: Automatic method selection and comparison
- **Cost-Benefit Analysis**: NPV, IRR, BCR with Monte Carlo simulation
- **Sensitivity Analysis**: Rosenbaum bounds, E-values, specification curves
- **Diagnostics**: Balance tests, parallel trends, placebo tests

### 📝 **Automated Reporting**
- **Multiple Formats**: HTML, LaTeX, Markdown
- **Publication-Ready**: Bootstrap styling, academic formatting
- **Comparison Tables**: Side-by-side method comparisons
- **Professional Output**: Executive summaries and technical appendices

### 📦 **Built-in Datasets**
- **5 Policy Datasets**: NSW, Medicaid, Minimum Wage, Education Voucher, SNAP
- **Ready-to-Use**: Pre-configured with proper metadata
- **Realistic**: Synthetic data with proper causal structure

## 🚀 Installation

```bash
pip install krl-causal-policy-toolkit
```

**Requirements**: Python 3.9+, NumPy, pandas, SciPy, scikit-learn

**Optional dependencies** for report generation:
```bash
pip install krl-causal-policy-toolkit[reporting]
```

**Development installation**:
```bash
git clone https://github.com/KR-Labs/krl-causal-policy-toolkit.git
cd krl-causal-policy-toolkit
pip install -e ".[dev]"
```

## 📖 Quick Start

### Basic Treatment Effect Estimation

```python
from krl_policy import TreatmentEffectEstimator, load_policy_dataset

# Load built-in dataset
dataset = load_policy_dataset("nsw")

# Estimate treatment effect with doubly robust method
estimator = TreatmentEffectEstimator(method="doubly_robust")
result = estimator.fit(
    y=dataset.outcome,
    treatment=dataset.treatment,
    X=dataset.covariates_data
)

print(f"Treatment Effect: {result.ate:.3f}")
print(f"95% CI: [{result.ci_lower:.3f}, {result.ci_upper:.3f}]")
print(f"P-value: {result.p_value:.4f}")
```

### Difference-in-Differences Analysis

```python
from krl_policy import DifferenceInDifferences, load_policy_dataset

# Load panel dataset
dataset = load_policy_dataset("medicaid")

# Run DiD analysis
did = DifferenceInDifferences()
result = did.fit(
    data=dataset.data,
    outcome_col="insurance_rate",
    treatment_col="medicaid_expansion",
    unit_col="state",
    time_col="year",
    covariates=["poverty_rate", "unemployment"]
)

print(f"Treatment Effect: {result.estimate:.3f}")

# Event study
event_study = did.event_study(
    data=dataset.data,
    outcome_col="insurance_rate",
    treatment_col="medicaid_expansion",
    unit_col="state",
    time_col="year"
)
```

### Unified Policy Evaluation

```python
from krl_policy import PolicyEvaluator, load_policy_dataset

dataset = load_policy_dataset("nsw")

# Compare multiple methods automatically
evaluator = PolicyEvaluator()
result = evaluator.evaluate(
    y=dataset.outcome,
    treatment=dataset.treatment,
    X=dataset.covariates_data,
    methods=["regression", "ipw", "doubly_robust", "matching"]
)

# Print comparison table
print(result.summary())

# Get recommended estimate
best = result.get_best_estimate()
print(f"Recommended Method: {best.method}")
print(f"Effect: {best.estimate:.3f}")
```

### Generate Professional Reports

```python
from krl_policy import ReportGenerator, TreatmentEffectEstimator, load_policy_dataset

dataset = load_policy_dataset("nsw")
estimator = TreatmentEffectEstimator(method="doubly_robust")
result = estimator.fit(
    y=dataset.outcome,
    treatment=dataset.treatment,
    X=dataset.covariates_data
)

# Create report in multiple formats
report = ReportGenerator(
    title="NSW Job Training Evaluation",
    author="Your Name"
)

report.add_title("Results")
report.add_estimate(result.get_estimate(), label="Average Treatment Effect")
report.add_diagnostics(result.diagnostics)

# Save in HTML, LaTeX, and Markdown
report.save_html("report.html")
report.save_latex("report.tex")
report.save_markdown("report.md")
```

## Available Tools

### 1. PolicyEvaluator
Standard framework for policy evaluation:
- Pre/post comparison
- Difference-in-differences
- Regression discontinuity
- Synthetic control
- Panel data methods

### 2. TreatmentEffectEstimator
Flexible treatment effect estimation:
- Propensity score matching
- Inverse probability weighting
- Regression adjustment
- Doubly robust estimation
- Heterogeneous effect analysis

### 3. CostBenefitAnalyzer
Comprehensive cost-benefit analysis:
- Monetization of impacts
- Discount rate sensitivity
- Monte Carlo simulation
- Distributional analysis
- Multi-criteria evaluation

### 4. SensitivityAnalyzer
Robustness testing:
- Placebo tests
- Randomization inference
- Confounding analysis
- Specification curves
- Leave-one-out analysis

### 5. ReportGenerator
Professional reporting:
- Executive summaries
- Technical appendices
- Visualizations (charts, maps, tables)
- LaTeX and HTML output
- Customizable templates

## Supported Methods

### Causal Inference Methods
- **Difference-in-Differences (DiD)**: Panel data with parallel trends
- **Synthetic Control**: Data-driven comparison units
- **Regression Discontinuity (RDD)**: Sharp and fuzzy designs
- **Propensity Score Matching (PSM)**: Matching on observables
- **Instrumental Variables (IV)**: Addressing endogeneity
- **Fixed Effects**: Individual and time fixed effects
- **Event Study**: Dynamic treatment effects

### Economic Evaluation
- **Cost-Benefit Analysis (CBA)**: Monetized impacts
- **Cost-Effectiveness Analysis (CEA)**: Outcomes per dollar
- **Return on Investment (ROI)**: Financial returns
- **Social Return on Investment (SROI)**: Broader impacts
- **Budget Impact Analysis**: Fiscal consequences

## Architecture

```
krl-causal-policy-toolkit/
├── src/krl_policy/
│   ├── __init__.py
│   ├── evaluators/           # Policy evaluation frameworks
│   │   ├── policy_evaluator.py
│   │   ├── treatment_effect.py
│   │   └── cost_benefit.py
│   ├── methods/              # Causal inference methods
│   │   ├── did.py
│   │   ├── synthetic_control.py
│   │   ├── rdd.py
│   │   └── psm.py
│   ├── analysis/             # Advanced analysis
│   │   ├── heterogeneity.py
│   │   ├── sensitivity.py
│   │   └── robustness.py
│   ├── reporting/            # Report generation
│   │   ├── templates/
│   │   ├── visualizations.py
│   │   └── generators.py
│   └── datasets/             # Synthetic datasets
│       └── examples.py
└── tests/
    ├── unit/
    └── integration/
```

## Example Datasets

The toolkit includes several synthetic datasets for demonstration:

- **minimum_wage_policy**: County-level employment and minimum wage changes
- **job_training_program**: Individual-level participant data
- **education_reform**: School district panel data
- **tax_policy**: State-level tax revenue and policy changes
- **healthcare_expansion**: Insurance coverage and health outcomes

```python
from krl_policy.datasets import load_example_dataset

# Load example dataset
data = load_example_dataset("minimum_wage_policy")
print(data.description)
print(data.variables)
```

## Best Practices

### 1. Identify Causal Question
Clearly define:
- Treatment/intervention
- Outcome of interest
- Comparison group
- Time period
- Population

### 2. Check Assumptions
Verify:
- Parallel trends (DiD)
- Common support (PSM)
- Continuity at cutoff (RDD)
- Donor pool validity (Synthetic Control)
- Instrument validity (IV)

### 3. Conduct Robustness Checks
Test:
- Alternative specifications
- Different time periods
- Placebo tests
- Falsification tests
- Sensitivity to unobservables

### 4. Report Transparently
Include:
- Descriptive statistics
- Balance tests
- Main estimates
- Standard errors
- Confidence intervals
- Sensitivity analysis

## 📚 Documentation

- **Full Documentation**: https://krl-causal-policy-toolkit.readthedocs.io
- **API Reference**: Comprehensive API docs with examples
- **User Guides**: Step-by-step tutorials for all features
- **Contributing**: Guidelines for contributors

## 🧪 Testing

All features are thoroughly tested with 293 passing tests and 100% coverage:

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=krl_policy --cov-report=html

# Run specific test file
pytest tests/test_treatment_effect.py -v
```

## 🤝 Contributing

We welcome contributions! Please see [CONTRIBUTING.md](docs/contributing.rst) for guidelines.

**Areas for contribution**:
- New causal inference methods
- Additional datasets
- Documentation improvements
- Bug reports and fixes

## 📄 License

MIT License - see [LICENSE](LICENSE) for details.

**Copyright** © 2024 Sudiata Giddasira, Inc. d/b/a Quipu Research Labs, LLC d/b/a KR-Labs™

**Trademark**: KR-Labs™ and Khipu Research Labs™ are trademarks of Quipu Research Labs, LLC.

## 📖 Citation

If you use this toolkit in your research, please cite:

```bibtex
@software{krl_causal_policy_toolkit,
  title = {KRL Causal Policy Toolkit},
  author = {{KR-Labs}},
  year = {2024},
  version = {1.0.0},
  url = {https://github.com/KR-Labs/krl-causal-policy-toolkit},
  doi = {10.5281/zenodo.XXXXXXX}
}
```

## 🔗 Related Projects

- [krl-open-core](https://github.com/KR-Labs/krl-open-core) - Core utilities and logging
- [krl-model-zoo](https://github.com/KR-Labs/krl-model-zoo) - Pre-trained models
- [krl-data-connectors](https://github.com/KR-Labs/krl-data-connectors) - Data integration
- [krl-tutorials](https://github.com/KR-Labs/krl-tutorials) - Learning resources

## 📚 References

- Angrist, J. D., & Pischke, J. S. (2009). *Mostly Harmless Econometrics*
- Cunningham, S. (2021). *Causal Inference: The Mixtape*
- Imbens, G. W., & Rubin, D. B. (2015). *Causal Inference for Statistics, Social, and Biomedical Sciences*
- Pearl, J. (2009). *Causality: Models, Reasoning, and Inference*

## 💬 Support

- **Issues**: [GitHub Issues](https://github.com/KR-Labs/krl-causal-policy-toolkit/issues)
- **Discussions**: [GitHub Discussions](https://github.com/orgs/KR-Labs/discussions)
- **Email**: support@kr-labs.ai

---

**Built with ❤️ by KR-Labs™ | Empowering Policy Analysis Through Causal Inference**