{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "2b2a0fd8", "metadata": {}, "source": [ "# Python: Impact of 401(k) on Financial Wealth" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a967ed5f", "metadata": {}, "source": [ "In this real-data example, we illustrate how the [DoubleML](https://docs.doubleml.org/stable/index.html) package can be used to estimate the effect of 401(k) eligibility and participation on accumulated assets. The 401(k) data set has been analyzed in several studies, among others [Chernozhukov et al. (2018)](https://arxiv.org/abs/1608.00060).\n", "\n", "401(k) plans are pension accounts sponsored by employers. The key problem in determining the effect of participation in 401(k) plans on accumulated assets is saver heterogeneity coupled with the fact that the decision to enroll in a 401(k) is non-random. It is generally recognized that some people have a higher preference for saving than others. It also seems likely that those individuals with high unobserved preference for saving would be most likely to choose to participate in tax-advantaged retirement savings plans and would tend to have otherwise high amounts of accumulated assets. The presence of unobserved savings preferences with these properties then implies that conventional estimates that do not account for saver heterogeneity and endogeneity of participation will be biased upward, tending to overstate the savings effects of 401(k) participation.\n", "\n", "One can argue that eligibility for enrolling in a 401(k) plan in this data can be taken as exogenous after conditioning on a few observables of which the most important for their argument is income. The basic idea is that, at least around the time 401(k)’s initially became available, people were unlikely to be basing their employment decisions on whether an employer offered a 401(k) but would instead focus on income and other aspects of the job." ] }, { "attachments": {}, "cell_type": "markdown", "id": "40b41785", "metadata": {}, "source": [ "## Data\n", "\n", "The preprocessed data can be fetched by calling [fetch_401K()](https://docs.doubleml.org/stable/api/generated/doubleml.datasets.fetch_401K.html#doubleml.datasets.fetch_401K). Note that an internet connection is required for loading the data." ] }, { "cell_type": "code", "execution_count": null, "id": "c06e87b2", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import doubleml as dml\n", "from doubleml.datasets import fetch_401K\n", "\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.linear_model import LassoCV, LogisticRegressionCV\n", "from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\n", "from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.pipeline import make_pipeline\n", "\n", "from xgboost import XGBClassifier, XGBRegressor\n", "\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns" ] }, { "cell_type": "code", "execution_count": null, "id": "28347df3", "metadata": {}, "outputs": [], "source": [ "sns.set()\n", "colors = sns.color_palette()" ] }, { "cell_type": "code", "execution_count": null, "id": "0ad5caf0", "metadata": {}, "outputs": [], "source": [ "plt.rcParams['figure.figsize'] = 10., 7.5\n", "sns.set(font_scale=1.5)\n", "sns.set_style('whitegrid', {'axes.spines.top': False,\n", " 'axes.spines.bottom': False,\n", " 'axes.spines.left': False,\n", " 'axes.spines.right': False})" ] }, { "cell_type": "code", "execution_count": null, "id": "11763be2", "metadata": {}, "outputs": [], "source": [ "data = fetch_401K(return_type='DataFrame')" ] }, { "cell_type": "code", "execution_count": null, "id": "853ba4be", "metadata": {}, "outputs": [], "source": [ "# Temporary fix for https://github.com/DoubleML/doubleml-docs/issues/45 / https://github.com/scikit-learn/scikit-learn/issues/21997\n", "# Can be removed when scikit-learn version 1.2.0 is released\n", "dtypes = data.dtypes\n", "dtypes['nifa'] = 'float64'\n", "dtypes['net_tfa'] = 'float64'\n", "dtypes['tw'] = 'float64'\n", "dtypes['inc'] = 'float64'\n", "data = data.astype(dtypes)" ] }, { "cell_type": "code", "execution_count": null, "id": "cf8659c7", "metadata": {}, "outputs": [], "source": [ "print(data.head())" ] }, { "cell_type": "code", "execution_count": null, "id": "c1d9ce03", "metadata": {}, "outputs": [], "source": [ "print(data.describe())" ] }, { "attachments": {}, "cell_type": "markdown", "id": "3ea8c00f", "metadata": {}, "source": [ "The data consist of 9,915 observations at the household level drawn from the 1991 Survey of Income and Program Participation (SIPP). All the variables are referred to 1990. We use net financial assets (*net\\_tfa*) as the outcome variable, $Y$, in our analysis. The net financial assets are computed as the sum of IRA balances, 401(k) balances, checking accounts, saving bonds, other interest-earning accounts, other interest-earning assets, stocks, and mutual funds less non mortgage debts. " ] }, { "attachments": {}, "cell_type": "markdown", "id": "1a4f9dc4", "metadata": {}, "source": [ "Among the $9915$ individuals, $3682$ are eligible to participate in the program. The variable *e401* indicates eligibility and *p401* indicates participation, respectively." ] }, { "cell_type": "code", "execution_count": null, "id": "1fb9537b", "metadata": {}, "outputs": [], "source": [ "data['e401'].value_counts().plot(kind='bar', color=colors)\n", "plt.title('Eligibility, 401(k)')\n", "plt.xlabel('e401')\n", "_ = plt.ylabel('count')" ] }, { "cell_type": "code", "execution_count": null, "id": "3d464563", "metadata": {}, "outputs": [], "source": [ "data['p401'].value_counts().plot(kind='bar', color=colors)\n", "plt.title('Participation, 401(k)')\n", "plt.xlabel('p401')\n", "_ = plt.ylabel('count')" ] }, { "attachments": {}, "cell_type": "markdown", "id": "b8461a88", "metadata": {}, "source": [ "Eligibility is highly associated with financial wealth:" ] }, { "cell_type": "code", "execution_count": null, "id": "9ab147b8", "metadata": {}, "outputs": [], "source": [ "_ = sns.displot(data, x=\"net_tfa\", hue=\"e401\", col=\"e401\",\n", " kind=\"kde\", fill=True)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "aae566a4", "metadata": {}, "source": [ "As a first estimate, we calculate the unconditional average predictive effect (APE) of 401(k) eligibility on accumulated assets. This effect corresponds to the average treatment effect if 401(k) eligibility would be assigned to individuals in an entirely randomized way. The unconditional APE of e401 is about $19559$:" ] }, { "cell_type": "code", "execution_count": null, "id": "97d9b759", "metadata": {}, "outputs": [], "source": [ "print(data[['e401', 'net_tfa']].groupby('e401').mean().diff())" ] }, { "attachments": {}, "cell_type": "markdown", "id": "491fc066", "metadata": {}, "source": [ "Among the $3682$ individuals that are eligible, $2594$ decided to participate in the program. The unconditional APE of p401 is about $27372$:" ] }, { "cell_type": "code", "execution_count": null, "id": "7f1660be", "metadata": {}, "outputs": [], "source": [ "print(data[['p401', 'net_tfa']].groupby('p401').mean().diff())" ] }, { "attachments": {}, "cell_type": "markdown", "id": "58862aff", "metadata": {}, "source": [ "As discussed, these estimates are biased since they do not account for saver heterogeneity and endogeneity of participation." ] }, { "attachments": {}, "cell_type": "markdown", "id": "bdb138b7", "metadata": {}, "source": [ "## The `DoubleML` package" ] }, { "attachments": {}, "cell_type": "markdown", "id": "d871d878", "metadata": {}, "source": [ "Let's use the package [DoubleML](https://docs.doubleml.org/stable/index.html) to estimate the average treatment effect of 401(k) eligibility, i.e. `e401`, and participation, i.e. `p401`, on net financial assets `net_tfa`." ] }, { "attachments": {}, "cell_type": "markdown", "id": "7c626f03", "metadata": {}, "source": [ "## Estimating the Average Treatment Effect of 401(k) Eligibility on Net Financial Assets" ] }, { "attachments": {}, "cell_type": "markdown", "id": "8f1f0cbb", "metadata": {}, "source": [ "We first look at the treatment effect of `e401` on net total financial assets. We give estimates of the ATE in the linear model\n", "\n", "$$\n", "\\begin{equation*}\n", "Y = D \\alpha + f(X)'\\beta+ \\epsilon,\n", "\\end{equation*}\n", "$$\n", "\n", "where $f(X)$ is a dictonary applied to the raw regressors. $X$ contains variables on marital status, two-earner status, defined benefit pension status, IRA participation, home ownership, family size, education, age, and income. \n", "\n", "In the following, we will consider two different models, \n", "\n", "* a basic model specification that includes the raw regressors, i.e., $f(X) = X$, and \n", "\n", "* a flexible model specification, where $f(X)$ includes the raw regressors $X$ and the orthogonal polynomials of degree 2 for the variables family size education, age, and income. \n", "\n", "We will use the basic model specification whenever we use nonlinear methods, for example regression trees or random forests, and use the flexible model for linear methods such as the lasso. There are, of course, multiple ways how the model can be specified even more flexibly, for example including interactions of variable and higher order interaction. However, for the sake of simplicity we stick to the specification above. Users who are interested in varying the model can adapt the code below accordingly, for example to implement the orignal specification in [Chernozhukov et al. (2018)](https://arxiv.org/abs/1608.00060). \n", "\n", "In the first step, we report estimates of the average treatment effect (ATE) of 401(k) eligibility on net financial assets both in the partially linear regression (PLR) model and in the interactive regression model (IRM) allowing for heterogeneous treatment effects." ] }, { "attachments": {}, "cell_type": "markdown", "id": "59d03336", "metadata": {}, "source": [ "### The Data Backend: `DoubleMLData`" ] }, { "attachments": {}, "cell_type": "markdown", "id": "2e1fe478", "metadata": {}, "source": [ "To start our analysis, we initialize the data backend, i.e., a new instance of a [DoubleMLData](https://docs.doubleml.org/dev/api/generated/doubleml.DoubleMLData.html#doubleml.DoubleMLData) object. We implement the regression model by using scikit-learn's `PolynomialFeatures` class.\n", "\n", "To implement both models (basic and flexible), we generate two data backends: `data_dml_base` and `data_dml_flex`." ] }, { "cell_type": "code", "execution_count": null, "id": "a69acf79", "metadata": {}, "outputs": [], "source": [ "# Set up basic model: Specify variables for data-backend\n", "features_base = ['age', 'inc', 'educ', 'fsize', 'marr',\n", " 'twoearn', 'db', 'pira', 'hown']\n", "\n", "# Initialize DoubleMLData (data-backend of DoubleML)\n", "data_dml_base = dml.DoubleMLData(data,\n", " y_col='net_tfa',\n", " d_cols='e401',\n", " x_cols=features_base)" ] }, { "cell_type": "code", "execution_count": null, "id": "283cb128", "metadata": {}, "outputs": [], "source": [ "print(data_dml_base)" ] }, { "cell_type": "code", "execution_count": null, "id": "4f8f4463", "metadata": {}, "outputs": [], "source": [ "# Set up a model according to regression formula with polynomials\n", "features = data.copy()[['marr', 'twoearn', 'db', 'pira', 'hown']]\n", "\n", "poly_dict = {'age': 2,\n", " 'inc': 2,\n", " 'educ': 2,\n", " 'fsize': 2}\n", "for key, degree in poly_dict.items():\n", " poly = PolynomialFeatures(degree, include_bias=False)\n", " data_transf = poly.fit_transform(data[[key]])\n", " x_cols = poly.get_feature_names_out([key])\n", " data_transf = pd.DataFrame(data_transf, columns=x_cols)\n", " \n", " features = pd.concat((features, data_transf),\n", " axis=1, sort=False)\n", "model_data = pd.concat((data.copy()[['net_tfa', 'e401']], features.copy()),\n", " axis=1, sort=False)\n", "\n", "# Initialize DoubleMLData (data-backend of DoubleML)\n", "data_dml_flex = dml.DoubleMLData(model_data, y_col='net_tfa', d_cols='e401')" ] }, { "cell_type": "code", "execution_count": null, "id": "4d5885ed", "metadata": {}, "outputs": [], "source": [ "print(data_dml_flex)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a85b7f11", "metadata": {}, "source": [ "### Partially Linear Regression Model (PLR)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "f4794f98", "metadata": {}, "source": [ "We start using lasso to estimate the function $g_0$ and $m_0$ in the following PLR model:" ] }, { "attachments": {}, "cell_type": "markdown", "id": "77aac812", "metadata": {}, "source": [ "$$\n", "\\begin{aligned}\n", "& Y = D\\theta_0 + g_0(X) + \\zeta, &\\quad E[\\zeta \\mid D,X]= 0,\\\\\n", "& D = m_0(X) + V, &\\quad E[V \\mid X] = 0.\n", "\\end{aligned}\n", "$$" ] }, { "attachments": {}, "cell_type": "markdown", "id": "8aaaa9ff", "metadata": {}, "source": [ "To estimate the causal parameter $\\theta_0$ here, we use double machine learning with 3-fold cross-fitting. \n", " \n", "Estimation of the nuisance components $g_0$ and $m_0$, is based on the lasso with cross-validated choice of the penalty term , $\\lambda$, as provided by [scikit-learn](https://scikit-learn.org). We load the learner by initializing instances from the classes [LassoCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html) and [LogisticRegressionCV](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html). Hyperparameters and options can be set during instantiation of the learner. Here we specify that the lasso should use that value of $\\lambda$ that minimizes the cross-validated mean squared error which is based on 5-fold cross validation.\n", "\n", "We start by estimation the ATE in the basic model and then repeat the estimation in the flexible model." ] }, { "cell_type": "code", "execution_count": null, "id": "6481a766", "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Initialize learners\n", "Cs = 0.0001*np.logspace(0, 4, 10)\n", "lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=10000))\n", "lasso_class = make_pipeline(StandardScaler(),\n", " LogisticRegressionCV(cv=5, penalty='l1', solver='liblinear',\n", " Cs = Cs, max_iter=1000))\n", "\n", "np.random.seed(123)\n", "# Initialize DoubleMLPLR model\n", "dml_plr_lasso = dml.DoubleMLPLR(data_dml_base,\n", " ml_l = lasso,\n", " ml_m = lasso_class,\n", " n_folds = 3)\n", "\n", "dml_plr_lasso.fit(store_predictions=True)\n", "print(dml_plr_lasso.summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "355e78ca", "metadata": {}, "outputs": [], "source": [ "# Estimate the ATE in the flexible model with lasso\n", "\n", "np.random.seed(123)\n", "dml_plr_lasso = dml.DoubleMLPLR(data_dml_flex,\n", " ml_l = lasso,\n", " ml_m = lasso_class,\n", " n_folds = 3)\n", "\n", "dml_plr_lasso.fit(store_predictions=True)\n", "lasso_summary = dml_plr_lasso.summary\n", "\n", "print(lasso_summary)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "92407d1e", "metadata": {}, "source": [ "Alternatively, we can repeat this procedure with other machine learning methods, for example a random forest learner as provided by the [RandomForestRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) and [RandomForestClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html) class in [scikit-learn](https://scikit-learn.org). " ] }, { "cell_type": "code", "execution_count": null, "id": "8462dd26", "metadata": {}, "outputs": [], "source": [ "# Random Forest\n", "randomForest = RandomForestRegressor(\n", " n_estimators=500, max_depth=7, max_features=3, min_samples_leaf=3)\n", "randomForest_class = RandomForestClassifier(\n", " n_estimators=500, max_depth=5, max_features=4, min_samples_leaf=7)\n", "\n", "np.random.seed(123)\n", "dml_plr_forest = dml.DoubleMLPLR(data_dml_base,\n", " ml_l = randomForest,\n", " ml_m = randomForest_class,\n", " n_folds = 3)\n", "dml_plr_forest.fit(store_predictions=True)\n", "forest_summary = dml_plr_forest.summary\n", "\n", "print(forest_summary)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "c2e8de45", "metadata": {}, "source": [ "Now, let's use a regression tree as provided in [scikit-learn](https://scikit-learn.org)'s [DecisionTreeRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html) and [DecisionTreeClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html)." ] }, { "cell_type": "code", "execution_count": null, "id": "20957649", "metadata": {}, "outputs": [], "source": [ "# Trees\n", "trees = DecisionTreeRegressor(\n", " max_depth=30, ccp_alpha=0.0047, min_samples_split=203, min_samples_leaf=67)\n", "trees_class = DecisionTreeClassifier(\n", " max_depth=30, ccp_alpha=0.0042, min_samples_split=104, min_samples_leaf=34)\n", "\n", "np.random.seed(123)\n", "dml_plr_tree = dml.DoubleMLPLR(data_dml_base,\n", " ml_l = trees,\n", " ml_m = trees_class,\n", " n_folds = 3)\n", "dml_plr_tree.fit(store_predictions=True)\n", "tree_summary = dml_plr_tree.summary\n", "\n", "print(tree_summary)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a187d938", "metadata": {}, "source": [ "We can also experiment with extreme gradient boosting as provided by [xgboost](https://xgboost.readthedocs.io/en/latest/)." ] }, { "cell_type": "code", "execution_count": null, "id": "988af9d6", "metadata": {}, "outputs": [], "source": [ "# Boosted Trees\n", "boost = XGBRegressor(n_jobs=1, objective = \"reg:squarederror\",\n", " eta=0.1, n_estimators=35)\n", "boost_class = XGBClassifier(use_label_encoder=False, n_jobs=1,\n", " objective = \"binary:logistic\", eval_metric = \"logloss\",\n", " eta=0.1, n_estimators=34)\n", "\n", "np.random.seed(123)\n", "dml_plr_boost = dml.DoubleMLPLR(data_dml_base,\n", " ml_l = boost,\n", " ml_m = boost_class,\n", " n_folds = 3)\n", "dml_plr_boost.fit(store_predictions=True)\n", "boost_summary = dml_plr_boost.summary\n", "\n", "print(boost_summary)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "b57d231e", "metadata": {}, "source": [ "Let's sum up the results:" ] }, { "cell_type": "code", "execution_count": null, "id": "0cc90651", "metadata": {}, "outputs": [], "source": [ "plr_summary = pd.concat((lasso_summary, forest_summary, tree_summary, boost_summary))\n", "plr_summary.index = ['lasso', 'forest', 'tree', 'xgboost']\n", "print(plr_summary[['coef', '2.5 %', '97.5 %']])" ] }, { "cell_type": "code", "execution_count": null, "id": "20528edc", "metadata": {}, "outputs": [], "source": [ "errors = np.full((2, plr_summary.shape[0]), np.nan)\n", "errors[0, :] = plr_summary['coef'] - plr_summary['2.5 %']\n", "errors[1, :] = plr_summary['97.5 %'] - plr_summary['coef']\n", "plt.errorbar(plr_summary.index, plr_summary.coef, fmt='o', yerr=errors)\n", "plt.ylim([0, 12500])\n", "\n", "plt.title('Partially Linear Regression Model (PLR)')\n", "plt.xlabel('ML method')\n", "_ = plt.ylabel('Coefficients and 95%-CI')" ] }, { "attachments": {}, "cell_type": "markdown", "id": "446bdae9", "metadata": {}, "source": [ "### Interactive Regression Model (IRM)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "aa53e2c6", "metadata": {}, "source": [ "Next, we consider estimation of average treatment effects when treatment effects are fully heterogeneous:" ] }, { "attachments": {}, "cell_type": "markdown", "id": "4ca39012", "metadata": {}, "source": [ "$$\n", "\\begin{aligned}\n", "& Y = g_0(D,X) + U, &\\quad E[U\\mid X,D] = 0,\\\\\n", "& D = m_0(X) + V, &\\quad E[V\\mid X] = 0.\n", "\\end{aligned}\n", "$$" ] }, { "attachments": {}, "cell_type": "markdown", "id": "e61aece3", "metadata": {}, "source": [ "To reduce the disproportionate impact of extreme propensity score weights in the interactive model\n", "we trim the propensity scores which are close to the bounds." ] }, { "cell_type": "code", "execution_count": null, "id": "14b79c21", "metadata": {}, "outputs": [], "source": [ "# Lasso\n", "lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=20000))\n", "\n", "# Initialize DoubleMLIRM model\n", "np.random.seed(123)\n", "dml_irm_lasso = dml.DoubleMLIRM(data_dml_flex,\n", " ml_g = lasso,\n", " ml_m = lasso_class,\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "dml_irm_lasso.fit(store_predictions=True) \n", "lasso_summary = dml_irm_lasso.summary\n", "\n", "print(lasso_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "6762686f", "metadata": {}, "outputs": [], "source": [ "# Random Forest\n", "randomForest = RandomForestRegressor(n_estimators=500)\n", "randomForest_class = RandomForestClassifier(n_estimators=500)\n", "\n", "np.random.seed(123)\n", "dml_irm_forest = dml.DoubleMLIRM(data_dml_base,\n", " ml_g = randomForest,\n", " ml_m = randomForest_class,\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_irm_forest.set_ml_nuisance_params('ml_g0', 'e401', {\n", " 'max_depth': 6, 'max_features': 4, 'min_samples_leaf': 7})\n", "dml_irm_forest.set_ml_nuisance_params('ml_g1', 'e401', {\n", " 'max_depth': 6, 'max_features': 3, 'min_samples_leaf': 5})\n", "dml_irm_forest.set_ml_nuisance_params('ml_m', 'e401', {\n", " 'max_depth': 6, 'max_features': 3, 'min_samples_leaf': 6})\n", "\n", "dml_irm_forest.fit(store_predictions=True) \n", "forest_summary = dml_irm_forest.summary\n", "\n", "print(forest_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "8589ee4d", "metadata": {}, "outputs": [], "source": [ "# Trees\n", "trees = DecisionTreeRegressor(max_depth=30)\n", "trees_class = DecisionTreeClassifier(max_depth=30)\n", "\n", "np.random.seed(123)\n", "dml_irm_tree = dml.DoubleMLIRM(data_dml_base,\n", " ml_g = trees,\n", " ml_m = trees_class,\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_irm_tree.set_ml_nuisance_params('ml_g0', 'e401', {\n", " 'ccp_alpha': 0.0016, 'min_samples_split': 74, 'min_samples_leaf': 24})\n", "dml_irm_tree.set_ml_nuisance_params('ml_g1', 'e401', {\n", " 'ccp_alpha': 0.0018, 'min_samples_split': 70, 'min_samples_leaf': 23})\n", "dml_irm_tree.set_ml_nuisance_params('ml_m', 'e401', {\n", " 'ccp_alpha': 0.0028, 'min_samples_split': 167, 'min_samples_leaf': 55})\n", "\n", "dml_irm_tree.fit(store_predictions=True)\n", "tree_summary = dml_irm_tree.summary\n", "\n", "print(tree_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "8ab9a005", "metadata": {}, "outputs": [], "source": [ "# Boosted Trees\n", "boost = XGBRegressor(n_jobs=1, objective = \"reg:squarederror\")\n", "boost_class = XGBClassifier(use_label_encoder=False, n_jobs=1,\n", " objective = \"binary:logistic\", eval_metric = \"logloss\")\n", "\n", "np.random.seed(123)\n", "dml_irm_boost = dml.DoubleMLIRM(data_dml_base,\n", " ml_g = boost,\n", " ml_m = boost_class,\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_irm_boost.set_ml_nuisance_params('ml_g0', 'e401', {\n", " 'eta': 0.1, 'n_estimators': 8})\n", "dml_irm_boost.set_ml_nuisance_params('ml_g1', 'e401', {\n", " 'eta': 0.1, 'n_estimators': 29})\n", "dml_irm_boost.set_ml_nuisance_params('ml_m', 'e401', {\n", " 'eta': 0.1, 'n_estimators': 23})\n", "\n", "dml_irm_boost.fit(store_predictions=True)\n", "boost_summary = dml_irm_boost.summary\n", "\n", "print(boost_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "83a3293b", "metadata": {}, "outputs": [], "source": [ "irm_summary = pd.concat((lasso_summary, forest_summary, tree_summary, boost_summary))\n", "irm_summary.index = ['lasso', 'forest', 'tree', 'xgboost']\n", "print(irm_summary[['coef', '2.5 %', '97.5 %']])" ] }, { "cell_type": "code", "execution_count": null, "id": "ddf460d6", "metadata": {}, "outputs": [], "source": [ "errors = np.full((2, irm_summary.shape[0]), np.nan)\n", "errors[0, :] = irm_summary['coef'] - irm_summary['2.5 %']\n", "errors[1, :] = irm_summary['97.5 %'] - irm_summary['coef']\n", "plt.errorbar(irm_summary.index, irm_summary.coef, fmt='o', yerr=errors)\n", "plt.ylim([0, 12500])\n", "\n", "plt.title('Interactive Regression Model (IRM)')\n", "plt.xlabel('ML method')\n", "_ = plt.ylabel('Coefficients and 95%-CI')" ] }, { "attachments": {}, "cell_type": "markdown", "id": "541d51d3", "metadata": {}, "source": [ "These estimates that flexibly account for confounding are\n", "substantially attenuated relative to the baseline estimate (*19559*) that does not account for confounding. They suggest much smaller causal effects of 401(k) eligiblity on financial asset holdings." ] }, { "attachments": {}, "cell_type": "markdown", "id": "a70f729b", "metadata": {}, "source": [ "## Local Average Treatment Effects of 401(k) Participation on Net Financial Assets" ] }, { "attachments": {}, "cell_type": "markdown", "id": "f5c32411", "metadata": {}, "source": [ "### Interactive IV Model (IIVM)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "9ad4bf98", "metadata": {}, "source": [ "In the examples above, we estimated the average treatment effect of *eligibility* on financial asset holdings. Now, we consider estimation of local average treatment effects (LATE) of *participation* using eligibility as an instrument for the participation decision. Under appropriate assumptions, the LATE identifies the treatment effect for so-called compliers, i.e., individuals who would only participate if eligible and otherwise not participate in the program. \n", "\n", "As before, $Y$ denotes the outcome `net_tfa`, and $X$ is the vector of covariates. We use `e401` as a binary instrument for the treatment variable `p401`. Here the structural equation model is:\n", "\n", "$$\n", "\\begin{aligned}\n", "& Y = g_0(Z,X) + U, &\\quad E[U\\mid Z,X] = 0,\\\\\n", "& D = r_0(Z,X) + V, &\\quad E[V\\mid Z, X] = 0,\\\\\n", "& Z = m_0(X) + \\zeta, &\\quad E[\\zeta \\mid X] = 0.\n", "\\end{aligned}\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "id": "85c3d0fe", "metadata": {}, "outputs": [], "source": [ "# Initialize DoubleMLData with an instrument\n", "\n", "# Basic model\n", "data_dml_base_iv = dml.DoubleMLData(data,\n", " y_col='net_tfa',\n", " d_cols='p401',\n", " z_cols='e401',\n", " x_cols=features_base)\n", "\n", "print(data_dml_base_iv)" ] }, { "cell_type": "code", "execution_count": null, "id": "9c6f8fc8", "metadata": {}, "outputs": [], "source": [ "# Flexible model\n", "model_data = pd.concat((data.copy()[['net_tfa', 'e401', 'p401']], features.copy()),\n", " axis=1, sort=False)\n", "\n", "data_dml_iv_flex = dml.DoubleMLData(model_data,\n", " y_col='net_tfa',\n", " d_cols='p401',\n", " z_cols='e401')\n", "\n", "print(data_dml_iv_flex)" ] }, { "cell_type": "code", "execution_count": null, "id": "c2e0942f", "metadata": {}, "outputs": [], "source": [ "# Lasso\n", "lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, max_iter=20000))\n", "\n", "# Initialize DoubleMLIRM model\n", "np.random.seed(123)\n", "dml_iivm_lasso = dml.DoubleMLIIVM(data_dml_iv_flex,\n", " ml_g = lasso,\n", " ml_m = lasso_class,\n", " ml_r = lasso_class,\n", " subgroups = {'always_takers': False,\n", " 'never_takers': True},\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "dml_iivm_lasso.fit(store_predictions=True)\n", "lasso_summary = dml_iivm_lasso.summary\n", "\n", "print(lasso_summary)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "19ddd6ad", "metadata": {}, "source": [ "Again, we repeat the procedure for the other machine learning methods:" ] }, { "cell_type": "code", "execution_count": null, "id": "438232b9", "metadata": {}, "outputs": [], "source": [ "# Random Forest\n", "randomForest = RandomForestRegressor(n_estimators=500)\n", "randomForest_class = RandomForestClassifier(n_estimators=500)\n", "\n", "np.random.seed(123)\n", "dml_iivm_forest = dml.DoubleMLIIVM(data_dml_base_iv,\n", " ml_g = randomForest,\n", " ml_m = randomForest_class,\n", " ml_r = randomForest_class,\n", " subgroups = {'always_takers': False,\n", " 'never_takers': True},\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_iivm_forest.set_ml_nuisance_params('ml_g0', 'p401', {\n", " 'max_depth': 6, 'max_features': 4, 'min_samples_leaf': 7})\n", "dml_iivm_forest.set_ml_nuisance_params('ml_g1', 'p401', {\n", " 'max_depth': 6, 'max_features': 3, 'min_samples_leaf': 5})\n", "dml_iivm_forest.set_ml_nuisance_params('ml_m', 'p401', {\n", " 'max_depth': 6, 'max_features': 3, 'min_samples_leaf': 6})\n", "dml_iivm_forest.set_ml_nuisance_params('ml_r1', 'p401', {\n", " 'max_depth': 4, 'max_features': 7, 'min_samples_leaf': 6})\n", "\n", "dml_iivm_forest.fit(store_predictions=True) \n", "forest_summary = dml_iivm_forest.summary\n", "\n", "print(forest_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "69630a44", "metadata": {}, "outputs": [], "source": [ "# Trees\n", "trees = DecisionTreeRegressor(max_depth=30)\n", "trees_class = DecisionTreeClassifier(max_depth=30)\n", "\n", "np.random.seed(123)\n", "dml_iivm_tree = dml.DoubleMLIIVM(data_dml_base_iv,\n", " ml_g = trees,\n", " ml_m = trees_class,\n", " ml_r = trees_class,\n", " subgroups = {'always_takers': False,\n", " 'never_takers': True},\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_iivm_tree.set_ml_nuisance_params('ml_g0', 'p401', {\n", " 'ccp_alpha': 0.0016, 'min_samples_split': 74, 'min_samples_leaf': 24})\n", "dml_iivm_tree.set_ml_nuisance_params('ml_g1', 'p401', {\n", " 'ccp_alpha': 0.0018, 'min_samples_split': 70, 'min_samples_leaf': 23})\n", "dml_iivm_tree.set_ml_nuisance_params('ml_m', 'p401', {\n", " 'ccp_alpha': 0.0028, 'min_samples_split': 167, 'min_samples_leaf': 55})\n", "dml_iivm_tree.set_ml_nuisance_params('ml_r1', 'p401', {\n", " 'ccp_alpha': 0.0576, 'min_samples_split': 55, 'min_samples_leaf': 18})\n", "\n", "dml_iivm_tree.fit(store_predictions=True)\n", "tree_summary = dml_iivm_tree.summary\n", "\n", "print(tree_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "239364cb", "metadata": {}, "outputs": [], "source": [ "# Boosted Trees\n", "boost = XGBRegressor(n_jobs=1, objective = \"reg:squarederror\")\n", "boost_class = XGBClassifier(use_label_encoder=False, n_jobs=1,\n", " objective = \"binary:logistic\", eval_metric = \"logloss\")\n", "\n", "np.random.seed(123)\n", "dml_iivm_boost = dml.DoubleMLIIVM(data_dml_base_iv,\n", " ml_g = boost,\n", " ml_m = boost_class,\n", " ml_r = boost_class,\n", " subgroups = {'always_takers': False,\n", " 'never_takers': True},\n", " trimming_threshold = 0.01,\n", " n_folds = 3)\n", "\n", "# Set nuisance-part specific parameters\n", "dml_iivm_boost.set_ml_nuisance_params('ml_g0', 'p401', {\n", " 'eta': 0.1, 'n_estimators': 9})\n", "dml_iivm_boost.set_ml_nuisance_params('ml_g1', 'p401', {\n", " 'eta': 0.1, 'n_estimators': 33})\n", "dml_iivm_boost.set_ml_nuisance_params('ml_m', 'p401', {\n", " 'eta': 0.1, 'n_estimators': 12})\n", "dml_iivm_boost.set_ml_nuisance_params('ml_r1', 'p401', {\n", " 'eta': 0.1, 'n_estimators': 25})\n", "\n", "dml_iivm_boost.fit(store_predictions=True)\n", "boost_summary = dml_iivm_boost.summary\n", "\n", "print(boost_summary)" ] }, { "cell_type": "code", "execution_count": null, "id": "9e20803b", "metadata": {}, "outputs": [], "source": [ "iivm_summary = pd.concat((lasso_summary, forest_summary, tree_summary, boost_summary))\n", "iivm_summary.index = ['lasso', 'forest', 'tree', 'xgboost']\n", "print(iivm_summary[['coef', '2.5 %', '97.5 %']])" ] }, { "cell_type": "code", "execution_count": null, "id": "259eb6eb", "metadata": {}, "outputs": [], "source": [ "colors = sns.color_palette()" ] }, { "cell_type": "code", "execution_count": null, "id": "87a4af31", "metadata": {}, "outputs": [], "source": [ "errors = np.full((2, iivm_summary.shape[0]), np.nan)\n", "errors[0, :] = iivm_summary['coef'] - iivm_summary['2.5 %']\n", "errors[1, :] = iivm_summary['97.5 %'] - iivm_summary['coef']\n", "plt.errorbar(iivm_summary.index, iivm_summary.coef, fmt='o', yerr=errors)\n", "plt.ylim([0, 16500])\n", "\n", "plt.title('Interactive IV Model (IIVM)')\n", "plt.xlabel('ML method')\n", "_ = plt.ylabel('Coefficients and 95%-CI')" ] }, { "attachments": {}, "cell_type": "markdown", "id": "f80f1c8c", "metadata": {}, "source": [ "## Summary of Results" ] }, { "attachments": {}, "cell_type": "markdown", "id": "1e427295", "metadata": {}, "source": [ "To sum up, let's merge all our results so far and illustrate them in a plot. " ] }, { "cell_type": "code", "execution_count": null, "id": "75c1862b", "metadata": {}, "outputs": [], "source": [ "df_summary = pd.concat((plr_summary, irm_summary, iivm_summary)).reset_index().rename(columns={'index': 'ML'})\n", "df_summary['Model'] = np.concatenate((np.repeat('PLR', 4), np.repeat('IRM', 4), np.repeat('IIVM', 4)))\n", "print(df_summary.set_index(['Model', 'ML']))" ] }, { "cell_type": "code", "execution_count": null, "id": "dfb07885", "metadata": { "tags": [ "nbsphinx-thumbnail" ] }, "outputs": [], "source": [ "plt.figure(figsize=(10, 15))\n", "colors = sns.color_palette()\n", "for ind, model in enumerate(['PLR', 'IRM', 'IIVM']):\n", " plt.subplot(3, 1, ind+1)\n", " this_df = df_summary.query('Model == @model')\n", " errors = np.full((2, this_df.shape[0]), np.nan)\n", " errors[0, :] = this_df['coef'] - this_df['2.5 %']\n", " errors[1, :] = this_df['97.5 %'] - this_df['coef']\n", " plt.errorbar(this_df.ML, this_df.coef, fmt='o', yerr=errors,\n", " color=colors[ind], ecolor=colors[ind])\n", " plt.ylim([0, 16500])\n", " plt.title(model)\n", " plt.ylabel('Coefficients and 95%-CI')\n", "\n", "_ = plt.xlabel('ML method')" ] }, { "attachments": {}, "cell_type": "markdown", "id": "4974df69", "metadata": {}, "source": [ "We report results based on four ML methods for estimating the nuisance functions used in\n", "forming the orthogonal estimating equations. We find again that the estimates of the treatment effect are stable across ML methods. The estimates are highly significant, hence we would reject the hypothesis\n", "that 401(k) participation has no effect on financial wealth." ] }, { "attachments": {}, "cell_type": "markdown", "id": "72e515ad", "metadata": {}, "source": [ "______\n", "\n", "**Acknowledgement**\n", "\n", "We would like to thank [Jannis Kueck](https://www.dice.hhu.de/en/dice/people/professors-1/kueck) for sharing [the kaggle notebook](https://www.kaggle.com/janniskueck/pm5-401k). The pension data set has been analyzed in several studies, among others [Chernozhukov et al. (2018)](https://arxiv.org/abs/1608.00060).\n", "\n" ] } ], "metadata": { "kernelspec": { "display_name": "dml_base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.2" }, "vscode": { "interpreter": { "hash": "04413e1efd13b5e2aaedccc5facec5686292d28983ef24fa021a12c73bd6369e" } } }, "nbformat": 4, "nbformat_minor": 5 }