Repository navigation
WIP: Add Panel Data models #1133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
9151ec6
ed7bcbb
1d1ee98
8d849aa
db4ac52
c68b284
4f1c373
92d7f6c
e387f58
5a50578
911af85
fb3df80
820ce7e
d1cbe52
71c6663
1978583
5d2f2e2
57fbfce
f5c9e41
f49ab30
fd3b2d6
b04787b
55ee7a9
ca3e797
2b77f5e
6fb5b46
581a8ef
849ed0c
0e3d23c
c29781b
59b7bc6
433398f
211a90d
ab1aa17
d77d6d8
ad12251
fd9b416
973cc0e
fa7871e
f9b11dc
679c649
bb5a030
2f7cd08
7e61b88
d62e68d
514a9f8
b1d5420
f8bee3e
50e04e7
227c999
02d86ad
598b743
38729d1
8a953ba
4e27073
1e2be1d
6865264
1256933
5c7f9ac
8a5003a
2523cce
7b3f390
1a40705
5c0ac18
c40c5c2
f23199f
a248265
0e2db04
1ae189e
9099344
757d7ff
10221f3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| import numpy as np | ||
| from scipy import special | ||
|
|
||
| from statsmodels.base.model import GenericLikelihoodModel | ||
| from statsmodels.panel.panel_model import PanelModel, _effects_levels | ||
| from statsmodels.discrete.discrete_model import Poisson | ||
|
|
||
| class PanelPoisson(PanelModel, GenericLikelihoodModel):#, Poisson): | ||
| #NOTE: if we want to inherit also from Poisson, we need to add | ||
| # *args, **kwargs to discrete model inits | ||
| """ | ||
| References | ||
| ---------- | ||
| Cameron, C. and Trivedi, P. K. 1998. *Regression Analysis of Count Data* | ||
| 1st Edition. | ||
| """ | ||
| # one-way fixed effects only for now using conditional MLE of | ||
| # Hausman et al (1984) | ||
| # panel poisson avoids the incidental parameters problem by conditioning | ||
| # on sufficient statistics for the fixed effects, namely | ||
| # sum(s, y_is) for panel fixed effects and sum(j, y_jt) for time | ||
| # fixed effects. If you want to do two-way just include dummies for | ||
| # the fixed dimension (usually time in econometrics as T = Fixed and | ||
| # N -> inf | ||
| def __init__(self, y, X, effects="oneway", panel=None, time=None, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. endog, exog |
||
| hasconst=None, missing='none'): | ||
| self.effects = effects | ||
| self._effects_level = _effects_levels[effects] | ||
| super(PanelPoisson, self).__init__(y, X, missing=missing, | ||
| time=time, panel=panel, | ||
| hasconst=hasconst) | ||
|
|
||
| def loglike(self, params, concentrated=True): | ||
| y = self.endog | ||
| offset = getattr(self, "offset", 0) | ||
| exposure = getattr(self, "exposure", 0) | ||
| # lambda in the literature | ||
| XB = np.dot(self.exog, params) + offset + exposure | ||
| mu = np.exp(XB) | ||
|
|
||
| g = self.data.groupings | ||
| level = self._effects_level[0] | ||
|
|
||
| p_it = g.transform_array(mu, lambda x : x / x.sum(), level=level) | ||
| llf = sum(y * np.log(p_it)) | ||
| if not concentrated: | ||
| llf += sum(special.gammaln(g.transform_array(y, | ||
| lambda x : x.sum(), level=level) + 1)) | ||
| llf -= sum(g.transform_array(special.gammaln(y + 1), | ||
| lambda x : x.sum(), level=level)) | ||
| return llf | ||
|
|
||
| def score(self, params): | ||
| pass | ||
|
|
||
| def hessian(self, params): | ||
| pass | ||
|
|
||
|
|
||
| class PanelZIPoisson(object): | ||
| def __init__(self, y, X, inflateX=None, missing='none'): | ||
| pass | ||
|
|
||
| def wide_to_long(df, stubnames, i, j): | ||
| """ | ||
| User-friendly wide panel to long format. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| df : DataFrame | ||
| The wide-format DataFrame | ||
| stubnames : list | ||
| A list of stub names. The wide format variables are assumed to | ||
| start with the stub names. | ||
| i : str | ||
| The name of the id variable. | ||
| j : str | ||
| The name of the subobservation variable. | ||
|
|
||
| Returns | ||
| ------- | ||
| DataFrame | ||
| A DataFrame that contains each stub name as a variable as well as | ||
| variables for i and j. | ||
|
|
||
| Examples | ||
| -------- | ||
| import pandas as pd | ||
| import numpy as np | ||
| np.random.seed(123) | ||
| df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, | ||
| "A1980" : {0 : "d", 1 : "e", 2 : "f"}, | ||
| "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, | ||
| "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, | ||
| "X" : dict(zip(range(3), np.random.randn(3))) | ||
| }) | ||
| df["id"] = df.index | ||
| wide_to_long(df, ["A", "B"], i="id", j="year") | ||
|
|
||
| Notes | ||
| ----- | ||
| All extra variables are treated as extra id variables. | ||
| """ | ||
| def get_var_names(df, regex): | ||
| return df.filter(regex=regex).columns.tolist() | ||
|
|
||
| def melt_stub(df, stub, i, j): | ||
| varnames = get_var_names(df, "^"+stub) | ||
| newdf = pd.melt(df, id_vars=i, value_vars=varnames, | ||
| value_name=stub, var_name=j) | ||
| newdf[j] = newdf[j].str.replace(stub, "").astype(int) | ||
| return newdf | ||
|
|
||
| id_vars = get_var_names(df, "^(?!%s)" % "|".join(stubnames)) | ||
| if i not in id_vars: | ||
| id_vars += [i] | ||
|
|
||
| stub = stubnames.pop(0) | ||
| newdf = melt_stub(df, stub, id_vars, j) | ||
|
|
||
| for stub in stubnames: | ||
| new = melt_stub(df, stub, id_vars, j) | ||
| newdf = newdf.merge(new, how="outer", on=id_vars + [j], copy=False) | ||
| return newdf.set_index([i, j]) | ||
|
|
||
|
|
||
| #NOTE: can remove this | ||
| def read_fwf_file(url, names, sep): | ||
| import pandas as pd | ||
| from urllib2 import urlopen | ||
| import re | ||
| lines = urlopen(url).readlines() | ||
|
|
||
| result = [] | ||
| row = [] | ||
| def pop_line(lines, sep): | ||
| line = lines.pop(0) | ||
| line = line.strip() | ||
| line = re.split(sep, line) | ||
| return line | ||
|
|
||
| while lines: | ||
| line = pop_line(lines, sep) | ||
| for i in range(len(names)): | ||
| if line: | ||
| row.append(line.pop(0)) | ||
| else: | ||
| if lines: | ||
| line = pop_line(lines, sep) | ||
| row.append(line.pop(0)) | ||
| result.append(row) | ||
| row = [] | ||
| return pd.DataFrame(result, columns=names) | ||
|
|
||
| if __name__ == "__main__": | ||
| import pandas as pd | ||
| #url = "http://cameron.econ.ucdavis.edu/mmabook/patr7079.asc" | ||
| #names = ["CUSIP", "ARDSSIC", "SCISECT", "LOGK", "SUMPAT", "LOGR70", | ||
| # "LOGR71", "LOGR72", "LOGR73", "LOGR74", "LOGR75", "LOGR76", | ||
| # "LOGR77", "LOGR78", "LOGR79", "PAT70", "PAT71", "PAT72", "PAT73", | ||
| # "PAT74", "PAT75", "PAT76", "PAT77", "PAT78", "PAT79"] | ||
| #dta = read_fwf_file(url, names, sep=" *") | ||
|
|
||
| url = "https://gist.github.com/jseabold/6652233/raw/44a04a78be85f5b3af16f26f51a143e047a10972/patr7079.csv" | ||
| dta = pd.read_csv(url) | ||
| dta["id"] = dta.index | ||
|
|
||
| dta = wide_to_long(dta, ["LOGR", "PAT"], "id", "year") | ||
| dta.reset_index(inplace=True) | ||
| dta = dta.ix[dta["year"] >= 75] | ||
| dta.set_index(["id", "year"], inplace=True) | ||
|
|
||
| y = dta["PAT"] | ||
| dta["const"] = 1 | ||
| X = dta[["LOGR"]] | ||
| mod = PanelPoisson(y, X) | ||
|
|
||
|
|
||
| params = [-.0377642474582] | ||
| res = mod.fit(disp=0) | ||
| np.testing.assert_almost_equal(res.params, params, 4) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import numpy as np | ||
|
|
||
| from statsmodels.base.data import ModelData, PatsyData, PandasData | ||
| from statsmodels.tools.grouputils import Grouping | ||
| import statsmodels.tools.data as data_util | ||
|
|
||
| #TODO: just move this all to base/data.py? | ||
|
|
||
| def _is_balanced(data, dropna=False): | ||
| """ | ||
| Checks if len(time) x len(panel) == len(data) | ||
| """ | ||
| if dropna: | ||
| dropped = data.dropna() | ||
| return np.multiply.reduce(dropped.index.levshape) == len(dropped) | ||
| else: | ||
| return np.multiply.reduce(data.index.levshape) == len(data) | ||
|
|
||
| def _is_balanced_index(index): | ||
| return np.multiply.reduce(index.levshape) == len(index) | ||
|
|
||
| def _check_panel_time(kwargs): | ||
| """ | ||
| Checks that panel and time are in the dict kwargs, pops them off, and | ||
| returns them. This will modify kwargs in place. | ||
| """ | ||
| panel = kwargs.pop('panel', None) | ||
| if panel is None: | ||
| raise ValueError("panel cannot be None") | ||
| time = kwargs.pop('time', None) | ||
| if time is None: | ||
| raise ValueError('time cannot be None') | ||
|
|
||
| return panel, time | ||
|
|
||
|
|
||
| class _CommonPanelMethods(object): | ||
| def _initialize(self): | ||
| self.exog, idx = self.groupings.sort(self.exog) | ||
| self.endog, idx = self.groupings.sort(self.endog) | ||
| self.groupings.reindex(idx) # sorting may have altered index | ||
| self.is_balanced = _is_balanced_index(idx) | ||
| self.n_panel, self.n_time = self.groupings.index.levshape | ||
|
|
||
|
|
||
| class PanelData(ModelData, _CommonPanelMethods): | ||
| def __init__(self, endog, exog, missing='none', hasconst=None, **kwargs): | ||
| panel, time = _check_panel_time(kwargs) | ||
| self.groupings = Grouping(index=zip(panel, time)) | ||
| super(PanelData, self).__init__(endog, exog, missing, hasconst, | ||
| **kwargs) | ||
| self._initialize() | ||
|
|
||
|
|
||
| class PatsyPanelData(PatsyData, _CommonPanelMethods): | ||
| def __init__(self, endog, exog, missing='none', hasconst=None, **kwargs): | ||
| panel, time = _check_panel_time(kwargs) | ||
| self.groupings = Grouping(index=zip(panel, time)) | ||
| super(PanelData, self).__init__(endog, exog, missing, hasconst, | ||
| **kwargs) | ||
| self._initialize() | ||
|
|
||
|
|
||
| class PandasPanelData(PandasData, _CommonPanelMethods): | ||
| def __init__(self, endog, exog, missing='none', hasconst=None, **kwargs): | ||
| if not endog.index.equals(exog.index): | ||
| raise ValueError("endog and exog index do not equal each other") | ||
| #TODO: could probably relax this and just take the MultiIndex one | ||
|
|
||
| from pandas import MultiIndex | ||
| if not isinstance(endog.index, MultiIndex): | ||
| raise ValueError("index is not a MultiIndex") | ||
|
|
||
| self.groupings = Grouping(index=endog.index) | ||
|
|
||
| super(PandasPanelData, self).__init__(endog, exog, missing, hasconst, | ||
| **kwargs) | ||
| self._initialize() | ||
|
|
||
|
|
||
| def handle_panel_data(endog, exog, missing='none', hasconst=None, **kwargs): | ||
| if isinstance(endog, (list, tuple)): | ||
| endog = np.asarray(endog) | ||
| if isinstance(exog, (list, tuple)): | ||
| exog = np.asarray(exog) | ||
|
|
||
| if data_util._is_using_ndarray_type(endog, exog): | ||
| klass = PanelData | ||
| elif data_util._is_using_pandas(endog, exog): | ||
| klass = PandasPanelData | ||
| elif data_util._is_using_patsy(endog, exog): | ||
| klass = PatsyPanelData | ||
| # keep this check last | ||
| elif data_util._is_using_ndarray(endog, exog): | ||
| klass = PanelData | ||
| else: | ||
| raise ValueError('unrecognized data structures: %s / %s' % | ||
| (type(endog), type(exog))) | ||
|
|
||
| return klass(endog, exog=exog, missing=missing, hasconst=hasconst, **kwargs) | ||
|
|
||
| ### Tests | ||
|
|
||
| def test_is_balanced(): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. still needs to move to test file |
||
| from statsmodels.datasets import grunfeld | ||
| balanced_panel = grunfeld.load_pandas().data | ||
|
|
||
| drop_idx = ((balanced_panel.firm == 'General Motors') & | ||
| balanced_panel.year.isin([1935, 1938])) | ||
| drop_idx = drop_idx | ((balanced_panel.firm == 'Westinghouse') & | ||
| balanced_panel.year.isin([1936, 1941])) | ||
| unbalanced_panel = balanced_panel.ix[~drop_idx] | ||
|
|
||
| balanced_panel.set_index(['firm', 'year'], inplace=True) | ||
| unbalanced_panel.set_index(['firm', 'year'], inplace=True) | ||
|
|
||
| np.testing.assert_(_is_balanced(balanced_panel)) | ||
| np.testing.assert_(not _is_balanced(unbalanced_panel)) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from statsmodels.base.model import LikelihoodModel | ||
| from statsmodels.panel.base.data import handle_panel_data | ||
|
|
||
| _effects_levels = dict(oneway=[0], | ||
| time=[1], | ||
| twoway=[0,1]) | ||
| #TODO: support any other aliases? | ||
|
|
||
| class PanelModel(LikelihoodModel): | ||
| def __init__(self, y, X, time=None, panel=None, missing='none', | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. endog exog I don't know if we shouldn't find a common name across models for |
||
| hasconst=None): | ||
| #TODO: make time-series stuff more modular so we can check time | ||
| # if need be - | ||
| # check_dates(time) | ||
| super(PanelModel, self).__init__(y, X, missing=missing, | ||
| time=time, panel=panel, | ||
| hasconst=hasconst) | ||
|
|
||
| def _handle_data(self, y, X, missing, hasconst, **kwargs): | ||
| return handle_panel_data(y, X, missing, hasconst, **kwargs) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIRC, name should indicate
conditional(given the total number per cluster unit)