This very simple case-study is designed to get you up-and-running quickly with statsmodels. Starting from raw data, we will show the steps needed to estimate a statistical model and to draw a diagnostic plot. We will only use functions provided by statsmodels or its pandas and patsy dependencies.
After installing statsmodels and its dependencies, we load a few modules and functions:
In [1]: import statsmodels.api as sm
In [1]: import pandas
In [1]: from patsy import dmatrices
pandas builds on numpy arrays to provide rich data structures and data analysis tools. The pandas.DataFrame function provides labelled arrays of (potentially heterogenous) data, similar to the R “data.frame”. The pandas.read_csv function can be used to convert a comma-separated values file to a DataFrame object.
patsy is a Python library for describing statistical models and building Design Matrices using R-like formulas.
We download the Guerry dataset, a collection of historical data used in support of Andre-Michel Guerry’s 1833 Essay on the Moral Statistics of France. The data set is hosted online in comma-separated values format (CSV) by the Rdatasets repository. We could download the file locally and then load it using read_csv, but pandas takes care of all of this automatically for us:
In [1]: url = "http://vincentarelbundock.github.com/Rdatasets/csv/HistData/Guerry.csv"
#the next two lines are not necessary with a recent version of pandas
In [1]: from urllib2 import urlopen
In [1]: url = urlopen(url)
In [1]: df = pandas.read_csv(url)
The Input/Output doc page shows how to import from various other formats.
We select the variables of interest and look at the bottom 5 rows:
In [1]: vars = ['Department', 'Lottery', 'Literacy', 'Wealth', 'Region']
In [1]: df = df[vars]
In [1]: df[-5:]
Notice that there is one missing observation in the Region column. We eliminate it using a DataFrame method provided by pandas:
In [1]: df = df.dropna()
In [1]: df[-5:]
We want to know whether literacy rates in the 86 French departments are associated with per capita wagers on the Royal Lottery in the 1820s. We need to control for the level of wealth in each department, and we also want to include a series of dummy variables on the right-hand side of our regression equation to control for unobserved heterogeneity due to regional effects. The model is estimated using ordinary least squares regression (OLS).
To fit most of the models covered by statsmodels, you will need to create two design matrices. The first is a matrix of endogenous variable(s) (i.e. dependent, response, regressand, etc.). The second is a matrix of exogenous variable(s) (i.e. independent, predictor, regressor, etc.). The OLS coefficient estimates are calculated as usual:
\hat{\beta} = (X'X)^{-1} X'y
where y is an N \times 1 column of data on lottery wagers per capita (Lottery). X is N \times 7 with an intercept, the Literacy and Wealth variables, and 4 region binary variables.
The patsy module provides a convenient function to prepare design matrices using R-like formulas. You can find more information here: http://patsy.readthedocs.org
We use patsy‘s dmatrices function to create design matrices:
In [1]: y, X = dmatrices('Lottery ~ Literacy + Wealth + Region', data=df, return_type='dataframe')
The resulting matrices/data frames look like this:
In [1]: y[:3]
In [1]: X[:3]
Notice that dmatrices has
The above behavior can of course be altered. See the patsy doc pages.
Fitting a model in statsmodels typically involves 3 easy steps:
For OLS, this is achieved by:
In [1]: mod = sm.OLS(y, X) # Describe model
In [1]: res = mod.fit() # Fit model
In [1]: print res.summary() # Summarize model
The res object has many useful attributes. For example, we can extract parameter estimates and r-squared by typing:
In [1]: res.params
In [1]: res.rsquared
Type dir(res) for a full list of attributes.
For more information and examples, see the Regression doc page
statsmodels allows you to conduct a range of useful regression diagnostics and specification tests. For instance, apply the Rainbow test for linearity (the null hypothesis is that the relationship is properly modelled as linear):
In [1]: sm.stats.linear_rainbow(res)
Admittedly, the output produced above is not very verbose, but we know from reading the docstring (also, print sm.stats.linear_rainbow.__doc__) that the first number is an F-statistic and that the second is the p-value.
statsmodels also provides graphics functions. For example, we can draw a plot of partial regression for a set of regressors by:
In [1]: from statsmodels.graphics.regressionplots import plot_partregress
In [1]: plot_partregress(res)
Congratulations! You’re ready to move on to other topics in the Table of Contents