Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
72 commits
Select commit Hold shift + click to select a range
9151ec6
ENH: New Linear Panel Model
Feb 24, 2014
ed7bcbb
smarter input processing sorting
Mar 2, 2013
1d1ee98
added between time model
Mar 2, 2013
8d849aa
ENH: Use reindex in Panel model
Feb 24, 2014
db4ac52
removed fd
Mar 10, 2013
c68b284
moved panel to regression folder
Mar 10, 2013
4f1c373
add panel tests
Mar 10, 2013
92d7f6c
test lower case sorting in plm
Mar 10, 2013
e387f58
minor testing
Jun 26, 2013
5a50578
ENH: Add panel data model data handling.
jseabold Jul 10, 2013
911af85
ENH: Add abstract PanelModel class.
jseabold Jul 10, 2013
fb3df80
ENH: Allow type check tools to work with one arg
jseabold Jul 10, 2013
820ce7e
ENH: Update PanelLM to use PanelModel and data attribute.
jseabold Jul 10, 2013
d1cbe52
TST: Use keywords in tests.
jseabold Jul 10, 2013
71c6663
REF: Check method and effects compat earlier.
jseabold Jul 10, 2013
1978583
STY: twoways -> twoway.
jseabold Jul 10, 2013
5d2f2e2
STY: Respect DRY a bit.
jseabold Jul 10, 2013
57fbfce
STY: Line length
jseabold Jul 10, 2013
f5c9e41
STY: Comment cleanup
jseabold Jul 10, 2013
f49ab30
STY: Revert call signature to what it was.
jseabold Jul 10, 2013
fd3b2d6
ENH: Do some more arg checking.
jseabold Jul 10, 2013
b04787b
TST: Just import what we need.
jseabold Jul 10, 2013
55ee7a9
BUG: Use matrix rank not numpy rank.
jseabold Jul 10, 2013
ca3e797
BUG: Fix logic mistake in data checkers.
jseabold Jul 10, 2013
2b77f5e
TST: Add df_resid test and two test stubs.
jseabold Jul 11, 2013
6fb5b46
STY: Use namespace for testing.
jseabold Jul 11, 2013
581a8ef
TST: Add sum of squares tests.
jseabold Jul 11, 2013
849ed0c
ENH: Fix degrees of freedom, bse, fvalue, and scale.
jseabold Jul 11, 2013
0e3d23c
BUG: Make sure hasconst is passed up to classes.
jseabold Jul 11, 2013
c29781b
STY: Remove commented out code.
jseabold Jul 11, 2013
59b7bc6
ENH: Copy conf_int so we can control dist. Needs refactor.
jseabold Jul 11, 2013
433398f
TST: Test confidence intervals
jseabold Jul 11, 2013
211a90d
TST: Fix path and add options setting.
jseabold Jul 11, 2013
ab1aa17
ENH: Add separate results for Within model.
jseabold Jul 12, 2013
d77d6d8
TST: Test added within results.
jseabold Jul 12, 2013
ad12251
ENH: Add between results class.
jseabold Jul 12, 2013
fd9b416
TST: Test between results.
jseabold Jul 12, 2013
973cc0e
ENH: Add resid alias to within.
jseabold Jul 13, 2013
fa7871e
TST: Test resid_overall
jseabold Jul 13, 2013
f9b11dc
ENH: Add loglikelihoods. Add random results. Fix dof.
jseabold Aug 7, 2013
679c649
TST: Test llf, random, and degrees of freedom.
jseabold Aug 7, 2013
bb5a030
ENH: Generalize for panel and time fixed effects.
jseabold Sep 17, 2013
2f7cd08
TST: Add Stata test script.
jseabold Sep 17, 2013
7e61b88
STY: Add comment on encodings.
jseabold Sep 17, 2013
d62e68d
TST: Add stata example for twoway effects.
jseabold Sep 17, 2013
514a9f8
TST: Remove redundant test. Add Twoway stub.
jseabold Sep 17, 2013
b1d5420
TST: Fix bug in stata script.
jseabold Sep 19, 2013
f8bee3e
REF: Move general code to panel base.
jseabold Sep 21, 2013
50e04e7
ENH: Add bare bones PanelPoisson
jseabold Sep 21, 2013
227c999
DOC: Add references and some comments.
jseabold Oct 9, 2013
02d86ad
REF: Remove _effects_levels and import it.
jseabold Oct 9, 2013
598b743
TST: Comment out tests.
jseabold Oct 9, 2013
38729d1
STY: Rename panel -> linear_panel
jseabold Oct 18, 2013
8a953ba
TST: Test rsquared in random.
jseabold Oct 18, 2013
4e27073
BUG: Make sure to return.
jseabold Oct 18, 2013
1e2be1d
TST/BUG: Fix and tests standard deviations
jseabold Oct 18, 2013
6865264
TST: Test/fix rho.
jseabold Oct 18, 2013
1256933
ENH: Add Hausman test.
jseabold Oct 18, 2013
5c7f9ac
EX: Make example runnable without internet.
jseabold Oct 18, 2013
8a5003a
ENH: Estimate constant in within model to be consistent.
jseabold Oct 21, 2013
2523cce
TST: Add some stata tricks
jseabold Oct 21, 2013
7b3f390
BUG: Change and back to or.
jseabold Oct 21, 2013
1a40705
DOC: Clean up Hausman doc.
jseabold Oct 22, 2013
5c0ac18
TST: Smoke test summary method.
jseabold Oct 22, 2013
c40c5c2
ENH: Make sure summary doesn't raise. TODO: Add summaries.
jseabold Oct 22, 2013
f23199f
ENH: Improve Hausman test usage.
jseabold Oct 22, 2013
a248265
TST: Test hausman_test.
jseabold Oct 22, 2013
0e2db04
ENH: Add nottest decorator.
jseabold Oct 22, 2013
1ae189e
ENH: Mark hausman_test function as not a test.
jseabold Oct 22, 2013
9099344
REF: Fix refactor victim
jseabold Feb 24, 2014
757d7ff
REF: Always nobs length 2d out of transform_slices.
jseabold Feb 24, 2014
10221f3
REF: Preserve 1d in 1d out.
jseabold Feb 24, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions statsmodels/discrete/discrete_panel.py
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):

Copy link
Copy Markdown
Member

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)

#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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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)
Empty file added statsmodels/panel/__init__.py
Empty file.
Empty file.
118 changes: 118 additions & 0 deletions statsmodels/panel/base/data.py
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():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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))
20 changes: 20 additions & 0 deletions statsmodels/panel/panel_model.py
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',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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 panel cluster group

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)
Loading