### `statsmodels.api.OLS(endog, exog=None, missing='none', hasconst=None, **kwargs)`

Ordinary Least Squares

Parameters
----------
endog : array_like
A 1-d endogenous response variable. The dependent variable.
exog : array_like
A nobs x k array where `nobs` is the number of observations and `k`
is the number of regressors. An intercept is not included by default
and should be added by the user. See
:func:`statsmodels.tools.add_constant`.
missing : str
Available options are 'none', 'drop', and 'raise'. If 'none', no nan
checking is done. If 'drop', any observations with nans are dropped.
If 'raise', an error is raised. Default is 'none'.
hasconst : None or bool
Indicates whether the RHS includes a user-supplied constant. If True,
a constant is not checked for and k_constant is set to 1 and all
result statistics are calculated as if a constant is present. If
False, a constant is not checked for and k_constant is set to 0.
**kwargs
Extra arguments that are used to set model properties when using the
formula interface.

Attributes
----------
weights : scalar
Has an attribute weights = array(1.0) due to inheritance from WLS.

See Also
--------
WLS : Fit a linear model using Weighted Least Squares.
GLS : Fit a linear model using Generalized Least Squares.

Notes
-----
No constant is added by the model unless you are using formulas.

Examples
--------
> > > import statsmodels.api as sm
> > > import numpy as np
> > > duncan_prestige = sm.datasets.get_rdataset("Duncan", "carData")
> > > Y = duncan_prestige.data['income']
> > > X = duncan_prestige.data['education']
> > > X = sm.add_constant(X)
> > > model = sm.OLS(Y,X)
> > > results = model.fit()
> > > results.params
> > > const 10.603498
> > > education 0.594859
> > > dtype: float64

> > > results.tvalues
> > > const 2.039813
> > > education 6.892802
> > > dtype: float64

> > > print(results.t_test([1, 0]))
> > > Test for Constraints
> > > ==============================================================================
> > > coef std err t P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
c0            10.6035      5.198      2.040      0.048       0.120      21.087
==============================================================================

> > > print(results.f_test(np.identity(2)))
<F test: F=array([[159.63031026]]), p=1.2607168903696672e-20,
> > > df_denom=43, df_num=2>

---

### `statsmodels.api.Logit(endog, exog, offset=None, check_rank=True, **kwargs)`

Logit Model

Parameters
----------
endog : array_like
A 1-d endogenous response variable. The dependent variable.
exog : array_like
A nobs x k array where `nobs` is the number of observations and `k`
is the number of regressors. An intercept is not included by default
and should be added by the user. See
:func:`statsmodels.tools.add_constant`.
offset : array_like
Offset is added to the linear prediction with coefficient equal to 1.
missing : str
Available options are 'none', 'drop', and 'raise'. If 'none', no nan
checking is done. If 'drop', any observations with nans are dropped.
If 'raise', an error is raised. Default is 'none'.
check_rank : bool
Check exog rank to determine model degrees of freedom. Default is
True. Setting to False reduces model initialization time when
exog.shape[1] is large.


Attributes
----------
endog : ndarray
A reference to the endogenous response variable
exog : ndarray
A reference to the exogenous design.

---

###
`statsmodels.graphics.tsaplots.plot_acf(x, ax=None, lags=None, *, alpha=0.05, use_vlines=True, adjusted=False, fft=False, missing='none', title='Autocorrelation', zero=True, auto_ylims=False, bartlett_confint=True, vlines_kwargs=None, **kwargs)`

Plot the autocorrelation function

Plots lags on the horizontal and the correlations on vertical axis.

Parameters
----------
x : array_like
Array of time-series values
ax : AxesSubplot, optional
If given, this subplot is used to plot in instead of a new figure being
created.
lags : {int, array_like}, optional
An int or array of lag values, used on horizontal axis. Uses
np.arange(lags) when lags is an int. If not provided,
``lags=np.arange(len(corr))`` is used.
alpha : scalar, optional
If a number is given, the confidence intervals for the given level are
returned. For instance if alpha=.05, 95 % confidence intervals are
returned where the standard deviation is computed according to
Bartlett's formula. If None, no confidence intervals are plotted.
use_vlines : bool, optional
If True, vertical lines and markers are plotted.
If False, only markers are plotted. The default marker is 'o'; it can
be overridden with a ``marker`` kwarg.
adjusted : bool
If True, then denominators for autocovariance are n-k, otherwise n
fft : bool, optional
If True, computes the ACF via FFT.
missing : str, optional
A string in ['none', 'raise', 'conservative', 'drop'] specifying how
the NaNs are to be treated.
title : str, optional
Title to place on plot. Default is 'Autocorrelation'
zero : bool, optional
Flag indicating whether to include the 0-lag autocorrelation.
Default is True.
auto_ylims : bool, optional
If True, adjusts automatically the y-axis limits to ACF values.
bartlett_confint : bool, default True
Confidence intervals for ACF values are generally placed at 2
standard errors around r_k. The formula used for standard error
depends upon the situation. If the autocorrelations are being used
to test for randomness of residuals as part of the ARIMA routine,
the standard errors are determined assuming the residuals are white
noise. The approximate formula for any lag is that standard error
of each r_k = 1/sqrt(N). See section 9.4 of [1] for more details on
the 1/sqrt(N) result. For more elementary discussion, see section
5.3.2 in [2].
For the ACF of raw data, the standard error at a lag k is
found as if the right model was an MA(k-1). This allows the
possible interpretation that if all autocorrelations past a
certain lag are within the limits, the model might be an MA of
order defined by the last significant autocorrelation. In this
case, a moving average model is assumed for the data and the
standard errors for the confidence intervals should be
generated using Bartlett's formula. For more details on
Bartlett formula result, see section 7.2 in [1].
vlines_kwargs : dict, optional
Optional dictionary of keyword arguments that are passed to vlines.
**kwargs : kwargs, optional
Optional keyword arguments that are directly passed on to the
Matplotlib ``plot`` and ``axhline`` functions.

Returns
-------
Figure
If `ax` is None, the created figure. Otherwise the figure to which
`ax` is connected.

See Also
--------
matplotlib.pyplot.xcorr
matplotlib.pyplot.acorr

Notes
-----
Adapted from matplotlib's `xcorr`.

Data are plotted as ``plot(lags, corr, **kwargs)``

kwargs is used to pass matplotlib optional arguments to both the line
tracing the autocorrelations and for the horizontal line at 0. These
options must be valid for a Line2D object.

vlines_kwargs is used to pass additional optional arguments to the
vertical lines connecting each autocorrelation to the axis. These options
must be valid for a LineCollection object.

References
----------
[1] Brockwell and Davis, 1987. Time Series Theory and Methods
[2] Brockwell and Davis, 2010. Introduction to Time Series and
Forecasting, 2nd edition.

Examples
--------
> > > import pandas as pd
> > > import matplotlib.pyplot as plt
> > > import statsmodels.api as sm

> > > dta = sm.datasets.sunspots.load_pandas().data
> > > dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
> > > del dta["YEAR"]
> > > sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40)
> > > plt.show()

.. plot:: plots/graphics_tsa_plot_acf.py

---

### `statsmodels.stats.diagnostic.het_breuschpagan(resid, exog_het, robust=True)`

Breusch-Pagan Lagrange Multiplier test for heteroscedasticity

The tests the hypothesis that the residual variance does not depend on
the variables in x in the form

.. :math: \sigma_i = \sigma * f(\alpha_0 + \alpha z_i)

Homoscedasticity implies that :math:`\alpha=0`.

Parameters
----------
resid : array_like
For the Breusch-Pagan test, this should be the residual of a
regression. If an array is given in exog, then the residuals are
calculated by the an OLS regression or resid on exog. In this case
resid should contain the dependent variable. Exog can be the same as x.
exog_het : array_like
This contains variables suspected of being related to
heteroscedasticity in resid.
robust : bool, default True
Flag indicating whether to use the Koenker version of the
test (default) which assumes independent and identically distributed
error terms, or the original Breusch-Pagan version which assumes
residuals are normally distributed.

Returns
-------
lm : float
lagrange multiplier statistic
lm_pvalue : float
p-value of lagrange multiplier test
fvalue : float
f-statistic of the hypothesis that the error variance does not depend
on x
f_pvalue : float
p-value for the f-statistic

Notes
-----
Assumes x contains constant (for counting dof and calculation of R^2).
In the general description of LM test, Greene mentions that this test
exaggerates the significance of results in small or moderately large
samples. In this case the F-statistic is preferable.

**Verification**

Chisquare test statistic is exactly (<1e-13) the same result as bptest
in R-stats with defaults (studentize=True).

**Implementation**

This is calculated using the generic formula for LM test using $R^2$
(Greene, section 17.6) and not with the explicit formula
(Greene, section 11.4.3), unless `robust` is set to False.
The degrees of freedom for the p-value assume x is full rank.

References
----------
.. [1] Greene, W. H. Econometric Analysis. New Jersey. Prentice Hall;
5th edition. (2002).
.. [2]  Breusch, T. S.; Pagan, A. R. (1979). "A Simple Test for
Heteroskedasticity and Random Coefficient Variation". Econometrica.
47 (5): 1287û1294.
.. [3] Koenker, R. (1981). "A note on studentizing a test for
heteroskedasticity". Journal of Econometrics 17 (1): 107û112.

---

### `statsmodels.api.add_constant(data, prepend=True, has_constant='skip')`

Add a column of ones to an array.

Parameters
----------
data : array_like
A column-ordered design matrix.
prepend : bool
If true, the constant is in the first column. Else the constant is
appended (last column).
has_constant : str {'raise', 'add', 'skip'}
Behavior if ``data`` already has a constant. The default will return
data without adding another constant. If 'raise', will raise an
error if any column has a constant value. Using 'add' will add a
column of 1s if a constant column is present.

Returns
-------
array_like
The original values with a constant (column of ones) as the first or
last column. Returned value type depends on input type.

Notes
-----
When the input is a pandas Series or DataFrame, the added column's name
is 'const'.

---

### `statsmodels.formula.api.ols(formula, data, subset=None, drop_cols=None, *args, **kwargs)`

Create a Model from a formula and dataframe.

Parameters
----------
formula : str or generic Formula object
The formula specifying the model.
data : array_like
The data for the model. See Notes.
subset : array_like
An array-like object of booleans, integers, or index values that
indicate the subset of df to use in the model. Assumes df is a
`pandas.DataFrame`.
drop_cols : array_like
Columns to drop from the design matrix. Cannot be used to
drop terms involving categoricals.
*args
Additional positional argument that are passed to the model.
**kwargs
These are passed to the model with one exception. The
``eval_env`` keyword is passed to patsy. It can be either a
:class:`patsy:patsy.EvalEnvironment` object or an integer
indicating the depth of the namespace to use. For example, the
default ``eval_env=0`` uses the calling namespace. If you wish
to use a "clean" environment set ``eval_env=-1``.

Returns
-------
model
The model instance.

Notes
-----
data must define __getitem__ with the keys in the formula terms
args and kwargs are passed on to the model instantiation. E.g.,
a numpy structured or rec array, a dictionary, or a pandas DataFrame.

---

### `statsmodels.stats.anova.anova_lm(*args, **kwargs)`

Anova table for one or more fitted linear models.

Parameters
----------
args : fitted linear model results instance
One or more fitted linear models
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
typ : str or int {"I","II","III"} or {1,2,3}
The type of Anova test to perform. See notes.
robust : {None, "hc0", "hc1", "hc2", "hc3"}
Use heteroscedasticity-corrected coefficient covariance matrix.
If robust covariance is desired, it is recommended to use `hc3`.

Returns
-------
anova : DataFrame
When args is a single model, return is DataFrame with columns:

    sum_sq : float64
        Sum of squares for model terms.
    df : float64
        Degrees of freedom for model terms.
    F : float64
        F statistic value for significance of adding model terms.
    PR(>F) : float64
        P-value for significance of adding model terms.

    When args is multiple models, return is DataFrame with columns:

    df_resid : float64
        Degrees of freedom of residuals in models.
    ssr : float64
        Sum of squares of residuals in models.
    df_diff : float64
        Degrees of freedom difference from previous model in args
    ss_dff : float64
        Difference in ssr from previous model in args
    F : float64
        F statistic comparing to previous model in args
    PR(>F): float64
        P-value for significance comparing to previous model in args

Notes
-----
Model statistics are given in the order of args. Models must have been fit
using the formula api.

See Also
--------
model_results.compare_f_test, model_results.compare_lm_test

Examples
--------
> > > import statsmodels.api as sm
> > > from statsmodels.formula.api import ols
> > > moore = sm.datasets.get_rdataset("Moore", "carData", cache=True) # load
> > > data = moore.data
> > > data = data.rename(columns={"partner.status" :
> > > ...                             "partner_status"}) # make name pythonic
> > > moore_lm = ols('conformity ~ C(fcategory, Sum)*C(partner_status, Sum)',
> > > ... data=data).fit()
> > > table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 Anova DataFrame
> > > print(table)

---
