### CausalPy Quickstart Example Source: https://github.com/pymc-labs/causalpy/blob/main/README.md A quickstart example demonstrating how to load data, perform a Regression Discontinuity analysis, visualize the results, and get a summary of posterior estimates. Ensure matplotlib is installed for plotting. ```python import causalpy as cp import matplotlib.pyplot as plt # Import and process data df = ( cp.load_data("drinking") .rename(columns={"agecell": "age"}) .assign(treated=lambda df_: df_.age > 21) ) # Run the analysis result = cp.RegressionDiscontinuity( df, formula="all ~ 1 + age + treated", running_variable_name="age", model=cp.pymc_models.LinearRegression(), treatment_threshold=21, ) # Visualize the causal effect at the threshold fig, ax = result.plot() # Get a results summary with posterior estimates result.summary() ``` -------------------------------- ### Setup Imports and Configurations Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/its_placebo_in_time_analysis.ipynb Imports necessary libraries for data analysis and visualization, and sets up plotting configurations and warning filters. This is a standard setup for causal inference and data analysis tasks. ```python import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd import causalpy as cp %config InlineBackend.figure_format = 'retina' warnings.filterwarnings("ignore") ``` -------------------------------- ### PrePostNEGD Example Usage Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/prepostnegd.md Demonstrates how to load data, initialize the PrePostNEGD model with a custom PyMC model, and generate a summary and plot of the results. The example uses a LinearRegression model with specific sampling arguments. ```python import causalpy as cp df = cp.load_data("anova1") result = cp.PrePostNEGD( df, formula="post ~ 1 + C(group) + pre", group_variable_name="group", pretreatment_variable_name="pre", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Install CausalPy from GitHub Source: https://github.com/pymc-labs/causalpy/blob/main/README.md Install the very latest version of CausalPy directly from its GitHub repository. ```bash pip install git+https://github.com/pymc-labs/CausalPy.git ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_vs_priors.ipynb Imports necessary libraries for causal inference and data analysis, and sets up autoreload for development. ```python import arviz as az import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc as pm from scipy.special import expit from statsmodels.formula.api import ols import causalpy as cp %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Notebook Setup: Import Libraries Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/multi_cell_geolift.ipynb Imports necessary libraries for data manipulation, plotting, and causal inference. ```python import arviz as az import matplotlib.dates as mdates import matplotlib.pyplot as plt import pandas as pd import causalpy as cp ``` -------------------------------- ### Load Example Dataset in CausalPy Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/example-datasets/SKILL.md Import the CausalPy library and load a dataset using `cp.load_data()`. This is the primary method for accessing built-in example data. ```python import causalpy as cp df = cp.load_data("did") ``` -------------------------------- ### PiecewiseITS Example with Data Generation Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/piecewise_its.md Demonstrates how to create and run a PiecewiseITS model. Includes data generation, model initialization, and summary/plot generation. ```python import numpy as np import pandas as pd import causalpy as cp rng = np.random.default_rng(42) t = np.arange(100) df = pd.DataFrame({"t": t, "y": 1 + 0.05 * t + 2 * (t >= 50) + 0.03 * np.maximum(0, t - 50) + rng.normal(0, 0.2, len(t))}) result = cp.PiecewiseITS( data=df, formula="y ~ 1 + t + step(t, 50) + ramp(t, 50)", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Install Graphviz on Ubuntu/Debian Source: https://github.com/pymc-labs/causalpy/blob/main/scripts/run_notebooks/README.md Installs the Graphviz system dependency on Ubuntu/Debian systems. ```bash sudo apt-get update && sudo apt-get install -y graphviz ``` -------------------------------- ### Install Joblib for Parallel Execution Source: https://github.com/pymc-labs/causalpy/blob/main/scripts/run_notebooks/README.md Installs the joblib library to enable parallel execution of notebooks. ```bash pip install joblib ``` -------------------------------- ### Panel Regression Example Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/panel_regression.md Example demonstrating how to create and use `PanelRegression` with synthetic panel data. Includes data generation, model setup with PyMC, and running summary and plot methods. ```python import numpy as np import pandas as pd import causalpy as cp units = [f"unit_{i}" for i in range(8)] times = range(6) rng = np.random.default_rng(42) df = pd.DataFrame( [ { "unit": unit, "time": time, "treatment": int(unit in units[:4] and time >= 3), "x1": rng.normal(), "y": rng.normal() + 0.5 * int(unit in units[:4] and time >= 3), } for unit in units for time in times ] ) result = cp.PanelRegression( data=df, formula="y ~ C(unit) + C(time) + treatment + x1", unit_fe_variable="unit", time_fe_variable="time", fe_method="dummies", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() result.plot() ``` -------------------------------- ### Notebook Setup: Configuration Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/multi_cell_geolift.ipynb Sets a random seed for reproducibility and configures plotting and display options. ```python seed = 42 ``` ```python %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = "retina" pd.set_option("display.precision", 2) ``` -------------------------------- ### Run tests Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Verifies the project setup by running the test suite within the activated CausalPy environment. ```bash make test ``` -------------------------------- ### Install JAX and NumPyro (optional) Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_weak_instruments.ipynb Provides commands to install JAX and NumPyro using conda. These libraries can significantly speed up posterior predictive sampling in the InstrumentalVariable class. ```bash !conda install jax !conda install numpyro ``` -------------------------------- ### Install Graphviz on macOS Source: https://github.com/pymc-labs/causalpy/blob/main/scripts/run_notebooks/README.md Installs the Graphviz system dependency on macOS using Homebrew. ```bash brew install graphviz ``` -------------------------------- ### DifferenceInDifferences Example Usage Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/diff_in_diff.md Demonstrates how to load data, instantiate the DifferenceInDifferences model with a specified formula and time/group variables, and then generate a summary and plot. ```python import causalpy as cp df = cp.load_data("did") result = cp.DifferenceInDifferences( df, formula="y ~ 1 + group * post_treatment", time_variable_name="t", group_variable_name="group", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### RegressionKink Example Usage Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/regression_kink.md Demonstrates how to create and use the RegressionKink model. This includes generating sample data, defining the model with a specific formula and bandwidth, and then summarizing and plotting the results. ```python import numpy as np import pandas as pd import causalpy as cp kink_point = 0.0 rng = np.random.default_rng(42) x = np.linspace(-1, 1, 100) df = pd.DataFrame({"x": x}) df["treated"] = (df["x"] >= kink_point).astype(int) df["y"] = 1 + 0.5 * df["x"] + 2 * (df["x"] - kink_point) * df["treated"] + rng.normal(0, 0.1, len(df)) result = cp.RegressionKink( data=df, formula=f"y ~ 1 + x + I((x - {kink_point}) * treated)", kink_point=kink_point, running_variable_name="x", bandwidth=1.0, model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### IPW Example with Data Loading and Plotting Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/inverse_propensity_weighting.md Demonstrates loading data, initializing IPW with a robust weighting scheme and a custom PyMC model, and plotting ATE and covariate balance. ```python import causalpy as cp df = cp.load_data("nhefs") result = cp.InversePropensityWeighting( df, formula="trt ~ 1 + age + race", outcome_variable="outcome", weighting_scheme="robust", model=cp.pymc_models.PropensityScore(sample_kwargs={"target_accept": 0.95}), ) result.plot_ate() result.plot_balance_ecdf(covariate="age") ``` -------------------------------- ### Install micromamba Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Installs micromamba, a lightweight package manager, which can be used as a substitute for conda. ```bash "${SHELL}" <(curl -L micro.mamba.pm/install.sh) ``` -------------------------------- ### Install CausalPy using pip Source: https://github.com/pymc-labs/causalpy/blob/main/README.md Install the latest release of CausalPy using pip. ```bash pip install CausalPy ``` -------------------------------- ### Instrumental Variable Constructor and Example Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/instrumental_variable.md Demonstrates how to initialize and use the `cp.InstrumentalVariable` class with sample data. This includes setting up dataframes, defining formulas, and specifying model priors. ```python import numpy as np import pandas as pd import causalpy as cp rng = np.random.default_rng(42) n = 100 z = rng.normal(size=n) x = rng.normal(size=n) unobserved = rng.normal(size=n) t = 0.8 * z + 0.5 * x + unobserved + rng.normal(size=n) y = 1.5 * t + 0.5 * x + unobserved + rng.normal(size=n) df = pd.DataFrame({"y": y, "t": t, "x": x, "z": z}) result = cp.InstrumentalVariable( instruments_data=df[["t", "z"]], data=df[["y", "t", "x"]], instruments_formula="t ~ 1 + z", formula="y ~ 1 + t + x", model=cp.pymc_models.InstrumentalVariableRegression( sample_kwargs={"target_accept": 0.95} ), priors={ "mus": [[0, 0], [0, 0, 0]], "sigmas": [2, 5], "eta": 2, "lkj_sd": 1, }, ) ``` -------------------------------- ### Setup and Imports for CausalPy Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/its_lift_test.ipynb Imports necessary libraries for data manipulation, modeling, and visualization. Sets up autoreload and inline plotting. ```python import inspect import arviz as az import matplotlib.pyplot as plt import numpy as np import pandas as pd from pymc_marketing.mmm.transformers import geometric_adstock, logistic_saturation from pytensor.xtensor import as_xtensor import causalpy as cp %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' # Set random seed for reproducibility seed = 42 rng = np.random.default_rng(seed) ``` -------------------------------- ### RegressionDiscontinuity Example Usage Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/regression_discontinuity.md Demonstrates how to instantiate and use the RegressionDiscontinuity class with a sample dataset, including data preparation, model fitting, and summary generation. ```python import causalpy as cp df = cp.load_data("drinking") df = df.rename(columns={"agecell": "age"}).assign(treated=lambda d: d.age > 21) result = cp.RegressionDiscontinuity( df, formula="all ~ 1 + age + treated + age:treated", running_variable_name="age", treatment_threshold=21, model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Setup and Fit Instrumental Variable Model Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_pymc.ipynb Initializes and fits an InstrumentalVariable model using PyMC. Requires `CausalPy` and `arviz` libraries. Ensure data is preprocessed and relevant formulas are defined. ```python sample_kwargs = {"tune": 1000, "draws": 2000, "chains": 4, "cores": 4} instruments_formula = "risk ~ 1 + logmort0" formula = "loggdp ~ 1 + risk" instruments_data = iv_df[["risk", "logmort0"]] data = iv_df[["loggdp", "risk"]] iv = InstrumentalVariable( instruments_data=instruments_data, data=data, instruments_formula=instruments_formula, formula=formula, model=InstrumentalVariableRegression(sample_kwargs=sample_kwargs), ) az.plot_trace(iv.model.idata, var_names=["beta_z", "beta_t"]); ``` -------------------------------- ### Staggered Difference-in-Differences Example Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/staggered_did.md Demonstrates how to create and use the StaggeredDifferenceInDifferences class with sample data. Includes data generation, model instantiation, and summary/plot generation. ```python import numpy as np import pandas as pd import causalpy as cp units = [f"unit_{i}" for i in range(8)] times = range(8) treatment_times = {unit: 4 + (i % 2) for i, unit in enumerate(units[:6])} rng = np.random.default_rng(42) df = pd.DataFrame( [ { "unit": unit, "time": time, "treatment_time": treatment_times.get(unit, np.inf), "treated": int(time >= treatment_times.get(unit, np.inf)), "y": rng.normal() + 0.8 * int(time >= treatment_times.get(unit, np.inf)), } for unit in units for time in times ] ) result = cp.StaggeredDifferenceInDifferences( data=df, formula="y ~ 1 + C(unit) + C(time)", unit_variable_name="unit", time_variable_name="time", treated_variable_name="treated", treatment_time_variable_name="treatment_time", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Configure and display results using maketables Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/did_pymc.ipynb Sets `maketables` options for HDI probability and displays the results in a formatted table. This requires the `maketables` package to be installed. ```python from maketables import ETable result.set_maketables_options(hdi_prob=0.95) ETable(result, coef_fmt="b:.3f \n [ci95l:.3f, ci95u:.3f]") ``` -------------------------------- ### Interrupted Time Series Example Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/interrupted_time_series.md Demonstrates how to load data, set up a DataFrame, define the treatment time, and instantiate the InterruptedTimeSeries model with a LinearRegression backend. It also shows how to generate a summary and plot the results. ```python import causalpy as cp import pandas as pd df = cp.load_data("its") df["date"] = pd.to_datetime(df["date"]) df.set_index("date", inplace=True) treatment_time = pd.to_datetime("2017-01-01") result = cp.InterruptedTimeSeries( df, treatment_time, formula="y ~ 1 + t + C(month)", model=cp.pymc_models.LinearRegression(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Running a Synthetic Difference-in-Differences Experiment Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/synthetic_difference_in_differences.md Example of setting up and running a Synthetic Difference-in-Differences analysis using CausalPy. This includes loading data, initializing the model with specific PyMC sampling arguments, and generating a summary and plot of the results. ```python import causalpy as cp df = cp.load_data("sc") result = cp.SyntheticDifferenceInDifferences( df, treatment_time=70, control_units=["a", "b", "c", "d", "e", "f", "g"], treated_units=["actual"], model=cp.pymc_models.SyntheticDifferenceInDifferencesWeightFitter( sample_kwargs={"target_accept": 0.95} ), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Run this command from the project root to build the documentation locally. ```bash make html ``` -------------------------------- ### Install CausalPy using conda Source: https://github.com/pymc-labs/causalpy/blob/main/README.md Install CausalPy using conda from the conda-forge channel. ```bash conda install causalpy -c conda-forge ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/pymc-labs/causalpy/blob/main/scripts/run_notebooks/README.md Installs project dependencies including Papermill and notebook-related packages. ```bash pip install -e ".[test,docs]" ``` -------------------------------- ### Install package and dependencies Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Installs the CausalPy package, all development dependencies, and pre-commit hooks within the specified conda environment. ```bash conda run -n CausalPy make setup ``` -------------------------------- ### Example Interpretation of Bayesian Statistics Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/knowledgebase/reporting_statistics.md This example shows how to interpret a typical output combining a point estimate (mean) and an uncertainty interval (HDI). ```text mean: 2.5, 95% HDI: [1.2, 3.8] "The estimated effect is 2.5 on average, and we can be 95% certain the true effect lies between 1.2 and 3.8." ``` -------------------------------- ### Configure Notebook Environment Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/did_pymc_banks.ipynb Sets up the notebook environment by enabling autoreload, setting the inline backend for figures, defining a random seed, and ignoring future warnings. It also applies a specific ArviZ style. ```python %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' seed = 42 warnings.simplefilter(action="ignore", category=FutureWarning) # Set arviz style to override seaborn's default az.style.use("arviz-darkgrid") ``` -------------------------------- ### PrePostNEGD Constructor Signature Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/prepostnegd.md Shows the required arguments for initializing the PrePostNEGD class. Ensure your data, formula, group variable, and pretreatment variable are correctly specified. ```python cp.PrePostNEGD( data, formula, group_variable_name, pretreatment_variable_name, model=None, **kwargs ) ``` -------------------------------- ### Install Jupyter Kernel for CausalPy Environment Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Make Jupyter Lab aware of the CausalPy environment by installing its kernel. This is necessary if you are editing or writing Jupyter notebooks. ```bash conda run -n CausalPy python -m ipykernel install --user --name CausalPy ``` -------------------------------- ### Clean and Rebuild Documentation Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Use these commands to clean the existing documentation build and then rebuild it from scratch. ```bash make cleandocs make html ``` -------------------------------- ### Configure Environment and Load Data Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/geolift1.ipynb Sets up the environment for plotting and data display, and loads the geolift dataset. The data is then processed to set the 'time' column as the datetime index. ```python %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' pd.set_option("display.precision", 2) seed = 42 ``` ```python df = ( cp.load_data("geolift1") .assign(time=lambda x: pd.to_datetime(x["time"])) .set_index("time") ) treatment_time = pd.to_datetime("2022-01-01") df.head() ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Build the project documentation locally using conda and make. This is necessary to check that documentation changes appear correctly. ```bash conda run -n CausalPy make html ``` -------------------------------- ### Get Prose Summary of Causal Effects Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/staggered_did_pymc.ipynb Use the `effect_summary()` method to get a textual summary of the average post-treatment effect and the results of the pre-treatment placebo check. This helps in assessing the parallel trends assumption. ```python effect_summary = result.effect_summary() print(effect_summary.text) ``` -------------------------------- ### Get Numerical Summary Table Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/knowledgebase/reporting_statistics.md Access the pandas DataFrame containing all statistics from the `effect_summary()` output. ```python summary = result.effect_summary() print(summary.table) ``` -------------------------------- ### Run Doctests with Make Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Execute all doctests in the project using the make command. This is a recommended step before submitting a pull request. ```bash make doctest ``` -------------------------------- ### Initialize and Sample Instrumental Variable Model Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_weak_instruments.ipynb Initialize the InstrumentalVariable model with the prepared data and formulas. Then, sample the predictive distribution using the 'jax' sampler. This step requires 'sample_kwargs' to be defined previously. ```python iv1 = InstrumentalVariable( instruments_data=instruments_data, data=data, instruments_formula=instruments_formula, formula=formula, model=InstrumentalVariableRegression(sample_kwargs=sample_kwargs), ) iv1.model.sample_predictive_distribution(ppc_sampler="jax") ``` -------------------------------- ### Load and Inspect Data Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_pymc.ipynb Loads the 'risk' dataset and displays the head of relevant columns. Ensure the causalpy library is installed and imported as 'cp'. ```python iv_df = cp.load_data("risk") iv_df[["longname", "loggdp", "risk", "logmort0"]].head() ``` -------------------------------- ### NUTS Sampler Initialization (Normal Model) Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/knowledgebase/structural_causal_models.ipynb Shows the initialization of the NUTS sampler for a standard normal model. This output details the parameters being sampled and the sampler configuration. ```text Output: Sampling: [alpha, beta_O, beta_T, likelihood, m, rho, s, sigma_U, sigma_V] Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [beta_O, beta_T, alpha, sigma_U, sigma_V, m, s, rho] ``` -------------------------------- ### Configure Sampler Arguments for PyMC Models Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/its_placebo_in_time_analysis.ipynb Sets up keyword arguments for the NUTS sampler, specifying 'nutpie' as the sampler and configuring JAX for gradient computation. This is useful for optimizing sampling performance in PyMC models. ```python sampler_kwargs = { "nuts_sampler": "nutpie", "nuts_sampler_kwargs": {"backend": "jax", "gradient_backend": "jax"}, "target_accept": 0.94, } ``` -------------------------------- ### Configure Sampling Parameters Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_vs_priors.ipynb Sets up keyword arguments for the PyMC sampling process, including draws, tuning steps, chains, and random seed. Adjust `target_accept` if divergences occur. ```python sample_kwargs = { "draws": 1000, "tune": 1000, "chains": 4, "cores": 4, "target_accept": 0.9, "progressbar": True, "random_seed": 42, "nuts_sampler": "numpyro", } ``` -------------------------------- ### Get Prose Summary Text Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/knowledgebase/reporting_statistics.md Retrieve a human-readable interpretation of the results, suitable for reports. This includes the average treatment effect and its confidence interval. ```python print(summary.text) # Output: "The average treatment effect was 2.50 (95% HDI [1.20, 3.80]), # with a posterior probability of an increase of 0.975." ``` -------------------------------- ### Load and Preprocess School Returns Data Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/iv_weak_instruments.ipynb Loads the 'schoolReturns' dataset and preprocesses it by creating polynomial features for experience and age, and generating indicator variables for various categorical features. Use this for initial data preparation. ```python df = cp.load_data("schoolReturns") def poly(x, p): # replicate R's poly decomposition function X = np.transpose(np.vstack([x**k for k in range(p + 1)])) return np.linalg.qr(X)[0][:, 1:] df["log_wage"] = np.log(df["wage"]) df[["experience_1", "experience_2"]] = pd.DataFrame(poly(df["experience"].values, 2)) df[["age_1", "age_2"]] = poly(df["age"].values, 2) df["nearcollege_indicator"] = np.where( df["nearcollege"] == "yes", 1, 0 ) # 4 year college df["nearcollege2_indicator"] = np.where( df["nearcollege2"] == "yes", 1, 0 ) # 2 year college df["nearcollege4_indicator"] = np.where( df["nearcollege4"] == "yes", 1, 0 ) # 4 year public or private college df["south_indicator"] = np.where(df["south"] == "yes", 1, 0) # southern US df["smsa_indicator"] = np.where( df["smsa"] == "yes", 1, 0 ) # standard metropolitan statistical area df["ethnicity_indicator"] = np.where( df["ethnicity"] == "afam", 1, 0 ) # African-American or other df[["wage", "education", "experience", "ethnicity", "nearcollege"]].head(5) ``` -------------------------------- ### Get Regression Kink Effect Summary Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/rkink_pymc.ipynb Provides a summary of the effect of the kink point, specifically the change in gradient. Requires `result1` to be defined. ```python stats1 = result1.effect_summary() stats1.table ``` -------------------------------- ### Fast Linting Check with Ruff Source: https://github.com/pymc-labs/causalpy/blob/main/AGENTS.md Perform a quick linting check on the causalpy directory during development to get fast feedback on potential issues. ```bash ruff check causalpy/ ``` -------------------------------- ### NUTS Sampler Initialization Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/knowledgebase/structural_causal_models.ipynb Shows the initialization of the NUTS sampler with jitter+adapt_diag. This output indicates the sampler is preparing to draw samples from the posterior distribution. ```text Output: Sampling: [alpha, beta_O_raw, beta_T_raw, gamma_O_u, gamma_T_u, likelihood, m, pi_O, pi_T, rho, s, sigma_U, sigma_V] Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [pi_O, beta_O_raw, gamma_O_u, pi_T, beta_T_raw, gamma_T_u, alpha, sigma_U, sigma_V, m, s, rho] ``` -------------------------------- ### Run NUTS Sampler for Simple Regression Model Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/inv_prop_latent.ipynb Initializes and runs the NUTS sampler for a simple regression model. This step is crucial for obtaining posterior estimates. ```python Sampling 4 chains for 2_000 tune and 2_000 draw iterations (8_000 + 8_000 draws total) took 14 seconds. Sampling: [alpha_outcome, beta_ps, beta_std, like, nu, sigma] Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [beta_std, beta_ps, alpha_outcome, sigma, nu] ``` -------------------------------- ### Get Post-Intervention Period Summary Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/its_post_intervention_analysis.ipynb Retrieves a detailed summary of the causal effect during the post-intervention period. Specify 'period="post"' to focus on this phase. ```python # Post-intervention period post_summary = result.effect_summary(period="post") print(post_summary.text) ``` -------------------------------- ### Running a Synthetic Control Experiment Source: https://github.com/pymc-labs/causalpy/blob/main/causalpy/skills/running-causalpy-experiments/reference/synthetic_control.md Loads sample data, defines the treatment time, and initializes the SyntheticControl model. It then generates a summary and plots the results. The `WeightedSumFitter` is used with specific sampling arguments. ```python import causalpy as cp df = cp.load_data("sc") treatment_time = 70 result = cp.SyntheticControl( df, treatment_time, control_units=["a", "b", "c", "d", "e"], treated_units=["actual"], model=cp.pymc_models.WeightedSumFitter(sample_kwargs={"target_accept": 0.95}), ) result.summary() summary = result.effect_summary(direction="increase") result.plot() ``` -------------------------------- ### Get Intervention Period Summary Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/its_post_intervention_analysis.ipynb Retrieves a detailed summary of the causal effect during the intervention period. Specify 'period="intervention"' to focus on this phase. ```python # Intervention period intervention_summary = result.effect_summary(period="intervention") print(intervention_summary.text) ``` -------------------------------- ### Initialize Inverse Propensity Weighting Model Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/inv_prop_pymc.ipynb Sets up the Inverse Propensity Weighting experiment using a specified formula, outcome variable, and a PyMC propensity score model with custom sampling arguments. ```python formula = """trt ~ 1 + age + race + sex + smokeintensity + smokeyrs + wt71 + active_1 + active_2 + education_2 + education_3 + education_4 + education_5 + exercise_1 + exercise_2""" result = cp.InversePropensityWeighting( df_standardised, formula=formula, outcome_variable="outcome", weighting_scheme="robust", ## Will be used by plots after estimation if no other scheme is specified. model=cp.pymc_models.PropensityScore( sample_kwargs={ "draws": 1000, "target_accept": 0.95, "random_seed": seed, "progressbar": False, }, ), ) result ``` -------------------------------- ### Create DataFrame with Datetime Index Source: https://github.com/pymc-labs/causalpy/blob/main/docs/source/notebooks/piecewise_its_pymc.ipynb Generates a pandas DataFrame with a datetime index and a target variable 'y'. This setup is used to demonstrate time series analysis with datetime-based interventions. ```python # Create data with datetime index import pandas as pd np.random.seed(42) dates = pd.date_range("2020-01-01", periods=150, freq="D") t_numeric = np.arange(150) y = ( 100 + 0.1 * t_numeric + 5 * (t_numeric >= 50) + 0.15 * np.maximum(0, t_numeric - 50) + np.random.randn(150) * 2 ) df_datetime = pd.DataFrame({"date": dates, "y": y}) ``` -------------------------------- ### Clone repository and set up environment Source: https://github.com/pymc-labs/causalpy/blob/main/CONTRIBUTING.md Clones the CausalPy repository and creates a conda environment from the provided YAML file. ```bash git clone git@github.com:/CausalPy.git && cd CausalPy conda env create -f environment.yml ```