Skip to content

ENH: causal impact, synthetic control - #3647

Open
josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:causal_panel
Open

josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:causal_panel

Conversation

@josef-pkt

@josef-pkt josef-pkt commented May 7, 2017 •

Copy link
Copy Markdown
Member

see #3631 for background on the type of treatment effect estimator
also includes predictive models with inequality constraints on parameters, see #3632, #1211 for nnls

currently:

  • one treated, many controls
  • only outcome variables, no covariates for matching or prediction
  • OLS based, serial dependence not modeled, see tsa based notebook and Google's causalimpact
  • constraints and regularization, options
    • OLS, no constraints, no regularization
    • elastic net
    • nonnegativity constraints using nnls
    • simplex constraint, i.e. nonnegative and sum to one, using slsqp
    • with or without adding constant to the predictor
  • no explicit tuning parameter selection, e.g. variable selection or choosing penalization weights, Needs an extra step for specification search for prediction, e.g. information criteria or cross-validation
  • no inference, nor standard errors are included here. Analytic/Asymptotic formulas for HCW style are in draft stage. Otherwise, it needs wrapper for placebo permutation tests

background

  • this started out as simplified synthetic control (Abadie et al), but removing covariates
  • HCW use just outcome regression with variable/control selection, Follow-up articles use e.g. LASSO and weaken assumptions for consistent estimation of ATT
  • Doudchenko, Imbens emphasize the role of constraints, and this is currently close to their approach

Also, statsmodels.treatment doesn't exist in master yet.

I haven't thought much about names for module and classes.

no nice wrapper things, this is currently pure numpy array based, no missing value handling, ...
Formulas might not be needed here because we only have one type of variables in the basic version, and we don't want to specify a list of names if we have a large number of controls.

@josef-pkt

josef-pkt commented May 7, 2017 •

Copy link
Copy Markdown
Member Author

edited with a bit more explanation

results in a made up example used in the current unit test

The treatment effect is in this example downward trending, i.e. a break in the linear trend plus a shift. ATT is the average of the trend over the treatment periods. see plot in next comment

The array of integers in the following are the indices of the controls that have nonzero coefficient, out of 10 controls

ATT true -5.75

with OLS
ATT -5.69648033022

with elastic net penalization
(array([1, 2, 5], dtype=int64),)
ATT -6.08555924953

with nonnegativity constraints
<class 'causal_tsa_class.OLSNonNegative'>
(array([2, 5, 8], dtype=int64),)
ATT -6.08028091863

with simplex constraints
<class 'causal_tsa_class.OLSSimplexConstrained'>
(array([0, 2, 4, 5], dtype=int64),)
ATT -5.96540036549

@josef-pkt

Copy link
Copy Markdown
Member Author

and one of the generated plot fig = res4.plot(loc_legend="upper left")

causal_tsa_ex

@josef-pkt

josef-pkt commented May 7, 2017 •

Copy link
Copy Markdown
Member Author

not python 2 compatible (print ain't no function there, so we cannot just override it.)
prints have to be removed instead of "mocking" them.

green in py3, read in py2

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.0005%) to 90.307% when pulling 7f5bf48 on josef-pkt:causal_panel into fd85308 on statsmodels:master.

@coveralls

coveralls commented May 7, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.001%) to 90.308% when pulling 932edc5 on josef-pkt:causal_panel into fd85308 on statsmodels:master.

@coveralls

coveralls commented May 8, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.001%) to 90.308% when pulling a150883 on josef-pkt:causal_panel into fd85308 on statsmodels:master.

"""fit the prediction model

constraints and regularization are currently mutually exclusive, only
one of the too can be different from None.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too--> two

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased, no merge conflicts
(temporary local mess during aborted rebase, broken git index, needed hard reset, which was not enough, and checkout --force master to get rid of untracked files that are already in master )


I'm adding `add_const` option separately from the constraints because
it can be used with OLS and with regularized.
(just implmentation leak?)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spelling. also can you expand on the implementation leak thought?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No idea right now, i.e. I don't remember.
The general point is that we need an option to handle constant separately or to exclude constant shift if we don't want to extrapolate (as imposed in the original articles, but dropped in other versions)

constraints=cons)
params = minout.x

return Results(self, params, method='OLSSimplexConstrained')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not a Wrapper?

def __init__(self, endog, exog, index_unconstrained=None):
super(OLSSimplexConstrained, self).__init__(endog, exog)


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whitespace

"""


def __init__(self, endog, exog, index_unconstrained=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is the index_unconstrained arg just ignored?

assert_allclose(res2.prediction_error * sf, diff_true * sf, atol=atol, rtol=0.1)
assert_allclose(res3.prediction_error * sf, diff_true * sf, atol=atol, rtol=0.1)
assert_allclose(res4.prediction_error * sf, diff_true * sf, atol=atol, rtol=0.1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's get this right the first time instead of having to come back and turn it into an organized test: setup_class, test_foo... and consider the pytest.mark.smoke idea where pertinent (e.g. plotting)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this test needs a complete rewrite, plus we need more unit tests.
first comment in this function: # this just dumps the example into a test

Comment thread statsmodels/treatment/__init__.py Outdated
@@ -0,0 +1,2 @@
from statsmodels import NoseWrapper as Tester
test = Tester().test

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs to switch to pytest

@josef-pkt

Copy link
Copy Markdown
Member Author

unit tests fail everywhere because of nose

ImportError while importing test module '/home/travis/build/statsmodels/statsmodels/statsmodels/treatment/tests/test_causal_tsa.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
statsmodels/treatment/__init__.py:1: in <module>
    from statsmodels import NoseWrapper as Tester
E   ImportError: cannot import name 'NoseWrapper'

@coveralls

coveralls commented Nov 1, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.02%) to 81.905% when pulling 07cbcef on josef-pkt:causal_panel into 5b8f20d on statsmodels:master.

@codecov-io

Copy link
Copy Markdown

Codecov Report

Merging #3647 into master will increase coverage by 0.01%.
The diff coverage is 86.88%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3647      +/-   ##
==========================================
+ Coverage   79.32%   79.34%   +0.01%     
==========================================
  Files         544      547       +3     
  Lines       81718    81901     +183     
  Branches     9255     9269      +14     
==========================================
+ Hits        64822    64981     +159     
- Misses      14802    14819      +17     
- Partials     2094     2101       +7
Impacted Files Coverage Δ
statsmodels/treatment/__init__.py 100% <100%> (ø)
statsmodels/treatment/panel_effect.py 82.35% <82.35%> (ø)
statsmodels/treatment/tests/test_causal_tsa.py 95.16% <95.16%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5b8f20d...07cbcef. Read the comment docs.

@hetspookjee

Copy link
Copy Markdown

I'm wondering, why hasn't this PR been accepted? Could really appreciate this and it's a perfect fit for statsmodels imo.

@josef-pkt

Copy link
Copy Markdown
Member Author

@tsktsktsk123
The main reason is insufficient unit tests.
The results looked good in the examples that I tried, but the results are not verified against other packages (if available ?) or the articles that this was mostly based on.

The API will most likely need another review to check whether it's usable.

(I don't remember how good the inferential statistic are that are already implemented.)

from statsmodels.nonparametric.smoothers_lowess import lowess


class OLSNonNegative(Model):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

privatize with leading underscore

@josef-pkt

Copy link
Copy Markdown
Member Author

PanelATTResults is missing a summary(), summary_frame method

The summary_frame could have predicted values ATE for each period and cumulative
ATT, ATT.cumsum, observed, POM/predicted

I don't remember if there is a summary statistic for the "bootstrap" (treat each time series as candidate), or it's just the plot.

we don't have synthetic control or causal impact in the names
need docs for discoverability and search

should be feasible for 0.14
if we don't find another package, then unit tests will just test against dgp and theoretical properties.

@josef-pkt josef-pkt mentioned this pull request Feb 17, 2022
16 of 20 tasks
@josef-pkt

Copy link
Copy Markdown
Member Author

causality handbook in python has good examples and explanations
https://github.com/matheusfacure/python-causality-handbook/blob/master/causal-inference-for-the-brave-and-true/15-Synthetic-Control.ipynb
is close to what we have

For ipw, double robust we have more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants